2 Answers
2

You can make ssh connections within a cron session. What you need is to setup a public key authentication to have passwordless access. For this to work, you need to have PubkeyAuthentication yes in each remote server's sshd_config.

You can create a private/public key pair with or without a passphrase. If you use a passphrase (recommented) you need to also start ssh-agent. Without a passphrase, you only need to add the parameter -i your_identity_file to ssh command line. ssh will use $HOME/.ssh/id_rsa as default.

I replicated your example by using a key pair with a passphrase. Here's how I did it.

1) Created the key pair with passphrase. Saved the private key as ~/.ssh/id_rsa_test, which should have the correct permissions by default. We can enter an empty passphrase for not using one.

2) Sent the public key to the servers, did the same for all of them. Remember they need to have PubkeyAuthentication enabled.

john@coffee:~$ ssh-copy-id -i .ssh/id_rsa_test server1
The authenticity of host 'server1 (11.22.33.1)' can't be established.
RSA key fingerprint is 79:e8:0d:f5:a3:33:1c:ae:f5:24:55:86:82:31:b2:76.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'server1,11.22.33.1' (RSA) to the list of known hosts.
john@server1's password:
Now try logging into the machine, with "ssh 'server1'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.

3) Run ssh-agent as service with -s. This will not kill it if you logout. Its output is a valid shell script, setting the environment so ssh client will know how to connect to it. We save that to a file (only the first line is really needed).

6) The script I used, slightly modified than yours. Notice that I did not enclose the ssh command in parentheses and not using backticks rather $(), which is a better alternative for command substitution (this is bash compatible, you didn't mention which shell you're using). I used the exact same ssh command as yours.

Why is it complaining about known_hosts? But yes, you need to watch out for permissions — the private key file should be mode 0600 or even 0400, owned by you. If you need some other user to be able to use it as well, you'll have look into POSIX ACLs or similar.
–
geekosaurMar 9 '11 at 8:12

Come to think of it, I saw GSSAPI being offered in there so another possibility is to get a keytab and use it to kinit inside the cron job. That said, keytabs also require the same care in permissions; but ssh at least won't complain about them.
–
geekosaurMar 9 '11 at 8:16