SSH does not have an easy way to send passwords over standard input, making it hard to automate. While it’s not ideal for security, you can automate SSH password authentication in bash scripts using the sshpass utility.

Before we begin—using automated passwords for SSH is considered bad practice for a reason. In almost all cases, it’s better to use an SSH key, which we will show below. However, passwords do have the benefit of being easier to manage, remember, and distribute to team members. Those are all simultaneously downsides for security, but that’s a tradeoff you may choose to make.

Using SSHPass

The regular ssh command does not have a –password flag to allow you to automate this easily. You will have to install a tool called sshpass to handle this explicitly. You can download it from most Linux package managers; for Debian based systems like Ubuntu, that would be:

If you’re using sshpass from inside a script file, you can pass it in directly with the -p flag, followed by your standard SSH command:

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

If used outside of a script file, it exposes the plaintext password to Linux command history and other systems. Other Linux users may be able to see it. It may be unclear that there is a password buried in this script file, potentially leading to bad file permissions exposing it. It may be accidentally tracked in version control, and doesn’t allow changing of the password used on the clients.

Because of this, you should store the password in a file instead. Make sure to set the permissions on it to ensure it’s not accessible by other users.

Then, pass this to sshpass with -f:

Setting Up SSH Keys Instead

SSH keys are preferred for most systems. They’re much longer, as well as harder to accidentally leak, making them ideal for security. They also encourage identity based authentication, since SSH keys are usually tied to the machine they’re created on.

SSH stores your public key in ~/.ssh/id_rsa.pub, which it uses for all requests. It’s easy to generate a new key file:

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

Once that’s done, you won’t be asked for a password anymore. You can copy this key to other machines, but usually it’s fine to just add multiple keys.

You’ll still want to disable password logins on the remote server, and probably set up rate limiting, whitelisting, or even two factor authentication. You can read our guide to securing an SSH accessible machine to learn more.

RELATED: How to Lock Down Your SSH Server