Skip to main content

Using ssh-agent for Unattended Batch jobs with Ssh Key Passphrase

In some cases, It is needed to make ssh connections to another servers in order to run shell commands on them remotely. But when it comes to run these commands from a cron job, password interaction will be a concern. Using ssh key-pair with an empty passphrase may be an option but it is not recommended. There is another option automates passphrase interaction.

Ssh-agent provides a storage for unencrypted key because the most secure place to store a key is in program memory.

I am going to explain how to run batch/cron shell script integrated with ssh-agent:

There are two servers, server1 and server2.

On server1, ssh key pair is created.

# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase): <your passphrase here>
Your public key has been saved in /root/.ssh/
The key fingerprint is:

On server2 copy content of the file from server1 and insert it to /root/.ssh/authorized_keys and give appropriate permissions to this file (700 for .ssh directory, 600 for authorized_keys file). From now on, from server1 ssh connections can be made to server2 using key passphrase.

On server1, it can be tested.

# ssh server2
Enter passphrase for key '/root/.ssh/id_rsa': <your passphrase here>
# (that is server2's shell prompt!)

On server1, we invoke an ssh-agent just once, thereafter cron jobs can use this agent for authentication.

# ssh-agent bash
# ssh-add /root/.ssh/id_rsa
Enter passphrase for /root/.ssh/id_rsa: <your passphrase here>
Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)

Ssh agent provides access to its services through a unix socket. If you have access to this socket you will obtain the right to use of keys.

On server1, write out two specific environment variables to a file.

# echo "export SSH_AUTH_SOCK=$SSH_AUTH_SOCK" > aginfo
# echo "export SSH_AGENT_PID=$SSH_AGENT_PID" >> aginfo

Now open an another terminal window on server1 and save the following shell script as an example and run it.

# cat
source ./aginfo
ssh -o 'BatchMode yes' server2 hostname

# ./cron_test

Now we have achieved our goal. Script can be put in the crontab and run periodically. But keep in mind that after a reboot ssh-agent won't live, so that ssh-agent setup process should be done again.


Popular posts from this blog

Find and replace with sed command in Linux

Find and replace feature is always handy. It can turn into a torture when it comes to change or delete a simple constant string in a text file. There is a handy tool in linux for doing these kind of tihngs. Actually sed is not a text editor but it is used outside of the text file to make changes.