This is probably remedial for a lot of you, but it never occurred to me before today.
I’ve got a lot of shell scripts that run in cron or manually, and a significant portion of those need to connect to a remote server via ssh, either to rsync or to issue commands, or whatever.
The way I do this is to set up key-based authentication between the machines…but what if, for whatever reason, that doesn’t work? Have you ever ran a script, and after 5 minutes, you realize it hasn’t finished, because it’s still sitting there yelling at you:
[email protected]’s password:
That’s no fun…mostly because you’re probably going to end up typing the password another dozen times (or more!) for each time that it has to connect to a remote host to which you haven’t copied the keys.
Today, I learned and/or realized that you can specify options from ‘man ssh_config’ on the command line to ssh. That means you can avoid the mess above and more gracefully handle these exceptions. Instead of just
ssh [email protected] command
ssh -o PreferredAuthentications=publickey [email protected] command
This causes the result to be
Permission denied (publickey).
Probably more importantly, it returns an error code (255 in this case), which you can handle in-script:
if ! ssh -o PreferredAuthentications=publickey \ $USERNAME@$HOST $COMMAND ; then echo "Sorry, key authentication failed for $HOST" exit 1 fi
I’m not sure why it never occurred to me before, but it’s a great way to account for those oddities which seem to crop up from time to time.
By the way, if you’re unfamiliar with key-based authentication in SSH (or with SSH tricks in general), there are several posts from a few years back where some other bloggers and I covered various SSH tricks that you might be interested in.
Drop a comment and let me know how you handle these sorts of things. Your way is probably better than mine, and I’m interested in hearing about it!