It’s been a while since I got this problem waiting to be solved, and tonight I finally found a solution!
I have a shell script that makes a rsync of a remote machine via ssh. Something like this:
#!/bin/bash rsync -e ssh -a firstname.lastname@example.org:/folder/to/be/saved /home/nico/backup
When I run the script by doing this :
$ sh MyScript.sh
…rsync doesn’t ask me for a password for the ssh connection because I have my public key that is well recorded in the
~/.ssh/authorized_keys file on the remote computer for the user
the public key was generated by default (I guess), by ubuntu and/or Gnome-keyring.
So far, everything’s fine. The script works very well without asking me any password.
My problem starts when I try to automate the exiecution of my backup. For example, I would like it to start every 30 minutes.
$ crontab -e
…and I add this line:
*/30 * * * * sh ~/MyScript.sh
Unfortunately, it doesn’t work. To understand where the problem is, I log to find out what’s going on.
*/30 * * * * sh ~/MyScript.sh > ~/logs.txt 2>&1
And unfortunately I don’t learn much more. Except that the SSH connection is refused.
To find out, I ask rsync to make ssh a little more verbose bavard in my script by adding the
-vv to the command
ssh (and some apostrophes around the
#!/bin/bash rsync -e 'ssh -vv' -a email@example.com:/folder/to/be/saved /home/nico/backup
That’s how I got the details of the SSH error:
read_passphrase: can't open /dev/tty
I tried several things to make SSH agree to log in using my SSH key:
…but no change. Actually the problem was elsewhere. If I understood it correctly, the problem is that my SSH key was generated with a passphrase managed by Gnome-Keyring. So it’s flowless when I make a SSH connection via the console. but when I try to make a SSH connection in non-interactive mode (as is the case for a cron task), then the passphrase is not communicated to the cron task because no gnome interface is related to it.
To avoid this, the only way that was within my reach was to generate a new ssh key without passphrase:
$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/nico/.ssh/id_rsa): # /home/nico/.ssh/id_rsa_without_passphrase Enter passphrase (empty for no passphrase): # leave empty
After that, there’s only two things left to:
- add my new public key to the
~/.ssh/authorized_keysfile on the remote computer.
- explain to SSH in my rsync command that it needs to use the key without passphrase rather than using the default
~/.ssh/id_rsakey. To do this, we simply put the
-ioption to the
#!/bin/bash rsync -e 'ssh -i /home/nico/.ssh/id_rsa_without_passphrase' -a firstname.lastname@example.org:/folder/to/be/saved /home/nico/backup
…and voilà. My sync finally works automatically without asking for a password.
Here’s the page which eventually gave me the real answer to my problem.