OpenSSH and password-less logins

Using SSH you can run commands at remote servers.

By default the remote server will ask for credentials but for instance when writing a script it is not a good idea to store the login credentials in a script.
The solution to this is to create a key pair at the origin machine (where the script is) and then send this key to the remoteserver (where the script needs to login).

  • First create a key pair (only has to be done once for this machine; it can be reused for other machines if you wish to be able to login to several computers)
     jonas@jonas-desktop:~$ ssh-keygen
    Generating public/private rsa key pair.
    Enter file in which to save the key (/home/jonas/.ssh/id_rsa): 
    Enter passphrase (empty for no passphrase): 
    Enter same passphrase again: 
    Your identification has been saved in /home/jonas/.ssh/id_rsa.
    Your public key has been saved in /home/jonas/.ssh/
    The key fingerprint is:
    11:f9:5a:8f:7d:74:e4:68:3b:4b:22:1c:78:e6:be:2d jonas@jonas-desktop
    The key's randomart image is:
    +--[ RSA 2048]----+
    |        ..       |
    |        ..      .|
    |        .o     + |
    |        ..*   + o|
    |        SB = o o |
    |        . = + =  |
    |         . . + o |
    |          E.  .  |
    |          .o.    |

    Passphrase is needed to “unlock” this key before being able to use it. Leaving passphrase blank means that the key can be used without any inputs.

  • Next send the key to the server that you wish to be able to login to.
     jonas@jonas-desktop:~$ ssh-copy-id -i .ssh/ user@remoteserver
    Warning: Permanently added 'remoteserver,11.222.333.222' (RSA) to the list of known hosts.
    user@remoteserver's password: 
    Now try logging into the machine, with "ssh 'user@remoteserver'", and check in:
    to make sure we haven't added extra keys that you weren't expecting.

    -i is the identity file we created with ssh-keygen

  • This is it. Now you are able to login to remoteserver as user without a password.