Saturday, June 21, 2008

Non-interactive SSH in Linux

There are two machines, A and B in a network. Let the IP of A be 192.168.1.2, and IP of B be 192.168.1.8. You can access remotely from A to B using the command: ssh guest@192.168.1.8. It will ask you the password of the user guest in machine B. Now let me tell you a simple trick so that you don't need to enter the password any more. It's called non-interactive ssh.

Suppose your username in machine A is pypy. Open the terminal. Go to the directory /home/pypy/.ssh (cd /home/pypy/.ssh). Now enter the follwoing command:
ssh-keygen -t dsa
First it will ask you for a filename. Just press enter to keep it default (id_dsa) or you can enter any other name. Then it will ask you for a passphrase. Enter empty there (just press enter twice). Now you will see two files there named id_dsa (that has the private key) and id_dsa.pub (that contains the public key).

pypy@pypy-laptop:~/.ssh$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/pypy/.ssh/id_dsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/pypy/.ssh/id_dsa.
Your public key has been saved in /home/pypy/.ssh/id_dsa.pub.
The key fingerprint is:
fc:37:69:9e:bb:15:e7:55:cd:b9:52:12:e6:49:b1:6c pypy@pypy-laptop

Key generation complete. Check the directory

pypy@pypy-laptop:~/.ssh$ ls -lt
total 12
-rw------- 1 pypy pypy 668 2008-06-20 23:54 id_dsa
-rw-r--r-- 1 pypy pypy 610 2008-06-20 23:54 id_dsa.pub

Now append the content of id_dsa.pub file to the file named authorized_keys2 in /home/guest/.ssh directory (if the file doesn't exist first create it) of machine B. You can do this using this command also:
cat /home/pypy/.ssh/id_dsa.pub | ssh guest@192.168.1.8 'cat - >> ~/.ssh/authorized_keys2'

(it will ask you for the password of user guest of machine B).

Now done. Try to access machine B from machine A
pypy@pypy-laptop:~/.ssh$ ssh guest@192.168.1.8

Hopefully it won't ask you for a password :-)

No comments: