364

How to automate SSH login with password? I'm configuring my test VM, so heavy security is not considered. SSH chosen for acceptable security with minimal configuration.

ex)

echo password | ssh id@server

This doesn't work.

I remember I did this with some tricks somebody guided me, but I can't remember now the trick I used...

338

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.

  • 11
    I finally decided using key pairs. Because I realized that's the most simple way. – Eonil Mar 1 '11 at 12:49
  • 8
    @Eonil: Don't be tempted to use keys without a pass phrase. Learn how to use ssh-agent or pageant. – Iain Mar 1 '11 at 13:20
  • 97
    This is a good answer, but not the correct answer to the question. – John Hunt Jul 4 '13 at 13:34
  • 56
    These kinds of answers really, really annoy me. That wasn't the question. Nobody asked how to use key pairs. – Matt Fletcher Jun 16 '16 at 12:41
  • 10
    This does not answer the question. It is a good answer for a completely different question, but it is terrible for the one asked. – srchulo Jan 4 '17 at 20:42
534
$ sudo apt-get install sshpass
$ sshpass -p your_password ssh user@hostname
  • 42
    Yup, sometimes you can't use key based auth for various reasons.. for example right now I can't use keyauth on a plesk server because out the box it's not enabled and I don't have root. – John Hunt Jul 4 '13 at 13:33
  • 13
    +1! As a side note, you need to run plain ssh once before using sshpass, in order to confirm the RSA fingerprint – user123444555621 Aug 2 '13 at 8:08
  • 16
    -1 for having to use the password in the command. This logs the password at .bash_history in plain text on your machine. – user164495 Apr 11 '14 at 21:18
  • 11
    @MisterDood You could run history -r after the command to erase your history. Good point though. – NuclearPeon May 14 '15 at 18:37
  • 11
    Pro tip: If you don't want to have a specific command show up in .bash_history, prefix the command with a space. It just works. However, users of this command should be more concerned that non-privileged users on the system can see the full command-line with ps, which, of course, includes the password. Since ssh sessions tend to be long-lived, this is a security issue. – CubicleSoft Jul 16 '16 at 15:47
62

While the correct answer for your question is sshkey, there is a more secure way - SSH keys. You are just three easy steps away from the solution:

Generate a rsa keypair:

# ssh-keygen

then copy it on the server with one simple command:

# ssh-copy-id userid@hostname

you can now log in without password:

# ssh userid@hostname
  • Works fine with the default values. Using ~/rsa4live.pub didn't work for me when attempting ssh-copy-id. – Cees Timmerman Jun 4 '15 at 10:08
  • If you want this steps to work for different user, 1. ssh-keygen 2. ssh-copy-id nazir@hostname 3. ssh nazir@hostname – Venfah Nazir Jun 17 '16 at 10:23
  • 1
    For me it was ssh-copy-id -i ~/.ssh/tatu-key-ecdsa user@host – Gabriel Fair Sep 8 '17 at 21:47
  • 14
    This isn't an answer to the question. – Steve Bennett Nov 27 '17 at 23:10
  • And? The answer is above, sshpass... – lzap Nov 30 '17 at 16:21
32

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
  • 1
    It worked but it can't print stdout of remote machine. – Eonil Mar 1 '11 at 12:41
  • it works well for some machine can't put the key in advance since IP address is changed everytime. – larrycai Dec 19 '12 at 6:14
  • 4
    it will be good to add -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null for ssh command as well to avoid accept the machine into known_hosts – larrycai Dec 19 '12 at 6:15
  • B.. b but muh ssh keys... – Damien Ó Ceallaigh Jun 1 '17 at 5:50
  • More detailed example of this script you can find at: linuxaria.com/howto/… This examples here should work with remote commands too – Radon8472 Jul 11 '18 at 13:39
13

This might not be any use to you, but you can do it with Perl:

\#!/usr/bin/perl  
use warnings;  
use strict;  

use Net::SSH::Perl;  
my $host = 'remote.serv.er';  
my $user = 'root';  
my $pass = 'hunter2';  
my $ssh = Net::SSH::Perl->new('$host');  
$ssh->login('$user', '$pass') or die "Oh noes! $!";
9

Sure you don't want to use SSH keys rather than passwords? That way it's both secure and automatic.

  • 3
    Using SSH keys without password is only slightly more secure than using passwords in a file. – yunzen Apr 14 '15 at 7:34
  • 9
    @yunzen Incorrect. Key authentication protects you from mitm-attacks even if you don't know the host key. An attacker could impersonate the server, but never connect to the real server. With password authentication any server you connect to (legitimate or not) will see the password. For those reasons an ssh key without password is a lot more secure than just storing the password in a file. – kasperd May 17 '16 at 7:15
  • 8
    This is not an answer. – Steve Bennett Nov 27 '17 at 23:10
  • @SteveBennett It's the same as the accepted answer and was posted before it, though it has less detail. – Michael Hampton Aug 4 '18 at 14:34
  • Well, I'd say the accepted answer is a decent answer to a question that wasn't asked. This isn't anything. – Steve Bennett Aug 6 '18 at 6:24
9

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.

  • For windows your answer is good, unfurtunally linux / unix user usually dont have plink – Radon8472 Jul 11 '18 at 13:48
  • 1
    it is in the putty-tools package – eadmaster Sep 14 '18 at 16:14
2

SSH single sign-on is usually achieved with public key authentication and an authentication agent. You could easily add your test VM key to an existing auth agent (see example below). Other methods such as gssapi/kerberos exist but are more complex.

sshpass

In situations where password is the only authentication method available, sshpass can be used to automatically enter the password. Please pay particular attention to the SECURITY CONSIDERATIONS section of the man page. In all three options, the password is visible or stored in plaintext at some point:

Anonymous pipe (recommended by sshpass)

# Create a pipe
PIPE=$(mktemp -u)
mkfifo -m 600 $PIPE
# Attach it to file descriptior 3
exec 3<>$PIPE
# Delete the directory entry
rm $PIPE
# Write your password in the pipe
 echo 'my_secret_password' >&3
# Connect with sshpass -d
sshpass -d3 ssh user@host

# Close the pipe when done
exec 3>&-

It is quite cumbersome in bash, arguably easier with programming languages. Another process could attach to your pipe/fd before the password is written. The window of opportunity is quite short and limited to your processes or root.

Environment variable

# Set your password in an environment variable
 export SSHPASS='my_secret_password'
# Connect with sshpass -e
sshpass -e ssh user@host

You and root can read your process' environment variables (i.e. your password) while sshpass is running (cat /proc/<pid>/environ | tr '\0' '\n' | grep ^SSHPASS=). The window of opportunity is much longer but still limited to your own processes or root, not other users.

Command-line argument (least secure)

 sshpass -p my_secret_password ssh user@host

This is convenient but less secure as described in the man page. Command line arguments are visible to all users (e.g. ps -ef | grep sshpass). sshpass attempts to hide the argument, but there is still a window during which all users can see your password passed by argument.

Side note

Set your bash HISTCONTROL variable to ignorespace or ignoreboth and prefix your sensitive commands with a space. They won't be saved in history.


SSH public key authentication

# Generate a key pair
# Do NOT leave the passphrase empty
ssh-keygen
# Copy it to the remote host (added to .ssh/authorized_keys)
ssh-copy-id user@host

The passphrase is very important. Anyone somehow obtaining the private key file won't be able to use it without the passphrase.

Setup the SSH authentication agent

# Start the agent
eval `ssh-agent`
# Add the identity (private key) to the agent
ssh-add /path/to/private-key
# Enter key passphrase (one time only, while the agent is running)

Connect as usual

ssh user@host

The advantage is that your private key is encrypted and you only need to enter its passphrase once (via a safer input method too).

1

Depending on your automation needs, perhaps Ansible would be a good fit for you. It can nicely manage things like prompting for password, prompting for sudo password, various ways of changing use, securely using encrypted secrets (vault).

If that’s not suitable, I would suggest Expect, as suggested in another answer.

protected by Tom O'Connor Jan 2 '14 at 13:27

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.