CGI Perl script for running remote commands on multiple machines
September 25, 2012 Leave a comment
#!/usr/bin/perl -w
use CGI qw(:standard);
use Net::SSH::Expect;
$serverr = param(‘servers’);
$passwordd = param(‘pass’);
$commandd = param(‘command’);
$selection = param(‘format’);
@server = split (‘ ‘ ,$serverr);
@password = split (‘ ‘ ,$passwordd);
`>/error`;
$tie= “/error”;
open ERR, “>>$tie”;
# taking the server from the list
foreach $serv (@server) {
$ping = `ping $serv`;
if ($ping =~/alive/){
foreach $pwd (@password)
{
log_server ();
}
}else {
#report error
print ERR “$serv is not reachable or unknown \n”;
}
next;
}
#sub routine for the login engine
sub log_server {
$ssh = Net::SSH::Expect->new(
host => “$serv”,
password => “$pwd”,
user => ‘root’,
raw_pty => 1,
timeout => 2
);
$working = $ssh->login ();
if ($working =~/Last/){
$uname = $ssh->exec(“$commandd”);
}else{
next;
}
if ( $selection eq “excel”){
excel();
}else {
screen ();
}
sub screen {
print <<END;
—————————————————————-
Server Name: $serv
—————————————————————-
$uname
—————————————————————-
END
}
sub excel {
print “content-type: application/vnd.ms-excel\n”;
print “content-disposition: attachment; filename=text.xls\n\n”;
print “########################################################\n”;
print “Server Name:$serv\n”;
print “########################################################\n”;
print $uname;
}
}
$ssh->close ();
close ERR;
$x = `cat /error`;
print <<END;
##############################################################
Below servers having errors
$x
END
Here is theĀ corresponding html page:
<body bgcolor=”#4682B4″>
<form action=”/cgi-bin/echo1.cgi” METHOD=”POST”>
<div class=”widget”>Enter Server Names / IPs : <textarea name=”servers”></textarea></div>
<div> Enter available passwords :<textarea name=”pass”></textarea> </div>
<p>
<div>Enter a command or script :<input name=”command” size=”20″></div>
</p>
<p>
<b>Select output format:</b><br>
<input type=”radio” name=”format” value=”screen”>Display on screen<br>
<input type=”radio” name=”format” value=”excel”>Download as excel sheet<br>
<div><input type=”submit”></div>
</p>
<img src=”caution.gif” width=”75″ height=”50″ />
<font size=”3″ color=”red”><b> I am root.
I can destroy anything..!</b></font>
</form>
<p>
<a href=”mailto:rash210210@gmail.com”>Feedback</a>
</p>
</body>