Accessing an SSH key from a bash script executed using a cron job

I linked this script together to update the Github forked repositories folder on a daily basis. It works fine if I call it from the prompt, but I can "figure out how to get it to use id_rsa reliably when it starts as a cron job. eval 'ssh-agent' is an attempt to do just that, but it has no positive effect.

 #!/bin/sh LOGPATH=log.txt eval 'ssh-agent' cd /path/to/update/folder echo "-------START UPDATE-------">$LOGPATH echo "Updating repos:">>$LOGPATH date "+%F %T">>$LOGPATH COUNT=1 find . -maxdepth 1 -type d | while read dir; do cd "$dir" LEN=$"${#dir}" if [ $LEN != "1" ] then echo "*********">>$LOGPATH echo "$COUNT. " ${dir:2}>>$LOGPATH /usr/local/bin/git pull upstream master>>$LOGPATH 2>> $LOGPATH /usr/local/bin/git push origin master>>$LOGPATH 2>> $LOGPATH let COUNT=COUNT+1 fi cd "$OLDPWD" done echo "-------END UPDATE-------">>$LOGPATH exit 0 

This is probably a terribly inefficient way to bypass the process as a whole, but it works, and I have never seen it. If I could use it, I would be delighted.

+6
github scripting bash ssh cron
source share
2 answers

I believe that you are using the wrong kind of quotes. A simple csh agent does nothing, you need to include the results of its launch using command substitution with:

 eval `ssh-agent` 

or

 eval $(ssh-agent) 

This causes the script to set the necessary environment variables. However, ssh-agent will still not have any keys unless you ssh-add them. If your keys do not have a passphrase, then ssh-add can simply be run from a script.

If your private key has a passphrase, you can run this script as a daemon, not a cron job. This will allow you to connect to the agent and add private keys.

The real reason the script runs from the command line is because your desktop environment is probably running ssh-agent , and it arranges the necessary environment variables for distribution in all of your terminal windows. (Either by making them children, and inheriting the variables, or having the shell source code the necessary commands.) I assume that you are running ssh-add at some point in your normal workflow?

+7
source share

The ssh-agent process provides the ability to use only ssh-add to add your passphrase. It does not automatically make your key available (your secret key cannot be decrypted without your phrase).

To do this, you will need to create a passphraseless key and use this from the cron job. The usual safety warnings apply when using silent keys.

+2
source share

All Articles