Ssh with keys for authentication

This will show you how to use ssh with keys for authentication. this has a couple of advantages over using passwords:

1) you can enable key only logins.
2) you dont need to type [or remember] passwords

You will need two machines (though you probably know this already):

  • remotehost.com – the remote machine that you want to log in to
  • yourmachine.local – your local machine that you want to log into remotehost.com from

Generating your key

on yourmachine.local open a terminal and type:

ssh-keygen

it will ask you a few questions and will ask for a password. you could enter one, or you could leave it blank. if you are on a mac it will remember what ever you use, so its probably best to use a password..

Adding the key to your ssh config

Once yourmachine.local has generated a key you need to edit the ssh config on yourmachine.local

vi ~/.ssh/config

paste the following into the file:


Host remotehost.com
User username
IdentityFile ~/.ssh/id_rsa

The last line should be the name of the file you created in the step above.

Transferring your key to the remote machine

Finally, you can run the following command to store the generated key on remotehost.com


ssh-copy-id -i ~/.ssh/id_rsa.pub username@remotehost.com

ssh-copy-id will ask you for your user password, and will store your key in the ~/.ssh/authorized_keys file on remotehost.com.

ssh-copy-id isnt available by default on a mac, but you can install it a couple of different ways: see this blog post to find out how to install ssh-copy-id on your mac

ssh with keys for authentication

You should now be able to log into remotehost.com without entering the passwords!


ssh remotehost.com

Troubleshooting

If you run into problems then you can enable debug mode to see debug information


ssh -v remotehost.com

You should be able to figure out whats happening from the messages displayed.

Leave a Reply