Wednesday, August 15, 2012

Perl Expect script (auto login)

This script basically takes hostname from "serverlist" and login one by one on servers and run specified commands.

Required: 

Perl

Expect perl module

Install Expect module using CPAN shell:

#perl -MCPAN -e shell

cpan>install Expect


Script:

#!/usr/bin/perl
use Expect;
my $timeout = 1;

$i = 0;

@hostnm = `cat ./serverlist`;

foreach(@hostnm)
{
my $sys_user_pass = 'myPassword';
my $exp = Expect->spawn("ssh -l spatel $hostnm[$i]");
$exp->expect($timeout,

[ 'password: $' => sub {
                         $exp->send("$sys_user_pass\r");
                         exp_continue; }
       ],
         '-re', qr'[#>:] $'
);

$exp->send("sudo -k\n");
$exp->send("sudo touch /root/foo.txt\r");

$exp->expect($timeout,
       [ ': $' => sub {
                          $exp->send("$sys_user_pass\n");
                          exp_continue; }
        ],
          '-re', qr'[#>:] $'
);

$exp->soft_close();
$i++;
}