How to Supply SSH Password in SSH Command

Setting up RSA keys for passwordless SSH is the most secure way to avoid being prompted for a password when connecting to a remote host with SSH. However, you can also supply the SSH password in the SSH command itself with the sshpass utility.

Using sshpass

We’d be remiss not to warn you that typing your SSH password in a terminal command is not very secure. As risky as it may seem, though, there are still scenarios where it’s useful and doesn’t present a security risk. Without further ado, here’s how it’s done.

You’ll need to install the sshpass utility from your distribution’s package manager. On Ubuntu and other Debian based distributions, you’d use this command:

sudo apt install sshpass

Once sshpass is installed, issue your SSH command with this syntax:

sshpass -p 'password' user@hostname

Replace password with your user’s password, but keep the single quotes around it.

This command should work with any utility that uses SSH, such as rsync. Just precede any command with the sshpass command.

sshpass -p 'password' rsync -av -e ssh /dir1/ user@hostname:/path/to/dir/

Note that the command won’t work unless you’ve already added the remote host to the ~/.ssh/known_hosts file. In other words, make sure you login the normal way at least once so you can type yes at this prompt:

Accepting a SSH hosts fingerprint

Once you’ve typed yes, the host is added to known_hosts and sshpass will work correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *