Automatic SSH login with a key

To get rid of having to type password every time you want to log into a server via SSH or by using SFTP, you may generate a pair of key files and let the software do logins automatically. One of the keys is the “private”  key, the pother one is the “public” key.

The basic concept is:

  • The contents of the public key get appended to the file ~/.ssh/authorized_keys on the server
  • The client takes the private key and either uses it as it is, or [renames it and] refers to it in the ~/.ssh/config file.

Technically, it does not matter, do you generate the keys at the server or at the client.The basic concern is that nobody except for the user must have access to user’s private key. Because it is THE key. More often then not though, for various reasons, the key pair is generated at the server, and that is what will be described in this example.

At the server (the future destination, the remote system):

  • cd ~/.ssh
  • ssh-keygen -t rsa
  • cat id_rsa.pub >> authorized_keys
  • rm id_rsa.pub
  • chmod 600 authorized_keys

At the client (the future origin, the local system):

  • cd ~/.ssh
  • scp -P <port> <username>@<address>:.ssh/id_rsa .
  • chmod 600 id_rsa

Regular automatic login:

  • ssh -l <username> <address> -p <port>

Automatic login by alias (less typing):

  • cd ~/.ssh
  • echo "Host <somename>" >> config
  • echo "    HostName <address>" >> config
  • echo "    Port <port>" >> config
  • echo "    User <user>" >> config
  • ssh <somename>

Multiple remote hosts:

If you have to log into multiple servers, rename each corresponding id_rsa file to a different name and make individual entries for each of the hosts in the config file, adding one more parameter:

  • IdentityFile ~/.ssh/<id_file_name>
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s