Saturday, February 11, 2012

Password-less logins with OpenSSH

Password-less logins with OpenSSH


Note: To see my entire list of tutorials click here.

SSH is often used to login from one system to another without requiring passwords. One thing that you probably won't want is to do though is store the remote system's password in the script. Instead you'll want to setup SSH so that you can login securely without having to give a password. The first step is to create a key-pair. I will explain this... but before that....

The ssh key-pair consists of a public key and private key. They are stored in /home/yourusername/.ssh/ folder.

Step 1: Creation of key pair


If you already have a key pair goto step 3. To check whether you already have a key pair check whether '/home/yourusername/.ssh/id_rsa.pub' file exists or not.

To create a new pair
ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/yourusername/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/skx/.ssh/id_rsa.
Your public key has been saved in /home/skx/.ssh/id_rsa.pub.
After entering 'ssh-keygen -t rsa' just keep on pressing enter.

Step 2: Adding identity to authentication agent


To add the generated key to the authentication agent either you should logout and then login or, run the following
ssh-add

Step 3: Copying the authentication to target


Step 1 and Step 2 should only be executed once. If you have more that one target, just executed step 3 multiple times (changing the target ip)

Lets assume that 10.192.35.12 is the ip address of the machine in which we want to login to. Run the following code
ssh-copy-id -i ~/.ssh/id_rsa.pub username@10.192.35.12
This will prompt you for the login password for the host, then automatically copy the key file for you, creating the correct directory and fixing the permissions as necessary.The contents of the key file will be appended to the file ~/.ssh/authorized_keys2 for RSA keys.

Once this has been done you should be able to login remotely, and run commands, without being prompted for a password.

To login use
ssh username@10.192.35.12

To execute a command say uptime use,
ssh username@10.192.35.12 uptime


No comments: