Ubuntu articles

SSH tricks

Connect automatically to a remote machine (without typing in the password each time)

The process goes roughly like this: you need to generate a public key that you'll save in the remote machine. It's the way of saying to it: this computer is authorised to connect to you, and this is my way of proving I am who I say I am.

To generate a public key, open a terminal in your local machine (the machine that you'll connect to the remote server) and type the following:

ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa_keyname_$(date +%Y-%m-%d) -C "Key for xyz"

When prompted, leave the passphrase empty. You can select which file to store the key in, remember the one you select (default is ~/.ssh/id_rsa).

ssh-keygen will actually generate two files. One contains your private key and the other contains the public key. In this case, id_rsa contains the private key, and id_rsa.pub contains the public key. You MUST NEVER REVEAL your private key to anyone since that means that people with access to it would be able to decrypt encrypted content signed with your key.

So now open the generated id_rsa.pub file and copy its contents to the ~/.ssh/authorized_keys in the remote machine. If there are any existing keys, just append the new contents to the end of the file.

If your client machine is a Mac you need to add the new key to the ssh-agent:


eval "$(ssh-agent -s)"
ssh-add -K key-name

where key-name is the private key, and the -K option is for adding the key to the KeyChain, otherwise it is 'forgotten' between sessions or when the computer is turned off.

At this point you could connect just using

ssh server.address -l username

but we want to type even less, something in the lines of

ssh server_alias

To do so you need to add an alias in your local ssh config file. If the file doesn't exist, create it at ~/.ssh/config and add the following:


Host server_alias
HostName server_domain.tld
User username

That should do!

References: Setting SSH public keys Type less with ssh aliases