Skip to content

Instantly share code, notes, and snippets.

@Justintime50
Last active April 18, 2024 16:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

@Justintime50
Copy link
Author

Justintime50 commented Mar 18, 2022

@durai23 that's an interesting thought, I'm not sure to be honest as I've never attempted this. I'm curious if you could continue forwarding to the next machine or if you'd need an intermediate step. Sadly I wouldn't know.

@mikesmithgh
Copy link

I had to specify in the crontab file to use bash as my shell: SHELL=/bin/bash

same here about needing to set SHELL=/bin/bash

thanks @Justintime50 for this gist 👍

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