ssh_pbs.pl for SGE batch systems

#!/usr/bin/perl
#
# A program to run a command via ssh on the set of nodes in a pbs job
#
# Galen Arnold, NCSA, 2/14/2002
#
# adapted to SGE and Ranger 3/26/2008

use English;
use Getopt::Long;

&Getopt::Long::Configure( 'noignorecase', 'no_autoabbrev');
$stat = Getopt::Long::GetOptions(
      'help|h'           => \$print_help,
      'skip=s'           => \$opt_s,
      'n=s'            => \$opt_n
      );

# Don't continue if there are any unknown options on command line
if ($Getopt::Long::error != 0)
{
  exit;
}

if (defined($print_help))
{
print STDERR <
     ssh to only the first N nodes of the job
  -skip 
     ssh to every Mth node [including the first] in the job
     This will ssh to every Mth node of the first N nodes when combined
     with the -n option.

MYEOF

exit;
}
$myargc= scalar(@ARGV);

if ($myargc < 2)
{
        print "usage: $PROGRAM_NAME [OPTIONS] pbs_jobid \"/some/command1; /another/command2\"\n";
        exit;
}

$nodes= `qstat -t | uniq -c | grep $ARGV[0] | cut -d@ -f2 | cut -d'.' -f1`;

(@nodes)= split /\n/, $nodes;

$prev_node="";
$nodecount=0;
$skipcount=0;
foreach $node (@nodes)
{
        ($node)= split/\//, $node;
        if (!($prev_node =~ /$node/))
        {
                # for -skip opt, only ssh when $skipcount is divisible by $opt_s                #
                # when -skip=M and -n=N are combined, this will skip stride M
                # through the first N nodes
                if (defined($opt_s))
                {
                        if (($skipcount % $opt_s) == 0)
                        {
                                $output=`ssh -q -x $node $ARGV[1]`;
                                print "$node: $output";
                        }
                        $skipcount++;
                }
                else
                {
                        $output=`ssh -q -x $node $ARGV[1]`;
                        print "$node: $output";
                }

                # for -n opt, just ssh to the 1st $opt_n nodes, then exit
                if (defined($opt_n))
                {
                        $nodecount++;
                        if ($nodecount >= $opt_n)
                        {
                                exit;
                        }
                }
        }
        $prev_node= $node;
}