-
Notifications
You must be signed in to change notification settings - Fork 0
/
deal_ssh_cmd_timeout.pl
98 lines (93 loc) · 2.4 KB
/
deal_ssh_cmd_timeout.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#! /usr/bin/perl
use warnings;
use strict;
use Expect;
use diagnostics;
my $pid = fork();
if ($pid) {
print "Started child process id: $pid\n";
} elsif ($pid == 0) {
cmd("bash /home/automation/test.sh");
exit $?;
} else {
print("fork error!");
exit 1;
}
$SIG{TERM} = sub { kill TERM => $pid};
$SIG{INT} = sub { kill INT => $pid};
sleep(60);
my $status = -1;
kill TERM => $pid;
sleep 1 and kill INT => $pid if kill 0 => $pid;
sleep 1 and kill KILL => $pid if kill 0 => $pid;
exit $status;
#print "Waiting for the child process to complete...\n";
#waitpid ($pid, 0);
#print "The child process has finished executing.\n\n";
sub cmd {
my $exp = new Expect;
my $cmd = shift;
my $timeout = 10;
$exp->raw_pty(1);
$exp->log_user(0);
$exp->spawn("ssh root\@10.138.25.141 -p 22");
$exp->expect($timeout,
[
qr'login: $',
sub {
my $fh = shift;
$fh->send("automation\r");
exp_continue;
}
],
[
'[Pp]assword: $',
sub {
my $fh = shift;
print $fh "password\r";
exp_continue;
}
],
[
eof =>
sub {
#die "ERROR: premature EOF in login.\n";
die "no password prompt: $! --- $@\n";
}
],
[
timeout =>
sub {
die "No login.\n";
}
],
'-re', qr'[#>:] $', #' wait for shell prompt, then exit expect
);
print("$cmd ..");
$| = 1;
$exp->send("$cmd \r");
my ($matched_pattern_position,
$error,
$successfully_matching_string,
$before_match,
$after_match) =
$exp->expect($timeout,
[
'[Pp]assword: $',
sub {
my $fh = shift;
print $fh "password\n";
exp_continue;
}
],
[
timeout =>
sub {
die "did not find prompt.\n";
}
],
'-re', qr'[#>:] $', #' wait for shell prompt, then exit expect
);
#print "<<<1.$error \n"."2.$before_match \n"."3.$successfully_matching_string \n"."4.$after_match>>> \n";
print($before_match);
}