2009년 3월 16일 월요일

SSH Auto Login with Perl(Ouput String Parse)

#!/usr/bin/perl
use Expect;
$Expect::Debug = 0; #Debug Level 0~3
#$Expect::Log_Stdout = 0; #Screen Log Output On/Off
#printf "Total Option Count: %d\n", $#ARGV;

if ($#ARGV lt 3) { die "Not Options ex)./ssh_autologin.pl 'IP' 'ID' 'PASSWORD' 'COMMAND'\n"; }
$ip = $ARGV[0];
$id = $ARGV[1];
$pwd = $ARGV[2];
$cmd = $ARGV[3];
my $exp = Expect->spawn("ssh -l $id $ip");
my $timeout = 10;
$retry = 0;

$exp->expect($timeout, [qr 'password: $' => \&inputpassword], [qr /][$|#] $/ => \&getcmd], [qr /connecting \(yes\/no\)\?\s*$/ => \&inputyes], [timeout => \&timeouterr],);

sub timeouterr
{
die "No Login(Timeout)\n";
}

sub inputpassword
{
my $exp = shift;
if ($retry > 0)
{
die "Login Error(Password)\n";
}
$exp->send("$pwd\n");
$retry++;
exp_continue;
}

sub inputyes
{
my $exp = shift;
$exp->send("yes\n");
exp_continue;
}

sub getcmd
{
my $exp = shift;
$exp->log_file("ssh_autologin.log","w"); #logfile save
$exp->send("$cmd\n");
$exp->expect(1); #sleep for $output
my $output = $exp->before(); #$exp->send("$cmd\n"); value
my @array = split("\n",$output);
my $result = "";
for (my $i = 1; $i < $#array; $i++) #first&last line remove
{
$result = $result."$array[$i] \n";
#printf("Array %d : %s \n", $i, $array[$i]);
}
print $result;

$exp->send("date\n");
$exp->send("exit\n");
$exp->soft_close();
$exp->hard_close();
}

실행 방법
[root@waf cstudy]# ./ssh_autologin.pl '203.239.130.161' 'root' 'pwd' 'ps -ef'

Perl Expect 설치 방법
[root@waf cstudy]# cpan

cpan shell -- CPAN exploration and modules installation (v1.7602)
ReadLine support enabled

cpan> install expect
CPAN: Storable loaded ok
Going to read /root/.cpan/Metadata
.
.
.
cpan> quit
Lockfile removed.
[root@waf cstudy]#

댓글 없음:

댓글 쓰기