How to automate SSH login with password?
Solution 1:
$ sudo apt-get install sshpass
$ sshpass -p your_password ssh user@hostname
Solution 2:
Don't use a password. Generate a passphraseless SSH key and push it to your VM.
If you already have an SSH key, you can skip this step… Just hit Enter for the key and both passphrases:
$ ssh-keygen -t rsa -b 2048
Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/username/.ssh/id_rsa.
Your public key has been saved in /home/username/.ssh/id_rsa.pub.
Copy your keys to the target server:
$ ssh-copy-id id@server
id@server's password:
Now try logging into the machine, with ssh 'id@server'
, and check in:
.ssh/authorized_keys
to make sure we haven’t added extra keys that you weren’t expecting.
Finally check logging in…
$ ssh id@server
id@server:~$
You may also want to look into using ssh-agent
if you want to try keeping your keys protected with a passphrase.
Solution 3:
While the correct answer for your question is sshpass (see other answer for details), there is a more secure way - SSH keys. You are just three easy steps away from the solution:
All the following commands are being run on the client side, i.e. your machine
Enter the following command to start generating a rsa keypair:
# ssh-keygen
When the message 'Enter file in which to save the key' appears, just leave the filename blank by pressing Enter.
When the terminal asks you to enter a passphrase, just leave this blank too and press Enter.
Then copy the keypair onto the server with one simple command:
# ssh-copy-id userid@hostname
you can now log in without a password:
# ssh userid@hostname
Solution 4:
Use expect:
#!/usr/bin/expect -f
# ./ssh.exp password 192.168.1.11 id
set pass [lrange $argv 0 0]
set server [lrange $argv 1 1]
set name [lrange $argv 2 2]
spawn ssh $name@$server
match_max 100000
expect "*?assword:*"
send -- "$pass\r"
send -- "\r"
interact
Example:
# ./1.ex password localhost ooshro
spawn ssh ooshro@localhost
ooshro@localhost's password:
Linux ubuntu-1010-server-01 2.6.35-25-generic-pae #44-Ubuntu SMP Fri Jan 21 19:01:46 UTC 2011 i686 GNU/Linux
Ubuntu 10.10
Welcome to Ubuntu!
* Documentation: https://help.ubuntu.com/
Last login: Tue Mar 1 12:41:12 2011 from localhost
Solution 5:
I am surprised nobody mentioned plink
from the putty-tools
package in Ubuntu:
plink user@domain -pw mypass [cmd]
It also available on Windows and the syntax is mostly compatible with the openssh client.