Saturday 7 January 2017

Using awk over a remote ssh connection

While trying to retrieve information from multiple servers in a script we may require formatting of the output via awk or sed. In this article I'll describe how we can use awk over ssh & some best practices while writing scripts involving lists of files.

As an example, I've taken up a requirement I recently had at work where I needed to check a list of servers for finger service & separate the servers on which service was enabled/disabled.

A couple of best practice tips:


  • When using files as input to for loops involving server names, use command line arguments to supply input files instead of hard coding the file name within the script. This enhances re-usability of the code.
  • Now that we are feeding the input via a command line argument, make sure that the user enters it while running the script & exit otherwise.
  • After ensuring that the user supplies the command line argument, put in another check to make sure that the supplied input is a non-empty file & exit otherwise.

So, with tips out of the way, let's see how we'll use awk over a remote ssh connection.
Generally when we run a command over ssh we include the commands withing singe quotes(''). But this won't work if we are using awk since it uses single quotes as well. Next if we need to print a particular column or field and we specify the usual $col, that won't work either because it'll get interpreted as a variable.

The fixes for the above mentioned problems are as follows:


  • Use double quotes for enclosing the commands to be run via ssh.
  • For specifying the field number with awk, use a backslash (\) to escape it.


Given below is the working script I wrote based on the above mentioned discussion:


#!/usr/bin/bash

##check that server list exists##

if [ $# != 1 ] ; then
        echo "script usage: $0 <server list>"
        exit

elif [ ! -s ${1} ] ; then

        echo "server list file not found. Exiting"
        exit
fi

##
        for name in `cat ${1}`
        do
        
        result=$(ssh -o StrictHostKeyChecking=no -q ${name} "svcs -a | grep finger | awk '{print \$1}' ")
        
        if [ ${result} == "disabled" ] ; then
                echo ${name} >> /export/home/ssuri/finger_disabled.txt
        elif [ ${result} == "online" ] ; then 
                echo ${name} >> /export/home/ssuri/finger_enabled.txt
        else 
                echo "could not get status of service on ${name}"
                echo "please log in and check"
        fi      
        done
        
        echo "list of servers on which finger is enabled is /export/home/ssuri/finger_enabled.txt"
        echo "list of servers on which finger is disabled is /export/home/ssuri/finger_disabled.txt"

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...