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

2017-10-07 Note added by Athanasius: This node was copied from StackExchange. See also Re: Extract specify values in file log using perl.


I am newbie in Perl programming and currently trying to use Net::OpenSSH module in my code, my new code as below which the task is to run multiple command in remote server, Code as below::

foreach $s (@servers) { my $ssh = Net::OpenSSH->new("$username\@$s", timeout=>30); $ssh->error and die "Unable to connect: " . $ssh->error; print "Connected to $s\n"; my $fh = $ssh->capture("df -k /home/ | tail -1") or die "Unable to run + command\n"; my @df_arr = split(/\s+/, $fh); print "$s: Disk space /home/ = $df_arr[3] \n"; my $fh1 = $ssh->capture("svmon -G -O unit=GB | grep memory") or die "U +nable to run command\n"; my @sv_arr = split(/\s+/, $fh1); print "$s: Free memory = $sv_arr[3] \n\n"; close $fh; undef $ssh; }

This code is not so nice since I plan to simplify and reduce a line as many as possible. Does there are any techniques or methods that I can use to simplify this code?

Replies are listed 'Best First'.
Re: Remotely collect server data using Net::OpenSSH Perl
by Corion (Patriarch) on Sep 06, 2017 at 12:33 UTC

    You don't need to read the content into a scalar then split it. Instead, directly assign to an array, like the documentation of Net::OpenSSH shows:

    my @df_arr = $ssh->capture("df -k /home/ | tail -1") or die "Unable to + run command\n"; print "$s: Disk space /home/ = $df_arr[3] \n";

    I find it very confusing if you name a variable $fh when it is not a filehandle.

    If you want to make your code more concise, consider the introduction of different routines which return information given a server connection:

    sub disk_space { my( $ssh, $dir ) = @_; my @df_arr = $ssh->capture("df -k '$dir' | tail -1") or die "Unabl +e to run command\n"; print "Disk space $dir = $df_arr[3]\n"; } disk_space( $ssh, '/home/' );
Re: Remotely collect server data using Net::OpenSSH Perl
by thanos1983 (Parson) on Sep 06, 2017 at 15:16 UTC

    Hello IruP,

    Fellow monk Corion has provided you an answer to your problem. I think you can learn also a lot by reading a similar question multiple machines disk space alert.

    Hope this helps, BR.

    Seeking for Perl wisdom...on the process of learning...not there...yet!