Automatically enter SSH password with script
I need to create a script that automatically inputs a password to OpenSSH ssh
client.
Let's say I need to SSH into myname@somehost
with the password a1234b
.
I've already tried...
#~/bin/myssh.sh
ssh myname@somehost
a1234b
...but this does not work.
How can I get this functionality into a script?
First you need to install sshpass.
- Ubuntu/Debian:
apt-get install sshpass
- Fedora/CentOS:
yum install sshpass
- Arch:
pacman -S sshpass
Example:
sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM
Custom port example:
sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM:2400
Notes:
-
sshpass
can also read a password from a file when the-f
flag is passed.- Using
-f
prevents the password from being visible if theps
command is executed. - The file that the password is stored in should have secure permissions.
- Using
After looking for an answer to the question for months, I finally found a better solution: writing a simple script.
#!/usr/bin/expect
set timeout 20
set cmd [lrange $argv 1 end]
set password [lindex $argv 0]
eval spawn $cmd
expect "password:"
send "$password\r";
interact
Put it to /usr/bin/exp
, So you can use:
exp <password> ssh <anything>
exp <password> scp <anysrc> <anydst>
Done!
Use public key authentication: https://help.ubuntu.com/community/SSH/OpenSSH/Keys
In the source host run this only once:
ssh-keygen -t rsa # ENTER to every field
ssh-copy-id myname@somehost
That's all, after that you'll be able to do ssh without password.
You could use an expects script. I have not written one in quite some time but it should look like below. You will need to head the script with #!/usr/bin/expect
#!/usr/bin/expect -f
spawn ssh HOSTNAME
expect "login:"
send "username\r"
expect "Password:"
send "password\r"
interact
Variant I
sshpass -p PASSWORD ssh USER@SERVER
Variant II
#!/usr/bin/expect -f
spawn ssh USERNAME@SERVER "touch /home/user/ssh_example"
expect "assword:"
send "PASSWORD\r"
interact