Skip to content

Instantly share code, notes, and snippets.

@Justintime50
Last active October 4, 2024 05:31
Show Gist options
  • Save Justintime50/297d0d36da40834b037a65998d2149ca to your computer and use it in GitHub Desktop.
Save Justintime50/297d0d36da40834b037a65998d2149ca to your computer and use it in GitHub Desktop.
Use Your SSH Agent in a Crontab

Use Your SSH Agent in a Crontab

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:

Usage

  1. Install Keychain.
  2. 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"
  1. 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

Attribution

https://eli.thegreenplace.net/2013/10/08/some-notes-on-logging-and-ssh-access-from-cron-jobs

@Dosflange
Copy link

Dosflange commented Oct 4, 2024

Really helpful Gist! I am using zsh and had to replace ${HOSTNAME}-sh by $HOST-sh👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment