SSH auto login

Auto login in remote machine

Sometimes, we would like to automatically login to remote machine without keying the password. It can be done by generating public/private key and stores the keys in the remote machine.

Steps:

1) Open a terminal, and type the following line in the local machine:

~$ ssh-keygen -t rsa -b 2048

Output:

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/henry/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/henry/.ssh/id_rsa.
Your public key has been saved in /Users/henry/.ssh/id_rsa.pub.
The key fingerprint is: xxx

2) Then type the following to copy the keys in the remote machine

~$ ssh-copy-d user@server_ip

Output:

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/userid/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
user@server_ip's password: 

Key in the password

Number of key(s) added:        1
Now try logging into the machine, with:   "ssh 'user@server_ip'"
and check to make sure that only the key(s) you wanted were added.

3) Now we can login to the remote machine without key in the password.


To automatically ask a remote machine to run a script

Let's say we would like to run the command "last > dump.txt" at remote machine "server_ip", type the following command:

~$ ssh user@server_ip "last > dump.txt"