я пытаюсь понять
Expect
Модуль Perl.
Я хочу взять значение и машину из $var
, но я не смог заставить свой код работать, даже если использовал регулярные выражения.
Я хочу взять из $var
машину и значение из командной строки (например, машина 1 - 7), но я не знаю, почему она печатает $var
в терминале, поскольку я не вызывал $var
переменная
$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>";
}
}
]
);
}
Выход
<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