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
Hi Justin,
Is it possible to adapt keychain to the case where I am already ssh-ed into a server and need to run a cronjob that will ssh to a third server. That is as follows:
workstation (with ssh keys) -> ssh into server 1 (with agent forwarding) -> run cronjob that will ssh into server 2
So ideally I would want keychain on server 1 but the keys are not present in server 1. Is this doable?