Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing SSH key from bash script running via a cron job

I've put this script together to updated a folder of forked Github repositories on a daily basis. It runs fine if I call it from a prompt, but I can' figure out how to make it utilize my id_rsa reliably when it is run as a cron job. the eval 'ssh-agent' is an attempt to do just that, but it doesn't seen to have any positive affect.

#!/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 horribly inefficient way to go about the process in general, but it works and I don't ever see it. If I could get it to use my creds, I would be elated.

like image 573
Joel Hooks Avatar asked Nov 04 '09 02:11

Joel Hooks


2 Answers

I believe you are using the wrong kind of quotes. Plain-quoting ssh-agent doesn't do anything, you need to incorporate the results of running it by using command substitution with:

eval `ssh-agent`

or

eval $(ssh-agent)

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

If your private key does have a passphrase, you might want to run this script as a daemon rather than a cron job. This would allow you to connect to the agent and add your private keys.

The real reason the script works from the command line is that your desktop environment is probably running ssh-agent and it arranges for the needed environment variables to be propagated to all your terminal windows. (Either by making them be children and inheriting the variables or by having your shell source the necessary commands.) I'm guessing you are running ssh-add at some point in your normal workflow?

like image 128
DigitalRoss Avatar answered Nov 15 '22 21:11

DigitalRoss


The ssh-agent process only provides a facility to use with ssh-add to add your passphrase. It does not automatically make your key available (your private key cannot be decrypted without your passphrase).

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

like image 20
Greg Hewgill Avatar answered Nov 15 '22 21:11

Greg Hewgill