UsingSSHAgentWithCron

30th October 2016 at 1:34pm
CodeSnippets OpenSSHTipsAndTricks SSH TechnicalNotes

Given that it is desireable to always secure SSH private key identies with a passphrase, you may wish to know how to configure your cron jobs to work with an ssh-agent.

Contrary to popular belief, this is very simple and requires no black magic or hackery to achieve. All you need to do is start an ssh-agent and add your private key with ssh-add. You can either perform these steps manually every time you boot your machine, or automate it as part of the boot process, assuming you have a secure manner to provide the private key passphrase to the ssh-add command (either by keyboard input on the console, hard coding it in a wrapper script or file with secure file permissions, or some other challenge response authentication mechanism).

An example of the former option to manually start an ssh-agent with a specified socket filename, and add your private key identities to the agent is:

mkdir -p /tmp/ssh-agent.cron/
ssh-agent -a /tmp/ssh-agent.cron/agent.fooname
SSH_AUTH_SOCK=/tmp/ssh-agent.cron/agent.fooname \
    ssh-add /path/to/ssh_private_key
SSH_AUTH_SOCK=/tmp/ssh-agent.cron/agent.fooname \
    ssh-add -l

Now you can set the SSH_AUTH_SOCK environment globally in your crontab so that all subsequent tasks in that crontab will use this pre-existng ssh-agent:

SSH_AUTH_SOCK=/tmp/ssh-agent.cron/agent.fooname
* * * * * ssh -i /path/to/ssh_private_key remote_user@remote.host.fqdn hostname -f >/tmp/example_cron_output.log 2>&1

Alternatively you may wish to simply specify the SSH_AUTH_SOCK on a per-task basis:

* * * * * SSH_AUTH_SOCK=/tmp/ssh-agent.cron/agent.fooname ssh -i /path/to/ssh_private_key remote_user@remote.host.fqdn hostname -f >/tmp/example_cron_output.log 2>&1

If this works, you will find the fully qualified hostname of the remote host written to /tmp/example_cron_output.log.

Simple!


Related