Mnet/Expect/Cli.pm

filter: Statementstmt 83.2% 218 / 262 Branchbran 75.5% 71 / 94 Conditioncond 54.1% 39 / 72 MC/DCmcdc 26.8% 11 / 41 Subroutinesub 80.9% 17 / 21 Podpod 100% 8 / 8 totaltotal 73.0% 364 / 498 CC 83 SCAR 27.8
CC
83
Cov
77%
_login
31.6
_command_expect
22.9
new
18.3
CRAP 16.1
« Mnet/T.pm ↑ Summary Mnet/IP.pm »
1 package Mnet::Expect::Cli;
2  
3 =head1 NAME
4  
5 Mnet::Expect::Cli - Expect sessions to command line interfaces
6  
7 =head1 SYNOPSIS
8  
9 # refer also to Mnet::Expect
10 use Mnet::Expect::Cli;
11  
12 # prepare ssh command with host/key checking disabled
13 my @ssh = qw(
14 ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null
15 );
16  
17 # connect via ssh for user to specified host, prompt for password
18 my $expect = Mnet::Expect::Cli->new({
19 spawn => [ @ssh, "user\@1.2.3.4" ],
20 password_in => 1,
21 });
22  
23 # gather output for specified command over ssh
24 my $output = $expect->command("ls");
25  
26 # close ssh session
27 $expect->close;
28  
29 =head1 DESCRIPTION
30  
31 Mnet::Expect::Cli can be used to spawn L<Expect> processes, which can be used
32 to programmatically control command line sessions to devices, with support
33 for L<Mnet> options, logging, caching, and testing.
34  
35 Refer to the L<Mnet::Expect> module, whose methods are inherited by objects
36 created with this module. Also refer to L<Mnet::Expect::Cli::Ios>, which
37 builds on this module,
38  
39 =head1 METHODS
40  
41 Mnet::Expect::Cli implements the methods listed below.
42  
43 =cut
44  
45 # required modules
46 39 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
47 39 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
48 39 ▶use parent qw( Mnet::Expect );
Subroutine BEGIN: called CC=1 SCAR=0.0
49 39 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 39 ▶use Mnet;
Subroutine BEGIN: called CC=1 SCAR=0.0
51 39 ▶use Mnet::Dump;
Subroutine BEGIN: called CC=1 SCAR=0.0
52 39 ▶use Mnet::Opts::Cli::Cache;
Subroutine BEGIN: called CC=1 SCAR=0.0
53 39 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
54  
55  
56  
57 34 ▶sub new {
Subroutine new: called CC=16 SCAR=29.1
Pod documented
58  
59 =head2 new
60  
61 $expect = Mnet::Expect::Cli->new(\%opts)
62  
63 This method can be used to create new Mnet::Expect::Cli objects.
64  
65 The following input opts may be specified, in addition to options documented
66 in the L<Mnet::Expect> module new method:
67  
68 delay millseconds delay for command prompt detection
69 eol_unix default true for output with unix /n eol chars only
70 failed_re set to speed login failures, disabled by default
71 log_login default undef uses Mnet::Expect log_expect logging
72 paging_key default space key to send for pagination prompt
73 paging_re default handles common prompts, refer to paging_re
74 password set to password for spawned command, if needed
75 password_in stderr prompt for stdin entry of password if not set
76 password_re undef to skip password/code/phrase prompt detection
77 prompt_re undef to disable post-login prompt detect, see below
78 timeout seconds for Expect restart_timeout_upon_receive
79 username set to username for spawned command, if needed
80 username_re undef to skip login/user/username promt detection
81  
82 An error is issued if there are login problems.
83  
84 For example, the following call will start an ssh expect session to a device
85 with host key checking disabled:
86  
87 # refer to SYNOPSIS example for ssh with host/key checks disabled
88 my $expect = Mnet::Expect::Cli->new({
89 spawn => "ssh user@1.2.3.4", password_in => 1
90 });
91  
92 Set failed_re to detect failed logins faster, as long as there's no conflict
93 with text that appears in login banners. For example:
94  
95 (?i)(closed|error|denied|fail|incorrect|invalid|refused|sorry)
96  
97 A default prompt_re regex string is used by this method to detect and confirm
98 the specific prompt text in use on a connected system, after login. When this
99 happens prompt_re is rewritten with the detected prompt text, which is used by
100 the command method to detect the end of command output.
101  
102 By default prompts ending with $ % # : > are detected, this can be changed by
103 setting prompt_re to a different regex string when calling the new method, or
104 disabled by setting to undef, note that prompt_re needs to match the entire
105 prompt line, not just the ending:
106  
107 (^|\r|\n)\S.*(\$|\%|#|:|>) ?(\r|\n|$)
108  
109 Refer also to the prompt_re method which can be used to examine or change
110 prompt_re for an existing session returned by this method.
111  
112 Refer to the L<Mnet::Expect> module for more information.
113  
114 =cut
115  
116 # read input class and options hash ref merged with cli options
117 34 ▶ my $class = shift // croak("missing class arg");
Condition50%1/2
shift() // croak("missing class arg")
l!l
340
MC/DC0%0/1
shift() // croak("missing class arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
118 34 ▶ my $opts = Mnet::Opts::Cli::Cache::get(shift // {});
Condition50%1/2
shift() // {}
l!l
340
MC/DC0%0/1
shift() // {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
119  
120 # create log object with input opts hash, cli opts, and pragmas in effect
121 # ensures we can log correctly even if inherited object creation fails
122 34 my $log = Mnet::Log::Conditional->new($opts);
123 34 $log->debug("new starting");
124  
125 # create hash that will become new object from input opts hash
126 34 my $self = $opts;
127  
128 # note default options for this class, refer also to Mnet::Expect defaults
129 # includes recognized cli opts and opts for this object
130 # update perldoc for this sub with changes
131 34 my $defaults = {
132 _command_cache_content => {}, # internal, see _command_cache_clear
133 _command_cache_counter => 0, # internal, see _command_cache_clear
134 delay => 250,
135 eol_unix => 1,
136 # failed_re default undef to be safe, refer to perldoc for more info
137 # junos telnet =~ /^Login incorrent/m
138 failed_re => undef,
139 log_login => undef,
140 paging_key => ' ',
141 paging_re => '(--more--|---\(more( \d\d?%)?\)---)',
142 password => undef,
143 password_in => undef,
144 # password_re default based on educated guess, specifics noted below:
145 # junos telnet =~ /^Password:$/m
146 password_re => '(?i)pass(code|phrase|word):?\s*(\r|\n)?$',
147 # prompt_re default based on educated guess, specifics noted below:
148 # junos telnet =~ /^\S+> $/mi
149 prompt_re => '(^|\r|\n)\S.*(\$|\%|#|:|>) ?(\r|\n|$)',
150 record => undef,
151 replay => undef,
152 timeout => 30,
153 username => undef,
154 # username_re default based on educated guess, specifics noted below:
155 # junos telnet =~ /^login: $/m
156 username_re => '(?i)(login|user(name)?):?\s*(\r|\n)?$',
157 };
158  
159 # update future object $self hash with default opts
160 34 foreach my $opt (sort keys %$defaults) {
161 578 ▶ $self->{$opt} = $defaults->{$opt} if not exists $self->{$opt};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{$opt} 401 177 578
162 }
163  
164 # debug opts, hide internal opts starting w/underscore, and passowrd
165 34 foreach my $opt (sort keys %$self) {
166 870 ▶ if ($opt !~ /^_/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opt =~ /^_/) 802 68 870
167 802 my $value = Mnet::Dump::line($self->{$opt});
168 802 ▶ if ($opt eq "password" and defined $self->{$opt}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt eq "password" and defined $self->{$opt}) 4 798 802
Condition100%3/3
$opt eq "password" and defined $self->{$opt}
!ll&&!rl&&r
768304
MC/DC100%2/2
$opt eq "password" and defined $self->{$opt}
$opt eq "password" defined $self->{$opt}
Truth table100%3/3
A and B
A= $opt eq "password"B= defined $self->{$opt}
ABresult
0X0
100
111
169 4 ▶ $value = "**** (redacted)" if $self->{$opt} ne "";
Branch: 1 branch
BranchTrueFalseTotal
if $self->{$opt} ne "" 4 0 4
170 }
171 802 $log->debug("new opt $opt = $value");
172 }
173 }
174  
175 # warn if timeout is not an even number, as per perldoc Expect
176 $log->warn("timeout $self->{timeout} should be even number, as per Expect")
177 34 ▶ if $self->{timeout} and $self->{timeout} % 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"timeout"} and $self->{"timeout"} % 2 0 34 34
Condition33%1/3
$self->{"timeout"} and $self->{"timeout"} % 2
!ll&&!rl&&r
0340
MC/DC0%0/2
$self->{"timeout"} and $self->{"timeout"} % 2
$self->{"timeout"} $self->{"timeout"} % 2
Truth table33%1/3
A and B
A= $self->{"timeout"}B= $self->{"timeout"} % 2
ABresult
0X0
100
111
178  
179 # set _no_spawn if replay is set so Mnet::Expect skips spawn
180 34 ▶ $self->{_no_spawn} = 1 if $self->{replay};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"replay"} 3 31 34
181  
182 # call Mnet::Expect to create new object
183 34 $log->debug("new calling Mnet::Expect::new");
184 34 $self = Mnet::Expect::new($class, $self);
185  
186 # return undef if new Mnet::Expect object could not be created
187 34 ▶ if (not $self) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self) 0 34 34
188 0 $log->debug("new Mnet::Expect object failed, returning undef");
189 0 return undef;
190 }
191  
192 # return if we are executing a replay
193 34 ▶ if ($self->{replay}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"replay"}) 3 31 34
194 3 $self->debug("new finished, replay in effect, returning $self");
195 3 return $self;
196 }
197  
198 # set timeout for complete output stall only, not output completion
199 31 $self->expect->restart_timeout_upon_receive(1);
200  
201 # return undef if login does not succeed
202 31 ▶ if (not $self->_login) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_login) 0 28 28
203 0 $self->debug("new finished, login failed, returning undef");
204 0 return undef;
205 }
206  
207 # finished new method, return Mnet::Expect::Cli object
208 28 $self->debug("new finished, returning $self");
209 28 return $self;
210 }
211  
212  
213  
214 31 ▶sub _login {
Subroutine _login: called CC=18 SCAR=34.5
215  
216 # $ok = $self->_login
217 # purpose: used to authenticate expect session
218 # $ok: set true on success, false on failure
219  
220 # read input object
221 31 ▶ my $self = shift // die "missing self arg";
Condition50%1/2
shift() // die("missing self arg")
l!l
310
MC/DC0%0/1
shift() // die("missing self arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
222 31 $self->debug("_login starting");
223  
224 # if log_level defined then set log_expect for login, note prior log_expect
225 31 my $prior = undef;
226 31 ▶ if (defined $self->{log_login}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"log_login"}) 1 30 31
227 1 $prior = $self->log_expect($self->{log_login});
228 }
229  
230 # if username is set then wait and respond to username_re prompt
231 31 ▶ if (defined $self->{username}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"username"}) 4 27 31
232 4 _login_expect($self, "username_re");
233 3 $self->expect->send("$self->{username}\r");
234 }
235  
236 # if password is set then wait and respond to password_re prompt
237 # prompt user for password if password not set and password_in is set
238 # _log_filter used to keep password out of Mnet::Expect->log
239 # reset log_expect level back to it's prior value before returning
240 30 ▶ if (defined $self->{password} or $self->{password_in}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"password"} or $self->{"password_in"}) 3 27 30
Condition66%2/3
defined $self->{"password"} or $self->{"password_in"}
l!l&&r!l&&!r
3027
MC/DC50%1/2
defined $self->{"password"} or $self->{"password_in"}
defined $self->{"password"} $self->{"password_in"}
Truth table66%2/3
A or B
A= defined $self->{"password"}B= $self->{"password_in"}
ABresult
1X1
011
000
241 3 _login_expect($self, "password_re");
242 2 my $password = $self->{password};
243 2 ▶ if (not defined $password and $self->{password_in}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $password and $self->{"password_in"}) 0 2 2
Condition33%1/3
not defined $password and $self->{"password_in"}
!ll&&!rl&&r
200
MC/DC0%0/2
not defined $password and $self->{"password_in"}
not defined $password $self->{"password_in"}
Truth table33%1/3
not(A) and B
A= not defined $passwordB= $self->{"password_in"}
ABresult
0X0
100
111
244 0 ▶ if ($self->{password_in}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'password_in'}) { } 0 0 0
245 0 $self->debug("_login password_in prompt starting");
246 {
247 0 ▶ local $SIG{INT} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
248 0 system("stty echo 2>/dev/null");
249 0 syswrite STDERR, "\n\n";
250 0 $self->fatal("interrupt signal received");
251 0 };
252 0 syswrite STDERR, "\nEnter $self->{password_in}: ";
253 0 system("stty -echo 2>/dev/null");
254 0 chomp($password = <STDIN>);
255 0 system("stty echo 2>/dev/null");
256 0 syswrite STDERR, "\n";
257 };
258 0 $self->debug("_login password_in prompt finished");
259 } else {
260 0 $self->fatal("password or password_in required and not set");
261 0 ▶ $self->log_expect($prior) if defined $self->{log_login};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"log_login"} 0 0 0
262 0 return undef;
263 }
264 }
265 2 $self->debug("_login sending password");
266 2 $self->{_log_filter} = $password;
267 2 $self->expect->send("$password\r");
268 }
269  
270 # return true if prompt_re was set undef
271 # clear any password from expect session and clear _log_filter
272 # reset log_expect level back to it's prior value before returning
273 29 ▶ if (not defined $self->{prompt_re}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"prompt_re"}) 1 28 29
274 1 $self->debug("_login detect prompt skipped, prompt_re set undef");
275 1 $self->debug("_login finished, returning true");
276 1 Time::HiRes::usleep($self->{delay}*1000);
277 1 $self->expect->clear_accum;
278 1 $self->{_log_filter} = undef;
279 1 ▶ $self->log_expect($prior) if defined $self->{log_login};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"log_login"} 0 1 1
280 1 return 1;
281 }
282  
283 # return true if we can detect command prompt
284 # send a carraige return and ensure we get the same prompt back
285 # clear _log_filter, which may have been set when password was sent
286 # clear expect buffer before sending cr, to flush out banner text, etc
287 # set prompt_re to detected command prompt when finished
288 # prompt_truncate in Mnet::Expect::Cli::Ios must match prompt_re changes
289 # reset log_expect level back to it's prior value before returning
290 28 my ($prompt1, $prompt2, $attempts) = ("", "", 3);
291 28 foreach my $attempt (1.. $attempts) {
292 55 $self->debug("_login detect prompt attempt $attempt");
293 55 ▶ $prompt1 = _login_expect($self, "prompt_re") // return undef;
Condition50%1/2
_login_expect($self, "prompt_re") // (return undef)
l!l
540
MC/DC0%0/1
_login_expect($self, "prompt_re") // (return undef)
_login_expect($self, "prompt_re")
Truth table50%1/2
A
A= _login_expect($self, "prompt_re")
Aresult
11
00
294 54 $prompt1 =~ s/(^(\r|\n)|(\r|\n)$)//;
295 54 $self->{_log_filter} = undef;
296 54 ▶ if ($prompt1 ne "" and $prompt1 eq $prompt2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prompt1 ne '' and $prompt1 eq $prompt2) { } 27 27 54
Condition66%2/3
$prompt1 ne "" and $prompt1 eq $prompt2
!ll&&!rl&&r
02727
MC/DC50%1/2
$prompt1 ne "" and $prompt1 eq $prompt2
$prompt1 ne "" $prompt1 eq $prompt2
Truth table66%2/3
A and B
A= $prompt1 ne ""B= $prompt1 eq $prompt2
ABresult
0X0
100
111
297 27 $prompt1 =~ s/(\\|\/|\(|\)|\$)/\\$1/g;
298 27 $self->{prompt_re} = '(^|\r|\n)'.$prompt1.'\r?$';
299 27 $self->debug("_login detect prompt_re = /$self->{prompt_re}/");
300 27 $self->debug("_login finished, returning true");
301 27 ▶ $self->log_expect($prior) if defined $self->{log_login};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"log_login"} 1 26 27
302 27 return 1;
303 } else {
304 27 $self->debug("_login detect prompt sending cr");
305 27 Time::HiRes::usleep($self->{delay}*1000);
306 27 $self->expect->clear_accum;
307 27 $self->expect->send("\r");
308 27 $prompt2 = $prompt1;
309 }
310 }
311  
312 # reset log_expect level back to it's prior value before returning
313 0 ▶ $self->log_expect($prior) if defined $self->{log_login};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"log_login"} 0 0 0
314  
315 # finished _login method, return true false for failure
316 0 $self->debug("_login finished, returning false");
317 0 return 0;
318 }
319  
320  
321  
322 62 ▶sub _login_expect {
Subroutine _login_expect: called CC=7 SCAR=19.7
323  
324 # $match = _login_expect($self, $re)
325 # purpose: wait for specified login prompt, output debug and error messages
326 # $self: current Mnet::Expect::Cli object
327 # $re: set to keyword username_re, password_re, or prompt_re
328 # $match: set to matched $re text, abort on errors
329 # note: failed_re is checked for first if set
330  
331 # read input object and re args
332 62 ▶ my $self = shift // die "missing self arg";
Condition50%1/2
shift() // die("missing self arg")
l!l
620
MC/DC0%0/1
shift() // die("missing self arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
333 62 ▶ my $re = shift // die "missing re arg";
Condition50%1/2
shift() // die("missing re arg")
l!l
620
MC/DC0%0/1
shift() // die("missing re arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
334 62 $self->debug("_login_expect starting for $re");
335  
336 # expect input username/password/prompt re, also failed_re if defined
337 62 my @matches = ('-re', $self->{$re});
338 62 ▶ unshift(@matches, '-re', $self->{failed_re}) if $self->{failed_re};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"failed_re"} 16 46 62
339 62 my $expect = $self->expect->expect($self->{timeout}, @matches);
340  
341 # note match text, and dump of match text for debug logging
342 62 my $match = $self->expect->match;
343 62 my $match_dump = Mnet::Dump::line($match);
344  
345 # error if none of the prompts were returned
346 62 ▶ if (not $expect) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $expect) { } 0 62 62
elsif ($self->{'failed_re'} and $expect == 1) { } 3 105 108
347 0 $self->fatal("login timed out waiting for $re");
348  
349 # error if failed_re was matched
350 ▶ } elsif ($self->{failed_re} and $expect == 1) {
Condition100%3/3
$self->{"failed_re"} and $expect == 1
!ll&&!rl&&r
46133
MC/DC100%2/2
$self->{"failed_re"} and $expect == 1
$self->{"failed_re"} $expect == 1
Truth table100%3/3
A and B
A= $self->{"failed_re"}B= $expect == 1
ABresult
0X0
100
111
351 3 $self->fatal("login failed_re matched $match_dump");
352 }
353  
354 # finished _login_expect method, return input re match
355 59 $self->debug("_login_expect finished $re, matched $match_dump");
356 59 return $match;
357 }
358  
359  
360  
361 14 ▶sub close {
Subroutine close: called CC=3 SCAR=11.0
Pod documented
362  
363 =head2 close
364  
365 $expect->close($command)
366  
367 This method sends closes the current expect session, sending the optional input
368 command first. Timeouts and disconnects are gracefully handled. Refer to the
369 close method in the L<Mnet::Expect> module for more information.
370  
371 =cut
372  
373 # read input object
374 14 ▶ my $self = shift or croak("missing self arg");
Branch: 1 branch
BranchTrueFalseTotal
my $self = shift() or croak("missing self arg") 14 0 14
375 14 my $command = shift;
376 14 $self->debug("close starting");
377  
378 # send command if specified, gracefully handle timeouts
379 14 ▶ $self->command($command, undef, [ "" => undef ]) if defined $command;
Branch: 1 branch
BranchTrueFalseTotal
if defined $command 9 5 14
380  
381 # call parent module close method
382 14 $self->SUPER::close();
383  
384 # finished close method
385 14 $self->debug("close finished");
386 14 return;
387 }
388  
389  
390  
391 49 ▶sub command {
Subroutine command: called CC=9 SCAR=22.1
Pod documented
392  
393 =head2 command
394  
395 $output = $expect->command($command, $timeout, \@prompts)
396  
397 This method returns output from the specified command sent to the current
398 expect cli session, or undefined if there was a timeout.
399  
400 Note that this method caches command output, so that if the exact same command
401 is sent repeatedly the first output from the connected device will be returned
402 for subsequent calls. Refer to the command_cache_clear method for more info.
403  
404 The optional timeout argument can be used to override the default timeout for
405 the new object.
406  
407 The optional prompts reference argument can be used to handle prompts that may
408 occur when running a command, such as confirmation prompts. It should contain
409 pairs of regex strings and responses. The regex string values should be what
410 goes in between the forward slash characters of a regular expression. The
411 response can be a string that is sent to the expect session with or without a
412 carraige return, or may be a code reference that gets the current object and
413 output as input args and returns a response string. A null prompt regex string
414 is activated for timeouts and disconnects. An undef prompt response causes an
415 immediate return of output.
416  
417 # sends $command, uses default timeout, defines some prompts
418 my $output = $expect->command($command, undef, [
419  
420 # send 1.2.3.4 and carraige return if matched by expect -re /ip/
421 'ip' => "1.2.3.4\r",
422  
423 # code ref
424 'confirm? ' => sub { my $output = shift; return "y" },
425  
426 # returns received output on timeout, might be undef
427 '' => undef,
428  
429 ]);
430  
431 By default the end of command output is recognized using the prompt_re string
432 detected by the new method after login. Refer to the new and prompt_re methods
433 for more information.
434  
435 =cut
436  
437 # read input arguments
438 49 ▶ my $self = shift // croak "missing self arg";
Condition50%1/2
shift() // croak("missing self arg")
l!l
490
MC/DC0%0/1
shift() // croak("missing self arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
439 49 ▶ my $command = shift // croak "missing command arg";
Condition50%1/2
shift() // croak("missing command arg")
l!l
490
MC/DC0%0/1
shift() // croak("missing command arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
440 49 ▶ my $timeout = shift // $self->{timeout};
Condition33%1/3
shift() // $self->{"timeout"}
l!l&&r!l&&!r
0490
MC/DC0%0/2
shift() // $self->{"timeout"}
shift() $self->{"timeout"}
Truth table33%1/3
A // B
A= shift()B= $self->{"timeout"}
ABresult
1X1
011
000
441 49 ▶ my $prompts = shift // [];
Condition100%2/2
shift() // []
l!l
3118
MC/DC100%1/1
shift() // []
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
442 49 $self->debug("command starting, command '$command' (timeout $timeout)");
443  
444 # initialize output
445 49 my $output = undef;
446  
447 # set output from _command_cache_content, if it exists in cache
448 49 ▶ if (exists $self->{_command_cache_content}->{$command}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $self->{'_command_cache_content'}{$command}) { } 1 48 49
elsif ($self->{'replay'}) { } 7 41 48
449 1 $self->debug("command retrieving output from _command_cache_content");
450 1 $output = $self->{_command_cache_content}->{$command};
451  
452 # set output from replay data, if replay option is set
453 } elsif ($self->{replay}) {
454 7 $self->debug("command retrieving output from replay data");
455 7 my $data = Mnet::Test::data();
456 7 $output = $data->{$self->{_command_cache_counter}}->{$command};
457  
458 # retrieve command output from expect session
459 } else {
460 41 $self->debug("command retrieving output from _command_expect");
461 41 $output = $self->_command_expect($command, $timeout, $prompts);
462 41 $self->{_command_cache_content}->{$command} = $output;
463 }
464  
465 # set outut in record data, if record option is set
466 49 ▶ if ($self->{record}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"record"}) 7 42 49
467 7 my $data = Mnet::Test::data();
468 7 $data->{$self->{_command_cache_counter}}->{$command} = $output;
469 }
470  
471 # finished command method, return output
472 49 my $output_dbg = "<undef>";
473 49 ▶ $output_dbg = length($output)." chars" if defined $output;
Branch: 1 branch
BranchTrueFalseTotal
if defined $output 48 1 49
474 49 $self->debug("command finished, returning $output_dbg");
475 49 return $output;
476 }
477  
478  
479  
480 41 ▶sub _command_expect {
Subroutine _command_expect: called CC=22 SCAR=31.3
481  
482 # $output = $self->_command_expect($command, $timeout, \@prompts)
483 # purpose: retrieve command output from expect session, refer to command method
484 # note: command cache, record, and replay, are handled in command sub
485  
486 # read inputs, set default timeout from current object
487 41 ▶ my $self = shift // die "missing self arg";
Condition50%1/2
shift() // die("missing self arg")
l!l
410
MC/DC0%0/1
shift() // die("missing self arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
488 41 ▶ my $command = shift // die "missing command arg";
Condition50%1/2
shift() // die("missing command arg")
l!l
410
MC/DC0%0/1
shift() // die("missing command arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
489 41 ▶ my $timeout = shift // $self->{timeout};
Condition33%1/3
shift() // $self->{"timeout"}
l!l&&r!l&&!r
4100
MC/DC0%0/2
shift() // $self->{"timeout"}
shift() $self->{"timeout"}
Truth table33%1/3
A // B
A= shift()B= $self->{"timeout"}
ABresult
1X1
011
000
490 41 ▶ my $prompts = shift // [];
Condition50%1/2
shift() // []
l!l
410
MC/DC0%0/1
shift() // []
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
491  
492 # return undef if expect session not defined
493 41 ▶ return undef if not $self->expect;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->expect 0 41 41
494  
495 # initialize output to undef
496 41 my $output = undef;
497  
498 # store input prompt regexes and responses, also timeout regex/response
499 # null timeout prompt is separate, it's not an expect -re like others
500 41 my $prompt_regexes = [];
501 41 my $prompt_responses = [];
502 41 my ($timeout_regex_flag, $timeout_response) = (undef, undef);
503 41 ▶ while (@$prompts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$prompts) 53 41 94
504 53 my ($regex, $response) = (shift @$prompts, shift @$prompts);
505 53 ▶ if ($regex eq "") {
Branch: 1 branch
BranchTrueFalseTotal
if ($regex eq '') { } 17 36 53
506 17 $timeout_regex_flag = 1;
507 17 $timeout_response = $response;
508 17 $regex = "(null=timeout)";
509 } else {
510 36 push @$prompt_regexes, $regex;
511 36 push @$prompt_responses, $response;
512 36 $regex = "/$regex/";
513 }
514 53 $response = Mnet::Dump::line($response);
515 53 $self->debug("_command_expect input prompt $regex = $response");
516 }
517  
518 # prepare regexes used for expect call
519 # this includes input prompts, and paging_re if defined
520 41 my $expect_regexes = [];
521 41 push @$expect_regexes, "-re", $_ foreach @$prompt_regexes;
522 41 ▶ push @$expect_regexes, "-re", $self->{paging_re} if $self->{paging_re};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"paging_re"} 41 0 41
523  
524 # send input command to expect session
525 41 $self->debug("_command_expect sending $command");
526 41 $self->expect->send("$command\r");
527  
528 # loop to collect command output and process input prompts
529 41 while (1) {
530  
531 # wait for input prompt regex, or pagination regex and/or prompt regex
532 my $expect = $self->expect->expect($timeout,
533 @$expect_regexes,
534 '-re', $self->{prompt_re},
535 53 );
536  
537 # append new output to prior output
538 53 $output .= $self->expect->before;
539  
540 # process prompt_response for timeout handled by undef prompt_regex
541 # return prior output if response undef or code ref returning undef
542 # otherwise return undef output
543 53 ▶ if (not $expect and $timeout_regex_flag) {
Branch: 4 branches
BranchTrueFalseTotal
if (not $expect and $timeout_regex_flag) { } 15 38 53
elsif (not $expect) { } 1 37 38
elsif ($expect <= scalar @$prompt_regexes) { } 18 19 37
elsif ($self->{'paging_re'} and $expect == scalar(@$prompt_regexes) + 1) { } 1 18 19
Condition100%3/3
not $expect and $timeout_regex_flag
!ll&&!rl&&r
37115
MC/DC100%2/2
not $expect and $timeout_regex_flag
not $expect $timeout_regex_flag
Truth table100%3/3
not(A) and B
A= not $expectB= $timeout_regex_flag
ABresult
0X0
100
111
544 15 $self->debug("_command_expect matched prompts (null=timeout)");
545 15 ▶ $self->_command_expect_prompt($timeout_response, $output) // last;
Condition50%1/2
$self->_command_expect_prompt($timeout_response, $output) // (last)
l!l
015
MC/DC0%0/1
$self->_command_expect_prompt($timeout_response, $output) // (last)
$self->_command_expect_prompt($timeout_response, $output)
Truth table50%1/2
A
A= $self->_command_expect_prompt($timeout_response, $output)
Aresult
11
00
546 0 $output = undef;
547 0 last;
548  
549 # process timeout not handled by undef prompt_regex
550 # returns undef output
551 } elsif (not $expect) {
552 1 $self->debug("_command_expect timeout");
553 1 $output = undef;
554 1 last;
555  
556 # process prompt_response for matched input prompt_regex
557 # return prior output if response undef or code ref returning undef
558 } elsif ($expect <= scalar(@$prompt_regexes)) {
559 18 my $regex = $prompt_regexes->[$expect-1];
560 18 $self->debug("_command_expect matched prompts regex /$regex/");
561 18 $output .= $self->expect->match;
562 18 my $prompt_response = $prompt_responses->[$expect-1];
563 18 ▶ $self->_command_expect_prompt($prompt_response, $output) // last;
Condition100%2/2
$self->_command_expect_prompt($prompt_response, $output) // (last)
l!l
108
MC/DC100%1/1
$self->_command_expect_prompt($prompt_response, $output) // (last)
$self->_command_expect_prompt($prompt_response, $output)
Truth table100%2/2
A
A= $self->_command_expect_prompt($prompt_response, $output)
Aresult
11
00
564  
565 # process prompt_response for matched paging_re
566 # return prior output if response undef or code ref returning undef
567 # expect paging_key so it doesn't appear in output
568 ▶ } elsif ($self->{paging_re} and $expect == scalar(@$prompt_regexes)+1) {
Condition66%2/3
$self->{"paging_re"} and $expect == scalar(@$prompt_regexes) + 1
!ll&&!rl&&r
0181
MC/DC50%1/2
$self->{"paging_re"} and $expect == scalar(@$prompt_regexes) + 1
$self->{"paging_re"} $expect == scalar(@$prompt_regexes) + 1
Truth table66%2/3
A and B
A= $self->{"paging_re"}B= $expect == scalar(@$prompt_regexes) + 1
ABresult
0X0
100
111
569 1 $self->debug("_command_expect matched paging_re");
570 1 ▶ $self->_command_expect_prompt($self->{paging_key}, $output) // last;
Condition50%1/2
$self->_command_expect_prompt($self->{"paging_key"}, $output) // (last)
l!l
10
MC/DC0%0/1
$self->_command_expect_prompt($self->{"paging_key"}, $output) // (last)
$self->_command_expect_prompt($self->{"paging_key"}, $output)
Truth table50%1/2
A
A= $self->_command_expect_prompt($self->{"paging_key"}, $output)
Aresult
11
00
571 1 $self->expect->expect($timeout, '-re', $self->{paging_key});
572  
573 # process prompt_response for matched prompt_re
574 # exit loop if we are not getting any more oupput after a small delay
575 # this allows us to skip prompts that might be embedded in data
576 # otherwise we are getting more data, reset accumulater and continue
577 } else {
578 18 $self->debug("_command_expect matched prompt_re");
579 18 my $match = $self->expect->match;
580 18 Time::HiRes::usleep($self->{delay}*1000);
581 18 my $expect = $self->expect->expect(0, '-re', '(\s|\S)+');
582 18 ▶ last if not $expect;
Branch: 1 branch
BranchTrueFalseTotal
unless $expect 17 1 18
583 1 $self->debug("_command_expect prompt_re detected more output");
584 1 $self->expect->set_accum($self->expect->match);
585 1 $output .= $match;
586 1 next;
587 }
588  
589 # continue loop to collect command output and process input prompts
590 }
591  
592 # remove echod command from start of output, fix eol chars, remove last eol
593 # normalize eol chars to be unix newlines only if eol_unix opt is set
594 41 ▶ if (defined $output) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output) 40 1 41
595 40 $output =~ s/^\s*\Q$command\E\s*\r?\n?//;
596 40 ▶ if ($self->{eol_unix}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"eol_unix"}) 40 0 40
597 40 $output =~ s/\r\n/\n/g;
598 40 $output =~ s/\r/\n/g;
599 }
600 40 $output =~ s/\r$//;
601 40 chomp($output);
602 }
603  
604 # finished _command_expect, return output
605 41 return $output;
606 }
607  
608  
609  
610 34 ▶sub _command_expect_prompt {
Subroutine _command_expect_prompt: called CC=5 SCAR=16.1
611  
612 # $ok = $self->_command_expect_prompt($prompt_response)
613 # purpose: handle prompt_response processing for _command_expect method
614 # $prompt_response: set undef to return undef, text to send, or code to execute
615 # $ok: true for caller to continue processing, undef to return current output
616  
617 # read inputs
618 34 ▶ my $self = shift // die "missing self arg";
Condition50%1/2
shift() // die("missing self arg")
l!l
340
MC/DC0%0/1
shift() // die("missing self arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
619 34 my ($prompt_response, $output) = (shift, shift);
620  
621 # return undef for undef prompt response
622 34 ▶ if (not defined $prompt_response) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $prompt_response) { } 22 12 34
elsif (ref $prompt_response eq 'CODE') { } 8 4 12
623 22 $self->debug("_command_expect_prompt response = undef");
624 22 return undef;
625  
626 # handle code prompt response, returning undef of sending returned text
627 } elsif (ref $prompt_response eq "CODE") {
628 8 $self->debug("_command_expect_prompt code response executing");
629 8 my $code_response = &{$prompt_response}($self, $output);
630 8 ▶ if (not defined $code_response) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $code_response) { } 1 7 8
631 1 $self->debug("_command_expect_prompt code response = undef");
632 1 return undef;
633 } else {
634 7 $self->debug("_command_expect_prompt code response = text");
635 7 $self->expect->send($code_response);
636 }
637  
638 # handle sending text prompt response
639 } else {
640 4 $self->debug("_command_expect_prompt response = text");
641 4 $self->expect->send($prompt_response);
642 }
643  
644 # finished _command_expect_prompt, return true
645 11 return 1;
646 }
647  
648  
649  
650 3 ▶sub command_cache_clear {
Subroutine command_cache_clear: called CC=2 SCAR=7.0
Pod documented
651  
652 =head2 command_cache_clear
653  
654 $expect->command_cache_clear
655  
656 This method can be used to clear the cache used by the command method.
657  
658 Normally the command method caches the outputs for all executed commands,
659 returning cached output when the same command is executed subsequently. When
660 the cache is cleared the command method will execute the next instance of any
661 specific command instead of returning cached output.
662  
663 =cut
664  
665 # clear command cache content and increment counter
666 # cache content is used to return same command output on susequent calls
667 # cache counter is used to to save same command output to replay
668 3 ▶ my $self = shift // croak "missing self arg";
Condition50%1/2
shift() // croak("missing self arg")
l!l
30
MC/DC0%0/1
shift() // croak("missing self arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
669 3 $self->{_command_cache_content} = {};
670 3 $self->{_command_cache_counter}++;
671 3 return;
672 }
673  
674  
675  
676 0 ▶sub delay {
Subroutine delay: not called CC=3 SCAR=24.8
Pod documented
677  
678 =head2 delay
679  
680 $delay = $expect->delay($delay)
681  
682 Get and/or set a new delay time in milliseconds for the current object. This
683 delay is used when detecting extra command, prompt, or pagination output.
684  
685 A good rule of thumb may be to set this delay to at least the round trip
686 response time for a response from the connected process.
687  
688 =cut
689  
690 # read input object and new delay
691 0 ▶ my $self = shift // croak "missing self arg";
Condition0%0/2
shift() // croak("missing self arg")
l!l
00
MC/DC0%0/1
shift() // croak("missing self arg")
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
692 0 my $delay = shift;
693  
694 # set new delay, if defined
695 0 ▶ if (defined $delay) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $delay) 0 0 0
696 0 $self->debug("delay set = $delay");
697 0 $self->{delay} = $delay;
698 }
699  
700 # finished, return delay
701 0 return $self->{delay};
702 }
703  
704  
705  
706 0 ▶sub paging_re {
Subroutine paging_re: not called CC=3 SCAR=24.8
Pod documented
707  
708 =head2 paging_re
709  
710 $paging_re = $expect->paging_re($paging_re)
711  
712 Get and/or set new paging_re for the current object.
713  
714 Following are known pagination prompts covered by the default paging_re:
715  
716 junos =~ /^---\(more( \d\d?%)?\)---$/
717 cisco ASA =~ /<--- More --->/
718 cisco ios =~ /--more--/
719 cisco ios 15 =~ /--More--/
720  
721 Following are other observed pagination prompts, not covered by default:
722  
723 linux more cmd =~ /--More--\(\d\d?%\)/
724  
725 Note that matched pagination text is not appended to command output. Refer also
726 to the command method in this module for more information.
727  
728 =cut
729  
730 # read input object and new paging_re
731 0 ▶ my $self = shift // croak "missing self arg";
Condition0%0/2
shift() // croak("missing self arg")
l!l
00
MC/DC0%0/1
shift() // croak("missing self arg")
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
732 0 my $paging_re = shift;
733  
734 # set new paging_re, if defined
735 0 ▶ if (defined $paging_re) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $paging_re) 0 0 0
736 0 $self->debug("paging_re set = $paging_re");
737 0 $self->{paging_re} = $paging_re;
738 }
739  
740 # finished, return paging_re
741 0 return $self->{paging_re};
742 }
743  
744  
745  
746 50 ▶sub prompt_re {
Subroutine prompt_re: called CC=3 SCAR=11.0
Pod documented
747  
748 =head2 prompt_re
749  
750 $prompt_re = $expect->prompt_re($prompt_re)
751  
752 This method can be used to get and/or set the prompt_re regex string for an
753 existing object, which is used by the command method to detect the end of
754 output for a sent command. The prompt_re regex string should be specific
755 enough to detect the cli prompt without matching any other command outputs.
756  
757 By default the new method sets a device specific prompt_re for the rest of
758 the session from the first prompt detected after login, confirmed by sending
759 a carraige return and getting the same specifc prompt back again. This prompt
760 detection can be adjusted or disabled, refer to the new method for more info.
761  
762 Note that normally prompt_re should start with a regex caret symbol, and end
763 with a regex dollar sign, so that all characters in the command prompt line
764 are matched, and to avoid spurrious matches in command outputs. Be aware of
765 any spaces that at the end of a prompt, as in the example below:
766  
767 $expect->prompt_re('^st-city-dev> $');
768  
769 Also note that the /Q and /E escape sequences do not appear to be recognized by
770 expect, and they should not be used in prompt_re.
771  
772 =cut
773  
774 # read input object and new prompt_re
775 50 ▶ my $self = shift // croak "missing self arg";
Condition50%1/2
shift() // croak("missing self arg")
l!l
500
MC/DC0%0/1
shift() // croak("missing self arg")
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
776 50 my $prompt_re = shift;
777  
778 # set new prompt_re, if defined
779 50 ▶ if (defined $prompt_re) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $prompt_re) 18 32 50
780 18 $self->debug("prompt_re set = $prompt_re");
781 18 $self->{prompt_re} = $prompt_re;
782 }
783  
784 # finished, return prompt_re
785 50 return $self->{prompt_re};
786 }
787  
788  
789  
790 0 ▶sub timeout {
Subroutine timeout: not called CC=3 SCAR=24.8
Pod documented
791  
792 =head2 timeout
793  
794 $timeout = $expect->timeout($timeout)
795  
796 Get and/or set a new timeout for the current object, refer to the L<Expect>
797 module for more information.
798  
799 =cut
800  
801 # read input object and new timeout
802 0 ▶ my $self = shift // croak "missing self arg";
Condition0%0/2
shift() // croak("missing self arg")
l!l
00
MC/DC0%0/1
shift() // croak("missing self arg")
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
803 0 my $timeout = shift;
804  
805 # set new timeout, if defined
806 0 ▶ if (defined $timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $timeout) 0 0 0
807 0 $self->debug("timeout set = $timeout");
808 0 $self->{timeout} = $timeout;
809 }
810  
811 # finished, return timeout
812 0 return $self->{timeout};
813 }
814  
815  
816  
817 =head1 TESTING
818  
819 L<Mnet::Test> --record and --replay command line options are supported by this
820 module, and will record and replay command method outputs associated with calls
821 to the command method, integrated with the command_cache_clear method.
822  
823 Refer to the L<Mnet::Test> module for more information.
824  
825 =head1 SEE ALSO
826  
827 L<Expect>
828  
829 L<Mnet>
830  
831 L<Mnet::Expect>
832  
833 L<Mnet::Expect::Cli::Ios>
834  
835 L<Mnet::Log>
836  
837 L<Mnet::Opts::Cli>
838  
839 L<Mnet::Test>
840  
841 =cut
842  
843 # normal package return
844 39 1;
845  
« Mnet/T.pm ↑ Summary Mnet/IP.pm »