Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I know there is a better way to do this in Perl - would Net:SSH lend a hand here or is there a steep learning curve? Thanks!
for HOST in `cat /tmp/hosts` do MODEL="" USER="" IDLE="" RELEASE="" host $HOST |grep "not found">>/dev/null #Check if the host is switched on and in DNS (due to our autom +agicaldns entry magic) if [ "$?" == "1" ] ; then # Grab the model name from AD (remember to kinit) MODEL=`/opt/adi/bin/adcat.py -x computer $HOST|grep M +odel|awk '{print $3}'` # ssh into the box, pick through the last entries, see + if a user logged into the console rather than via ssh # if so then thats probably the primary user, if nobod +y logged in then we're SOL. USER=`ssh $HOST "last|grep ':0\ + '|awk '{print \\$1}'|head -n1" 2>/dev/null` if [ "x$USER" == "x" ] ; then USER="NO-LOCAL" fi IDLE="0" AVERAGE="0" SUM="0" NUM="0" # SSH into the box, for each sar entry display the cpu + usage and average it for IDLE in `ssh $HOST 'for i in /var/log/sa/sa*; do s +ar -f $i 2>/dev/null; done' 2>/dev/null|awk '{print $7}'|grep -v idle +|sed -e s/...$// ` do SUM=$[$SUM + $IDLE] NUM=$[$NUM + 1] done AVERAGE=$[$SUM / $NUM] RELEASE=`ssh $HOST "uname -r" 2>/dev/null` fi echo "$HOST $MODEL $USER $IDLE $RELEASE" done

Replies are listed 'Best First'.
Re: Usage gathering query
by apl (Monsignor) on Apr 21, 2008 at 18:27 UTC
Re: Usage gathering query
by pc88mxer (Vicar) on Apr 21, 2008 at 20:52 UTC
    I usually don't spend time fixing scripts which already work unless there is a compelling reason to do so. If you are using SSH2, a perl version can reduce the number of ssh calls and thus be a little more efficient. Additionally, a perl version would allow you to refactor the code so that it is more maintainable and perhaps reusable by other programs. For instance, consider replacing code like this:
    MODEL=`/opt/adi/bin/adcat.py -x computer $HOST|grep Model|awk '{print + $3}'`
    with a subroutine like this:
    sub get_model { my $host = shift; ... }
    Even if the initial implementation of this routine is the same as the shell version, by creating this interface you'll be able to change the implementation later. This routine might also be useful in other scripts.

    You can attempt the same refactoring with shell functions, but you won't be able to pass around complex data structures which will prove to be limiting. For instance, it is clear that the adcat.py returns a lot of information about a host, and being able to pass that information back as a hash is much more efficient (and natural) than writing separate get routines for each attribute.

    If you need help using Net::SSH or Net::SSH::Perl, just let us know.