Its reasonably common for me to require one server to log into another server automatically over SSH. Whether you’re transferring backup files to a remote server using scp or just performing a scheduled remote function, automating the authentication process can make this a lot easier.
For the sake of this tutorial, my username on the local machine will be localuser@localserver and my username on the remote machine will be remoteuser@remoteserver. If you are running these automated taks in your crontab remember to specify the localuser as the user account running the script in your /etc/crontab file:
# Running backup for server conf files every night at 1.00 am 00 1 * * * localuser /backup/scripts/backupToRemoteServer.sh
WARNING: Allowing a local server to automatically log into a remote server means that if the local server gets compromised, then the intruders will also have automatic access to the remote server, compromising it also.
For this reason I always ensure that the remoteuser account has its privileges reduced to the point where it can’t do anything except what I require it to do. Setting up user privileges is outside the scope of this tutorial and depends greatly on the specific task you need to perform on the remote server.
1. Login to the local machine as localuser
#ssh localuser@localserver
2. Create an .ssh directory on the local machine in the localuser’s home directory
#mkdir ~/.ssh #chmod 700 ~/.ssh
3. Generate the ssh keys on the local machine
#ssh-keygen -t dsa -C '<enter a description about your local server here>'
Output:
Generating public/private dsa key pair. Enter file in which to save the key (/home/localuser/.ssh/id_dsa): Enter passphrase (empty for no passphrase): <Leave Empty> Enter same passphrase again: <Leave Empty> Your identification has been saved in /home/localuser/.ssh/id_dsa. Your public key has been saved in /home/localuser/.ssh/id_dsa.pub. The key fingerprint is: 64:be:2f:ec:d4:30:61:28:d4:8b:58:e9:bd:ea:f4:65 <local machine description as entered in above>
4. Set permissions for the SSH key on the local server
#chmod 600 ~/.ssh/id_dsa.pub
5. Open the ~/.ssh/id_dsa.pub file and copy its contents to your clipboard
#cat ~/.ssh/id_dsa.pub
6. Login to the remote server
#ssh remoteuser@remoteserver
7. Create an .ssh directory on the remote machine in the remoteuser’s home directory
#mkdir ~/.ssh #chmod 700 ~/.ssh
8. Paste your clipboard contents (the local servers id_dsa.pub file) at the bottom of the authorized_keys file on the remote server
#vim ~/.ssh/authorized_keys
9. Set permissions on the remote servers authorized_keys file
#chmod 600 ~/.ssh/authorized_keys
10. Go back to the local machine as localuser and then try to log into the remote machine
Login to the local server:
#ssh localuser@localserver
Then try to access the remote server from the local server:
#ssh remoteuser@remoteserver
It should now login automatically.


