I'm trying to understand the
Expect
Perl module.
I want to take the value and the machine from $var
, but I couldn't make my code work even if I used regular expressions.
I want to take from $var
the machine and the value from the command prompt (like machine 1 - 7) but I don't know why it prints $var
in the terminal as I didn't call the $var
variable
$Expect::Exp_Internal =0;
my $admin_user = "root";
my $timeout = 40;
my $prompt = '~]#';
my @devices =qw(
machine1
machine2
machine3);
foreach my $device (@devices){
my $exp = Expect->spawn("ssh", "-o", "UserKnownHostsFile /dev/null", "root\@$device");
$exp->log_user(0);
my $seen_user = 0;
$exp->expect(
$timeout,
[
qr/connecting \(yes\/no\)\? / => sub {
my $self = shift;
$self->send("yes\r");
exp_continue;
}
],
[
qr/User: ?/ => sub {
my $self = shift;
if ( $seen_user == 1 ) {
$var .= "Bad password on $device \n<br>";
$exp->soft_close();
}
# $self->send("$admin_user\n<br>");
$seen_user = 1;
exp_continue;
}
],
[
qr/$prompt/ => sub {
my $self = shift;
# print 'first_prompt';
}
],
[
'timeout' => sub {
$var .= "timed out during login on $device\n<br>";
}
]
);
$exp->log_user(1);
# This following line is printed, without being called:
my $var = $exp->send("ps -aef | grep -i app | wc -l\n");
#$var =~ s/\D+//g;
#print 'numbers'.$var;
print $var;
undef $var;
my $logout_sent = 0;
$exp->expect(
$timeout,
[
qr/$prompt/ => sub {
my $self = shift;
$exp->log_user(0);
# $self->send("ps -aef | grep -i sql | wc -l\r");
$self->send("logout\r");
$logout_sent = 1;
exp_continue;
}
],
}],
[
qr/\(y\/N\)/ => sub {
my $self = shift;
$self->send("y");
print "ok\n<br>";
# exit 0;
}
],
[
'timeout' => sub {
print "timed out waiting for prompt\n<br>";
# exit 1;
}
],
[
'eof' => sub {
if ($logout_sent) {
$var .= "succesfully logged out from the $device\n<br>";
#exit 0;
}
else {
$var .="unexpected eof waiting for prompt on $device\n<br>";
}
}
]
);
}
The Output
<br>ps -aef | grep -i app | wc -l
7
[root@machine1 ~]# succesfully logged out from the machine1
<br>ps -aef | grep -i app | wc -l
9
[root@machine2 ~]# succesfully logged out from the machine2
<br>ps -aef | grep -i app | wc -l
7
[root@machine3 ~]# succesfully logged out from the machine3
You can get the value of the machine like this:
Then you can get the number of processes like this: