Friday, 9 December 2016

Quick and Dirty Tutorial: SSH login without a password

The Goal

 Connect from host A to host B without having to enter a password.

The Solution

There are a number of methods of doing this, however this is by far the simplest. The account you are connect to does not need to be the same name or UUID.

Step 1 - Generate a pair of authentication keys.

On host A, generate your RSA keys using ssh-keygen. Defaults are fine.

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/<UserA>/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/<UserA>/.ssh/id_rsa.
Your public key has been saved in /home/<UserA>/.ssh/id_rsa.pub.
The key fingerprint is:
5a:f6:ef:ac:30:86:27:b0:36:22:ca:c8:92:f0:37:88 <userA>@<HostA>
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|                 |
|                 |
|                 |
|    .   S        |
|.    o = .       |
|o+..+ + = .      |
|E.ooo. + o o     |
|+o . .    .o+    |
+-----------------+

Step 2a - Copy public key to host B using ssh-copy-id

$ ssh-copy-id <userB>@<HostB>
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
<userB>@<HostB> password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '<userB>@<HostB>'"
and check to make sure that only the key(s) you wanted were added.

$ ssh <userB>@<HostB>
<userB>@<HostB>:~$

If this method doesn't work, try the alternate:

Step 2b - Copy public key to host B using ssh

$ ssh <userB>@<HostB> mkdir -p .ssh
password:
$ cat .ssh/id_rsa.pub | ssh <userB>@<HostB> 'cat >> .ssh/authorized_keys'
password:
$ ssh <userB>@<HostB>
<userB>@<HostB>:~$

---

Voila! No longer will you need to enter a password when connecting to host B from host A between these two user accounts, a key exchange will happen instead.

For additional servers, skip step 1 - you can re-use the same key.

If you want to use a pass phrase, you may need to setup an environment variable so that ssh can find your keys by placing the following script into your .bash_profile:
 
if [ -z "$SSH_AUTH_SOCK" ] ; then
    eval `ssh-agent -s`
    ssh-add
fi





No comments:

Post a Comment