Tuesday, February 14, 2012

How to use ssh to log in without a password from within a script.

How to use ssh to log in without a password.

Problem:

Today I needed to mount a drive on a remote Linux server from within a Perl script. To do this, I should be able to call ssh to login without specifying the password. 

Let's say, we want to connect as; user a on Host A to user b on Host B.

Here are the steps for doing this:

  1. First log in on A as user a and generate a pair of authentication keys. Select the default options while doing this (just hit enter.).



a@A:~> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/a/.ssh/id_rsa): 
Created directory '/home/a/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/a/.ssh/id_rsa.
Your public key has been saved in /home/a/.ssh/id_rsa.pub.
The key fingerprint is:
38:db:f0:80:aa:0f:dd:39:bc:9d:b7:23:a9:0f:be:1a a@A


    2.  Now, the private and public keys are created under the /home/a/ssh folder.
Now, create a directory ~/.ssh as user b on B. (The directory may already exist, which is fine)


a@A:~> ssh b@B mkdir -p .ssh
b@B's password: 



    3. Append a's new public key to b@B:.ssh/authorized_keys and enter b's password.


a@A:~> cat .ssh/id_rsa.pub | ssh b@B 'cat >> .ssh/authorized_keys'
b@B's password: 



After the third step, you should be able to login with ssh without entering password. The following command should not prompt for a password.

ssh b@B



If you still have to provide a password, try this:
  • Change the permissions of .ssh to 700


No comments:

Post a Comment