Spencer Christensen Site Reliability Engineer

Using sshpass to ssh to a host with a password automatically

Most times you want to automate an ssh connection to a host you would think of using ssh public/private keys. And well you should; they are the best way to access a host without using passwords. However there are sometimes when you are not able to use keys, such as logging into a switch, router, blade chassis, or other device that doesn't support the use of keys. What are you to do to automate ssh connections to them?
Some may look to using expect, and that is fine. But expect can be complicated to learn and get right. There is a simpler solution: sshpass.
You may need to install the sshpass package for your Linux distro (yum install sshpass, apt-get install sshpass).
Then you can run:
sshpass -p$PASS ssh $user@$host $command
OR
sshpass -e ssh $user@$host $command
In the first example you provide the password in the $PASS variable in the command line. This may or maynot be a problem depending on how you are entering the command.
In the second example you first need to export SSHPASS="$PASS" and then the -e option uses this env variable for the password.