Securely connect to a Linux server with putty and ssh key

First you need to download PuTTY and PuTTYgen from the PuTTY Download Page.

Then start puttygen:

Open puttygen

Make sure the type of key to generate is SSH-2 RSA and click on the Generate button:

puttygen generate key

As instructed, you’ll have to move the mouse randomly over the grey area. After some moving around, the key will be generated:

puttygen key generated

Now copy the key from the "Public key for pasting into OpenSSH authorized_keys file" text area. We’ll add it as an authorized key for the user on the Linux machine.

Now login to the Linux server (e.g. using putty) and type the following:

cd $HOME/.ssh
vi authorized_keys

If there are no keys defined for this user yet, the file will be created, otherwise there will already be entries in this file.
Press I to enter insert mode, if it’s not the first key you’ll have to add a newline here, then paste the copied key. Press :wq for saving and exiting.

If the file was newly created, we’ll need to make sure that only the current user can write in this file:

chmod g-w $HOME $HOME/.ssh $HOME/.ssh/authorized_keys

Now, in case it’s not already done, we’ll need to allow public keys as an authentication mechanism for ssh:

vi /etc/ssh/sshd_config

There make sure the lines are in there:

  • PubkeyAuthentication yes
  • AuthorizedKeysFile .ssh/authorized_keys

These lines are most probably in there but commented out. In this case just remove the hash sign before them.

If you also want to completely disable password based authentication (e.g. only use public keys), you can also set the following:

  • ChallengeResponseAuthentication no
  • PasswordAuthentication no
  • UsePAM no

If you’re afraid to do something wrong, you can also set these 3 parameters later on.
Then press :wq to save.

Then restart your ssh daemon to activate the new settings using one of the following commands (depending on your system):

rcsshd restart

service sshd restart

service ssh restart

/etc/rc.d/sshd restart

/etc/init.d/sshd restart

We’re done on the linux side. Let’s go back to puttygen. You can define now a passphrase if you want (it’s optional). Then press "Save private key" and choose an appropriate location on the disk. Now you can open putty:

putty

Type in the user name and host name or the IP address of the Linux server (e.g. root@192.168.190.157), then open the SSH node in the tree on the left hand side, then click on Auth:

putty ssh auth

Click on Browse and choose the private key file you’ve saved using puttygen.
Then click again on Session (at the top of the tree on the left hand side). Give the connection a name (in Saved Sessions) and press Save:

putty session saved

Now you can press Open and will be automatically logged in !

Leave a Reply

Your email address will not be published. Required fields are marked *