Monday, February 7, 2011

SCP without Password

Sometimes we need a ssh connection that do not ask for passwords. It is use frequently in scripts that involve ssh, scp or sftp connections. I do not encourage this kind of logging but sometimes is very useful...

So, those are the steps to make such connection.

1. Login as user1 on computer1 and generate a pair of authentication keys. Note: even if is unsecured to work without password, do not enter it. Let it empty...

[user1@computer1]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user1/.ssh/id_rsa):
Created directory '/home/user1/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/user1/.ssh/id_rsa.
Your public key has been saved in /home/user1/.ssh/id_rsa.pub.
The key fingerprint is:
31:df:a5:73:4a:2f:a6:6c:1c:32:a2:f2:b3:c5:a7:1f user1@computer1

2. Login to the remote computer (computer2) as user2 and create the .ssh directory (many Linux distributions create this folder by default. No problem with that.). You still need the password for now...

[user1@computer1]$ ssh -l user2 computer2 mkdir -p .ssh
user2@computer2's password:

3. Copy the user1 public key to user2@computer2 .ssh folder into authorized_keys file. And, type the password again for the last time, hopefully...

[user1@computer1]$ cat .ssh/id_rsa.pub ssh -l user2 computer2 \
>'cat >> .ssh/authorized_keys'
user2@computer2's password:

4. If all things are OK, you don't need the password

[user1@computer1]$ ssh -l user2 computer2
[user2@computer2]$


..or optionaly (see the troubleshooting section of this page):

[user1@computer1]$ ssh -i $HOME/.ssh/id_rsa user2@computer2

NOTE:
This is the way not only for ssh but also for scp and sftp as well...

TROUBLESHOOTING:
If the password prompt will be shown again check the /etc/ssh/ssh_config and uncomment or insert the following option:

IdentityFile ~/.ssh/id_rsa


As you can see, the above option is for RSA type keys. If you want to generate the key pairs using DSA change the "id_rsa" with "id_dsa". Sound logic, right?
This modification in /etc/ssh/ssh_config file can be avoided if you will use the parameter "-i" followed by the location of the key file as in example:

[user1@computer1]$ ssh -i $HOME/.ssh/id_rsa user2@computer2


Also, if you do have write permissions for either the .ssh directory or for the authorized_keys file on the remote machine, then sshd will consider that the procedure is not safe enough, so it will abort the RSA challenge-authentication mode (mode 3) and will go to the default mode (mode 5) asking you for the password on the remote machine. Set chmod 700 for .ssh folder and 600 authorized_keys file. See http://cag.lcs.mit.edu/~rugina/ssh-procedures/

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.