blib/lib/Net/Appliance/Session/Scripting.pm untested

filter: Statementstmt 0.0% 0 / 215 Branchbran 0.0% 0 / 132 Conditioncond 0.0% 0 / 57 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 432 SCAR 84.2
CC
67
Cov
0%
do_session
1056.0
get_creds_from_cloginrc
210.0
commandline
182.0
CRAP 4556.0
1 package Net::Appliance::Session::Scripting;
2 { $Net::Appliance::Session::Scripting::VERSION = '4.300003' }
3  
4 use strict;
5 use warnings FATAL => 'all';
6  
7 use Getopt::Long 2.24 qw(:config bundling);
8 use Term::ANSIColor qw(colored);
9 use Text::ParseWords qw(shellwords);
10 use Term::ReadPassword qw(read_password);
11 $Term::ReadPassword::USE_STARS = 1;
12 use IO::Prompt::Tiny qw(prompt);
13 use IO::Handle ();
14 use Cwd qw(abs_path);
15 use Data::Dumper ();
16 use Try::Tiny;
17 use Text::Glob qw(match_glob);
18  
19 use Net::Appliance::Session;
20  
21 my $banner = colored ['blue'],
22 sprintf "Net Appliance Session scripting - v%s - © 2012-2017 by Oliver Gorwits\n", $Net::Appliance::Session::Scripting::VERSION;
23  
24 my %options = (cloginrc_opts => {});
25 my $exit_status = 0;
26  
27 sub bailout {
28 if (scalar @_) {
29 print "\n", colored(['magenta bold'], @_) if scalar @_;
30 }
31 else {
32 print $banner;
33 }
34 print <<ENDUSAGE;
35  
36 nas [options] [hostname or IP]
37  
38 -p, --personality Device <personality> (default: "ios")
39 -t, --transport <transport> method (Serial, Telnet, default: SSH)
40 -u, --username <username> to connect as on device (default: \$USER)
41
42 -R, --record Record session
43 -P, --playback Play back session
44 -s, --script When recording, save playback script to this <filename>
45 -l, --cmdlog NAS <file> to record commands to, or play them back from
46
47 -e, --exit-last Num. of output lines from last command is program exit status
48 -c, --cloginrc RANCID cloginrc <file> with device credentials
49 -z, --nopassword Do not ask for device password (if not using cloginrc)
50 -o, --echo Echo commands sent, when playing back the recorded script/cmdlog
51 -M, --paging Do not attempt to disable command output paging
52 -B, --nobanner Suppress display of any login banner received from the device
53
54 -q, --quiet Hide informational messages
55 -v, --verbose NCI log <level> ("debug", "notice", "info", etc)
56 -V, --version Display this program's version number
57 -h, --help Display this help text
58  
59 Notes:
60 * If hostname or IP is not specified, the script loops, waiting for hostnames
61 to be entered passed on standard input, each one starting a new session.
62 * When you disconnect from an interactive session there may be an input/output
63 read error. You should run "!s close" to request a graceful disconnection.
64  
65 ENDUSAGE
66  
67 exit(0);
68 }
69  
70 sub getopt {
71 my @getoptconf = (qw/
72 personality|p=s
73 transport|t=s
74 username|u=s
75  
76 record|R
77 playback|P
78 script|s=s
79 cmdlog|l=s
80  
81 exit-last|e
82 cloginrc|c=s
83 nopassword|z
84 echo|o
85 paging|M
86 nobanner|B
87  
88 quiet|q
89 verbose|v=s
90 help|h
91 version|V
92 /);
93  
94 unshift @ARGV, shellwords($ENV{PERL_NAS_OPT});
95 %options = (map {$_ => $main::defaults->{$_}} keys %$main::defaults);
96 GetOptions(\%options, @getoptconf) || bailout();
97 $options{hostname} = $ARGV[0] if scalar @ARGV;
98 }
99  
100 sub commandline {
101 bailout() if exists $options{help};
102  
103 if (exists $options{version}) {
104 printf "nas version %s\n", $Net::Appliance::Session::Scripting::VERSION;
105 exit(0);
106 }
107  
108 if (exists $options{verbose}) {
109 $ENV{NCI_LOG_AT} = $options{verbose};
110 }
111  
112 # checks for incompatible/nonsense command option combinations
113 bailout("error: Cannot Record (-R) and Playback (-P) at the same time.\n")
114 if $options{record} and $options{playback};
115  
116 bailout("error: Record needs either command log file (-l) or script name (-s).\n")
117 if $options{record} and not ($options{script} or $options{cmdlog});
118  
119 bailout("error: Makes no sense to have both command log file (-l) and script (-s).\n")
120 if $options{cmdlog} and $options{script};
121  
122 bailout("error: Please specify hostname or IP on command line if recording.\n")
123 if $options{record} and not $options{hostname};
124  
125 # hello there, user
126 print $banner if not exists $options{quiet};
127  
128 # login credentials
129 if (not exists $options{cloginrc}) {
130 if (not exists $options{username}) {
131 $options{username} = prompt('Username:', $ENV{USER});
132 }
133 if (not exists $options{nopassword}) {
134 $options{password} = read_password(colored ['white'], 'Password (optional): ');
135 bailout("error: No login password and no cloginrc (-c) file (need -z ?).\n")
136 if not length $options{password};
137 }
138 }
139 }
140  
141 sub get_creds_from_cloginrc {
142 return unless $options{cloginrc} and -e $options{cloginrc};
143 open my $cloginrc, '<', $options{cloginrc} or bailout("$!\n");
144  
145 my %t_map = (telnet => 'Telnet', 'ssh' => 'SSH');
146 my @find = qw(autoenable method timeout user password);
147 my %found = (map {$_ => 0} @find);
148  
149 while (<$cloginrc>) {
150 my $line = $_;
151 next unless defined $line and length $line and $line =~ m/^add /;
152  
153 foreach my $f (@find) {
154 next unless $line =~ m/^add\s+$f\s+(\S+)\s+(\S+)(?:\s+(\S+))?/;
155 my ($host, $value, $value2) = ($1, $2, $3);
156  
157 next unless match_glob($host, $options{hostname});
158 next if $found{$f}++;
159  
160 if ($f eq 'autoenable') {
161 $options{cloginrc_opts}{do_privileged_mode} = not $value;
162 }
163 elsif ($f eq 'method') {
164 $options{cloginrc_opts}{transport} = $t_map{$value}
165 if not exists $options{transport};
166 }
167 elsif ($f eq 'timeout') {
168 $options{cloginrc_opts}{timeout} = $value;
169 }
170 elsif ($f eq 'user') {
171 $options{cloginrc_opts}{username} = $value
172 if not exists $options{username};
173 }
174 elsif ($f eq 'password') {
175 $options{cloginrc_opts}{password} = $value;
176 $options{cloginrc_opts}{privileged_password} = $value2
177 if defined $value2 and length $value2;
178 }
179 }
180 }
181 }
182  
183 sub run {
184 getopt();
185 commandline();
186  
187 if (not exists $options{hostname}) {
188 if (not exists $options{quiet}) {
189 print colored ['green'],
190 qq{Now looping, waiting for hostnames on standard input...\n};
191 }
192  
193 while (<>) {
194 $options{hostname} = $_;
195 chomp $options{hostname};
196 next if not length $options{hostname};
197 get_creds_from_cloginrc();
198 do_session(%options);
199 }
200 }
201 else {
202 get_creds_from_cloginrc();
203 do_session(%options);
204 }
205  
206 exit($exit_status);
207 }
208  
209 sub do_session {
210 my (%options) = @_;
211  
212 # scripting sources
213 my $script_read = IO::Handle->new();
214 my $command_log = IO::Handle->new();
215  
216 if ($options{cmdlog}) {
217 if ($options{playback}) {
218 open $script_read, '<', $options{cmdlog};
219 if (not $options{quiet}) {
220 print colored ['green'], "Playing back command log...\n";
221 }
222 }
223 elsif ($options{record}) {
224 open $command_log, '>', $options{cmdlog};
225 if (not $options{quiet}) {
226 print colored ['green blink'], "Recording command log!\n";
227 }
228 }
229 }
230  
231 if ($options{record} and $options{script}) {
232 open $command_log, '>', $options{script};
233 open my $source, '<', abs_path($0);
234 while (<$source>) { print $command_log $_ unless $_ =~ m/__END__/ }
235 close $source;
236  
237 my %settings = (%options, playback => 1);
238 delete $settings{$_}
239 for qw/record script cmdlog password nopassword cloginrc_opts/;
240 print $command_log "BEGIN {\n our ";
241 print $command_log Data::Dumper->Dump([\%settings], ['defaults']);
242 print $command_log "}\n\n";
243 print $command_log "__DATA__\n";
244  
245 print colored ['green blink'], "Recording session!\n"
246 if not $options{quiet};
247 }
248  
249 # informational messages if not in quiet mode
250 if (not exists $options{quiet}) {
251 my @messages = ();
252 if (not exists $options{personality}) {
253 push @messages, qq{personality "/cisco/ios"};
254 }
255 if (not exists $options{transport}
256 and not exists $options{cloginrc_opts}{transport}) {
257 push @messages, 'transport SSH';
258 }
259 if (scalar @messages) {
260 print colored ['green'], 'Assuming '. (join ' and ', @messages), ".\n";
261 }
262 }
263  
264 print colored ['white'], "Connecting to [$options{hostname}]...\n\n"
265 if not $options{quiet};
266  
267 my $transport = ($options{transport}
268 || $options{cloginrc_opts}{transport}
269 || 'SSH');
270  
271 my $s = Net::Appliance::Session->new({
272 host => $options{hostname},
273 transport => $transport,
274 personality => ($options{personality} || 'ios'),
275 ($options{username} ? (username => $options{username}) : ()),
276 ($options{password} ? (password => $options{password}) : ()),
277 (($options{quiet} and ($transport eq 'SSH')) ? (
278 connect_options => { opts => ['-q'] },
279 ) : ()),
280 %{ $options{cloginrc_opts} || {} },
281 });
282  
283 if ($options{paging}
284 or not ($s->nci->phrasebook->has_macro('enable_paging')
285 or $s->nci->phrasebook->has_macro('paging'))) {
286 $s->do_paging(0);
287 }
288  
289 try {
290 $s->connect();
291 print $s->last_response if not $options{nobanner};
292  
293 while (1) {
294 my $cmd = get_next_cmd($s, $script_read);
295 last if not defined $cmd;
296 next if $cmd =~ m/^\s+$/;
297 if ($command_log->opened) {
298 print $command_log "$cmd\n";
299 $command_log->flush;
300 }
301  
302 if ($cmd =~ m/^!m\s+(\S+)(?:\s+(.+))?/) {
303 my ($name, $args) = ($1, $2);
304 $args = '' if not defined $args;
305 print colored ['white bold'], "Running macro [$name]...\n"
306 if not $options{quiet};
307 $s->macro($name, { params => [split /\s+/, $args] });
308 next;
309 }
310 elsif ($cmd =~ m/^!m/) {
311 print colored ['white bold'], "Macro Names:\n";
312 foreach my $m ($s->nci->phrasebook->macro_names) {
313 print colored ['white bold'], " $m\n";
314 }
315 next;
316 }
317 elsif ($cmd =~ m/^!s\s+(\S+)/) {
318 my $call = $1;
319 if (not $s->can($call)) {
320 print colored ['red bold'], "NAS cannot do [$call]\n";
321 }
322 else {
323 print colored ['white bold'], "Running session call [$call]...\n"
324 if not $options{quiet};
325 $s->$call;
326 last if not $s->logged_in;
327 }
328 next;
329 }
330 elsif ($cmd =~ m/^\\!m/) {
331 $cmd =~ s/^\\//;
332 }
333  
334 my @last_response = $s->cmd($cmd);
335 $exit_status = scalar @last_response if $options{'exit-last'};
336 print join '', @last_response;
337 }
338 }
339 catch {
340 print colored ['white bold'], $_;
341 }
342 finally {
343 $s->close;
344 };
345 }
346  
347 sub get_next_cmd {
348 my ($s, $script_read) = @_;
349 my $turtle = colored ['red'], '>> ';
350  
351 if ($options{playback}) {
352 no warnings 'once';
353 my $cmd = ($options{cmdlog} ? <$script_read> : <main::DATA>);
354 return if not defined $cmd;
355 chomp $cmd;
356 print $turtle, $s->nci->last_prompt, $cmd, "\n"
357 if not $options{echo};
358 return $cmd;
359 }
360 else {
361 prompt($turtle . $s->last_prompt);
362 }
363 }
364  
365 1;