views:

1597

answers:

2

I have a bash script that does ssh to a remote machine and executes a command there, like:

ssh -nxv user@remotehost echo "hello world"

When I execute the command from a command line it works fine, but it fails when is being executed as a part of crontab (errorcode=255 - cannot establish SSH connection). Details:

...
Waiting for server public key.
Received server public key and host key.
Host 'remotehost' is known and matches the XXX host key.
...
Remote: Your host key cannot be verified: unknown or invalid host key.
Server refused our host key.
Trying XXX authentication with key '...'
Server refused our key.
...

When executing locally I'm acting as a root, crontab works as root as well. Executing 'id' from crontab and command line gives exactly the same result:

$ id
> uid=0(root) gid=0(root) groups=0(root),...

I do ssh from some local machine to the machine running crond. I have ssh key and credentials to ssh to crond machine and any other machine that the scripts connects to.

PS. Please do not ask/complain/comment that executing anything as root is bad/wrong/etc - it is not the purpose of this question.

+1  A: 

I am guessing that normally when you ssh from your local machine to the machine running crond, your private key is loaded in ssh-agent and forwarded over the connection. So when you execute the command from the command line, it finds your private key in ssh-agent and uses it to log in to the remote machine.

When crond executes the command, it does not have access to ssh-agent, so cannot use your private key.

You will have to create a new private key for root on the machine running crond, and copy the public part of it to the appropriate authorized_keys file on the remote machine that you want crond to log in to.

Dave Hinton
Dave, how can list keys registered in ssh-agent? That would help to actually check that case.
tkokoszka
Try running ssh-add -l (that's dash lower-case-L).
Dave Hinton
A: 

i need to take MySQL backup every month. MySQL is in cluster mode and having two servers, called server 1 and server 2. i have installed rsa key on both machines. every month i want to execute the command at server 1. from server 1, i need to ssh server 2 and dump all the mysql database. so i want to add this in crontab. but i dont know how to add two commands in a single event in the crontab.

for example at server 1, first ssh server 2 therefore ssh server2

and then dump the mysql db mysqldump -u root -proot WMS >> /tmp/backup

so how to combine these two commands in a single event in crontab??

Post this question as a question in its own right, not as an answer to someone else's question.
Dave Hinton
But the answer to your question is either to use a semicolon to separate the two commands, or to write a shell script containing those commands and execute that from the crontab.
Dave Hinton