Why ssh fails from crontab but succeeds when executed from a command line?

keychain

solves this in a painless way. It’s in the repos for Debian/Ubuntu:

sudo apt-get install keychain

and perhaps for many other distros (it looks like it originated from Gentoo).

This program will start an ssh-agent if none is running, and provide shell scripts that can be sourced and connect the current shell to this particular ssh-agent.

For bash, with a private key named id_rsa, add the following to your .profile:

keychain --nogui id_rsa

This will start an ssh-agent and add the id_rsa key on the first login after reboot. If the key is passphrase-protected, it will also ask for the passphrase. No need to use unprotected keys anymore! For subsequent logins, it will recognize the agent and not ask for a passphrase again.

Also, add the following as a last line of your .bashrc:

. ~/.keychain/$HOSTNAME-sh

This will let the shell know where to reach the SSH agent managed by keychain. Make sure that .bashrc is sourced from .profile.

However, it seems that cron jobs still don’t see this. As a remedy, include the line above in the crontab, just before your actual command:

* * * * * . ~/.keychain/$HOSTNAME-sh; your-actual-command

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)