Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cron with ssh keys

Tags:

bash

ssh

cron

rsync

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?

like image 278
johncorser Avatar asked Aug 24 '26 00:08

johncorser


2 Answers

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!

like image 139
jytou Avatar answered Aug 25 '26 15:08

jytou


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/
like image 36
lihao Avatar answered Aug 25 '26 13:08

lihao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!