How to automate SSH logins if you need a password – CloudSavvy IT

How to automate SSH logins if you need a password – CloudSavvy IT

Bash Shell

SSH does not have an easy way to send passwords over standard input, making it difficult to automate. Although not ideal for security, you can automate SSH password authentication in bash scripts using sshpass utility value.

Before we begin – using automated passwords for SSH is considered a bad practice for a reason. In almost all cases, it is better to use an SSH key, which we will show below. However, passwords have the advantage of being easier to manage, remember, and distribute to team members. These are all safety disadvantages at the same time, but it is a trade-off you can choose to make.

Using SSHPass

The ordinary ssh the command does not have one --password flag so you can easily automate this. You will need to install a tool called sshpass to deal with this explicitly. You can download it from most Linux package managers; for Debian-based systems like Ubuntu, it would be:

sudo apt-get install sshpass

If you use sshpass inside a script file you can pass it directly with -p flag, followed by your default SSH command:

sshpass -p 'password' ssh user@remote

However, this is not good practice for a few reasons:

  • Used outside of a script file, it exposes the plain text password for Linux command history and other systems. Other Linux users may see this.
  • It may be unclear that there is a password buried in this script file, which could potentially lead to bad file permissions revealing it.
  • It can be accidentally tracked in version control and does not allow changing the password used on the clients.

Because of this, you should save the password in a file instead. Be sure to set the permissions for it to ensure that it is not accessible to other users.

echo "password" > password_file
chmod 600 password_file

Then pass this on to sshpass with -f:

sshpass -f password_file ssh user@remote

Setting up SSH keys instead

SSH keys are preferred for most systems. They are much longer, as well as harder to leak accidentally, making them ideal for safety. They also encourage identity-based authentication, as SSH keys are usually associated with the machine on which they were created.

SSH stores your public key in ~/.ssh/, which it uses for all requests. Generating a new key file is easy:


You need to add this to ~/.ssh/authorized_keys file on the server you want to connect to. There is a built-in SSH command that can easily do this for you:

ssh-copy-id -i ~/.ssh/ user@host

Once done, you will not be prompted for a password again. You can copy this key to other machines, but usually it’s fine to just add more keys.

You will still disable password logins on the remote server and probably configure speed limit, whitelist or even two-factor authentication. You can read our guide to securing an SSH-accessible machine to learn more.

RELATED: How to lock your SSH server

Leave a Comment