Blog    Notes   

SSH key generation

Sometimes, the secure commands like ssh, scp, sftp, etc. might have to be run in a non-interactive mode, especially when called from a shell script. Anyone trying this for the first time, faces a major problem of automating the authentication. The password can not be passed as a standard input to these commands. This problem can be solved by generating cryptographic authentication keys. There is a utility called ssh-keygen which can be used to create RSA or DSA keys.

License

Copyright © 2008 Susam Pal

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is available at: http://www.gnu.org/licenses/fdl.txt

This document is published with the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. The author shall not be liable in any event of any damages, incidental or consequential, in connection with, or arising out of this document.

Generating Key Pair

We'll assume that the remote system you are trying to connect to is remote.example.com and your user name on that system is superman. Enter the command ssh-keygen. Press 'enter' key when it asks for the file where the key is to be stored, in order to store the key in the default file. Press 'enter' key again when it asks for passphrase, so that no passphrase is asked when you try to invoke ssh, scp, sftp, etc. from a shell script. The following is an example from my computer:-

susam@cave:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/susam/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/susam/.ssh/id_rsa.
Your public key has been saved in /home/susam/.ssh/id_rsa.pub.
The key fingerprint is:
e5:73:6b:48:5a:c2:60:63:cf:ae:b3:d8:cd:ca:05:96 susam@cave

Two files are created after this step in the ~/.ssh directory: id_rsa and id_rsa.pub. id_rsa contains the private key which should be kept secure. id_rsa.pub is the public key which has to be distributed to all the remote servers where you would like to login without 'password' authentication.

Distributing Public Key

The public key can be distributed by copying the public key file to .ssh/authorized_keys in your home directory in the remote system. For example, in this case, the public key file has to be copied to .ssh/authorized_keys in the home directory of superman. Once this has been done, you are ready to log into the remote server and you won't be prompted for password. Now that you could get rid of the password, you can proceed with writing the shell script.