How to connect with ssh without using a password

Let’s say you have an account on a remote server running some flavour of linux (or even *BSD – I think OpenSSH works the same way on those), and connect to it via ssh from your local linux machine.
There is a simple yet secure way to connect without the need for entering your password on the remote server. This involves public-key cryptography : in simple words, you are going to generate a public key and copy it over to the remote host, and afterwards use the associated secret key to authenticate yourself instead of your unix password.

0. I assume you have openssh installed both remotely and locally. If not, just do :

user@localbox:~$ sudo apt-get install openssh

1. Generate public and private RSA keys for the local computer :

user@localbox:~$ ssh-keygen -t rsa

(ssh-keygen will offer to protect your private key with a passphrase but I personnally skip that part.)
This will create 2 files named id_rsa and id_rsa.pub in the .ssh subdirectory of your home directory. id_rsa.pub is your public RSA key, which you can disclose to anyone, whereas id_rsa is your private key, which you absolutely need to keep secret (that’s why by default the file has -rw——- permissions, meaning only you can read it).

2. Copy your public key to the remote computer using scp :

user@localbox:~$ scp ~/.ssh/id_rsa.pub user@remotebox.remotedomain.tld:~/.ssh/id_rsa_localbox.pub

(assuming ‘user’ is also your login name at the remote machine, and replacing ‘remotebox.remotedomain.tld’ with the server name or IP address).
scp will ask you to provide your remote password.

3. Log in to the remote host and add your public key to the file named authorized_keys2 in the remote .ssh directory :

user@remotebox:~$ cd .ssh
user@remotebox:~/.ssh$ cat id_rsa_localbox.pub >> authorized_keys2
user@remotebox:~/.ssh$ rm id_rsa_localbox.pub

Voilà ! You can now use ssh to connect from your local box to the remote server without password. You can also use scp or rsync to copy files over, with no password needed either.
Note that the key-pair you generated is attached to your account on the local box, and will not work for another user. Also note that you do not need admin rights on the local box nor on the server side to make this work.

2 Replies to “How to connect with ssh without using a password”

Leave a Reply

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