Saturday 28 January 2017

Best options for using SSH within scripts

As system administrators we frequently write scripts involving authenticating to more than one server to accomplish tasks within a single script. We want our scripts to run fast but when working with ssh within scripts, we may encounter a very slow execution time in case there are hosts on which some password less authentication setup does not exist or the server is unresponsive.
For example if a server is down & we are trying to connect to it within our script then by default ssh will continue to make connection attempts for 60 seconds before giving up & move to the next server. Take another example wherein you get prompted for password while logging into the server. The script will remain hung until you don't enter the password.

In this article I'd like to share some ssh options that I use within my scripts for quick execution.

StrictHostKeyChecking:
With this option set to no, destination host key checking is turned off so we don't get prompted to accept the key fingerprint while connecting.

BatchMode:
With this option set to yes, ssh will effectively skip any hosts for which password less ssh connectivity is not set up. You can always redirect the hostnames you were unable to connect to another file.

ConnectTimeout:
This option determines the time in seconds for which ssh will continue to initiate a connection to a host. By reducing this value to under 10 seconds, we can reduce the waiting time before moving on to another host. You should redirect the host names you were unable to connect to another file to check them later.

q(quite):
By specifying quite mode, we can effectively skip motd & banner messages seen on the terminal when we log in thereby making room for a more cleaner output.

Usage in scripts:

We can specify the above mentioned options with our ssh command. But I've realized with experience that a better way is to variableize the options so that if we have multiple ssh commands within the script then we don't have to specify the options every time.

Here is an example of how I used these options in a script:


SSH_OPTIONS=" -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=3 -q"


ssh $SSH_OPTIONS ${name} "bash -s" < /export/home/ssuri/automount_check_solaris.sh


i disabled host key checking, set batch mode to yes, reduced connection timeout to a mere 3 seconds & finally specified -q to signify that I wanted a quite ssh login.

I assigned all the ssh options I wanted to use in a variable & then used that variable with the ssh command to connect to some servers, the names of which were in a list looped over in a for loop & run a local script remotely by using "bash -s".

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...