johncorser
johncorser

Reputation: 9822

Using cron with ssh keys

I am using a cron script that rsyncs with a server via ssh.

The commands work great when I run them directly as a bash script, but when I run them as cron, cron logs out bad permissions. I think this is because the cron user does not have access to the ssh key.

This is the code that I need cron to run:

rsync --progress -rvze ssh my_user@myserver/root_folder folder/

Can I pass the ssh key into the cronfile, or into the script itself? If so, would you provide an example like the one above?

Upvotes: 4

Views: 12132

Answers (4)

Derek Mahar
Derek Mahar

Reputation: 28386

Another option is for your cron script to run Keychain before rsync:

eval $(keychain --agents ssh --eval --noask --quiet)

This assumes that you've already run Keychain as the same user in another terminal to add a private key to an active ssh-agent process:

$ eval $(keychain --agents ssh --eval id_rsa)

 * keychain 2.8.5 ~ http://www.funtoo.org
 * Found existing ssh-agent: 272060
 * Known ssh key: /home/ubuntu/.ssh/id_rsa

Run keychain --list to see keys present in the active SSH agent:

$ keychain --list
3072 SHA256:E2IzZ635kapyGwQG0HiZT+5hCv7dh8glpgvz+qN4dsM ubuntu@raspberrypi1 (RSA)

Upvotes: 1

vincecalpari
vincecalpari

Reputation: 11

Just to add to @jytous answer, typically env|grep -i ssh gives you a tmp file:

eg: SSH_AUTH_SOCK=/tmp/ssh-1gJufasJLiXv/agent.3591

The /tmp in the above, refers to a temporary file that will be deleted when ssh-agent exits or the computer shuts down.

Therefore, if you have ssh-agent running to manage your keys, try adding this at the beginning of whatever script(s) you call from cron:

auth=`find /tmp -user $LOGNAME -type s -name "*agent*" -print 2>/dev/null`
SSH_AUTH_SOCK=$auth
export SSH_AUTH_SOCK

Refer - Link

Upvotes: 1

jytou
jytou

Reputation: 550

I know this thread is old, but for the sake of others who stumble on this problem like me, here are your two options:

  • pass the key as suggested by lihao,
  • add the correct SSH environment variable so that it will pick the correct key, just the same way as it runs in your normal environment.

For the second option, and assuming that your cron job runs with the correct user (otherwise there are more things to set correctly in your environment), just run:

env|grep -i ssh

There will be a line like:

SSH_AUTH_SOCK=/run/user/1000/keyring/ssh

The user id might be different for you. From there, you can just add the following lines to your script:

if [ -z "$SSH_AUTH_SOCK" ]
then
    export SSH_AUTH_SOCK=/run/user/1000/keyring/ssh
fi

Hope this helps!

Upvotes: 18

lihao
lihao

Reputation: 781

add '-i' switch to your ssh command in your command line:

rsync --progress -rvze "ssh -i/path/to/ssh_private_key" my_user@myserver:/root_folder folder/

Upvotes: 4

Related Questions