ssh Permission denied only in cron job

Interactive commands and cron jobs run in different environments – in particular, an interactive session might have a SSH agent running, or a Kerberos TGT stored. Because of the way ssh orders authentication methods, you cannot be sure that your key is used just because you added the -i option.

  • If a SSH agent is running, the ssh client always tries agent keys before using any explicitly-specified keys.

  • If the network uses Kerberos and a Kerberos TGT is present, OpenSSH will use it before trying public-key authentication.

I don't know anything about your environment, but both of these possibilities are easy to check:

  1. Add unset SSH_AUTH_SOCK and unset KRB5CCNAME before the ssh command, then manually run the modified script.

    This will prevent the script from seeing the agent or the Kerberos tickets, and will only use the explicitly-specified key.

  2. Add the -v option to ssh. This will display more detail on how the authentication happens.

You can also add -oIdentitiesOnly=yes to the ssh command; this will force it to use the specified key.


And if you add tips on accessing the agent from cron - even better

This is generally not recommended, since the agent is usually closely tied to your interactive login session. In particular, it's only started when you log in, and killed when you log out – and it needs your password to actually unlock the SSH keys (assuming they were password-protected).

You mentioned "Keychain" – is this the OS X program, or the Linux script? (I don't know much about the architecture of Mac OS X, but AFAIK it makes it much harder to access the user's ssh-agent from a cronjob...)


Another workaround to this issue is set cron to ssh to the local box to in turn run the ssh command instead of running the file or command by its local, absolute path. This caches the KRB5CCNAME and works where /path/command does not.

# Fails:
0 * * * * /home/user/sshscript.sh

# Works:
0 * * * * /usr/bin/ssh user@localhost /home/user/sshscript.sh

#!/bin/bash
# Works:
unset SSH_AUTH_SOCK
unset KRB5CCNAME
/usr/bin/ssh user@localhost /home/user/sshscript.sh

Tags:

Bash

Ssh

Cron