Getting access to SSH inside a Crontab is often a problem for many as the environment in which your cron runs is not the same as your normal shell. Simply running ssh-add
will not allow you to use your SSH Agent inside your crontab. Follow the below guide to setup your crontab to use your ssh-agent
:
- Install Keychain.
- Add the following to your
~/.zlogin
file which will be invoked on each login. This will allow your crontab (and normal shell) to use your ssh keys and bypass needing to punch in your password each time you need SSH. This will also span across multiple sessions and shells.
# Use keychain to keep ssh-agent information available in a file
/usr/bin/keychain "$HOME/.ssh/id_rsa"
. "$HOME/.keychain/${HOSTNAME}-sh"
- Finally, prepend the following to your cron job command to allow it access to your new keychain.
. "$HOME/.keychain/${HOSTNAME}-sh"
A full crontab example may look like the following:
0 2 * * * . "$HOME"/.keychain/${HOSTNAME}-sh; my_command --someflag > /dev/null
https://eli.thegreenplace.net/2013/10/08/some-notes-on-logging-and-ssh-access-from-cron-jobs
In Step 3, can you clarify how to prepend "source "$HOME/.keychain/${HOSTNAME}-sh" to the cron job? Should it be prepended to the command with '&&' ? For example, a cron job that runs at 12:10am every day:
10 0 * * * source "$HOME/.keychain/${HOSTNAME}-sh" && do my ssh stuff here