-
Notifications
You must be signed in to change notification settings - Fork 8
/
NetDBHelper.pm
1261 lines (1089 loc) · 40.9 KB
/
NetDBHelper.pm
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##############################################################################
# NetDBHelper.pm - Network Tracking Database Helper Module
# Author: Jonathan Yantis <[email protected]>
# Copyright (C) 2013 Jonathan Yantis
##############################################################################
#
# This module handles logging in to devices, cleaning up output and writing
# files in parallel.
#
# This replaces the old CiscoHelper.pm module. There is still a lot of crusty
# old code in here, but you don't have to use the login methods for your
# custom plugins if you don't want. You can safely remove CiscoHelper.pm and
# replace it with this one if you use any of those methods.
#
##############################################################################
# Versions:
#
# v1.0 - 12/01/2011 - Initial Code ported from CiscoHelper.pm
# v2.0 - 10/12/2012 - Commenting, function organization, and debuging output
# cleanup. Regex cleanup and optimization.
#
##############################################################################
# License:
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details:
# http://www.gnu.org/licenses/gpl.txt
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
package NetDBHelper;
use English qw( -no_match_vars );
use AppConfig;
use File::Flock;
use Carp;
eval "use Net::Telnet::Cisco;"; # Optional unless telnet is required
use Net::SSH::Expect;
use Net::Ping;
use Net::DNS;
use NetAddr::IP;
use IO::Select;
use IO::Socket::INET6;
use List::MoreUtils; # for any()
use strict;
use warnings;
use Exporter;
# no nonsense
no warnings 'uninitialized';
our $VERSION = 1.13;
our @ISA = qw(Exporter);
our @EXPORT = qw( cleanTrunks altHelperConfig setPrependNew writeMAC writeARP
writeINT writeND writeIPV6 processDevConfig whirley
get_cisco_ssh_auto get_cisco_session_auto writeFile
normalizePort getSessionCisco sendCiscoCommand SSHCommand
attempt_ssh ping_device getIPfromName testSSH
get_SSH_session enable_ssh getCredentials compactResults
);
our @EXPORT_OK = qw( $whirley );
# DEBUG
my $DEBUG = 0;
## Username and password option for get_cisco_session_auto
# Gets data from /etc/netdb.conf
my $username;
my $passwd;
my $username2; # Try this if the first username/password fails
my $passwd2;
my $enablepasswd; # The second passwd always tries to enable
my $default_timeout = 20;
my $ssh_timeout = 10;
my $ssh_port = 22;
my $login_timeout = undef; # Uses ssh_timeout unless defined in config_file
my $WHIRLEY_COUNT=-1;
my $session_type;
my $general_session;
my $hostprompt;
my $ssh_options;
my ( $whirley, $myprompt );
my @whirley;
$whirley='[>...] [.>..] [..>.] [...>] [...<] [..<.] [.<..] [<...]';@whirley=split /\s+/,$whirley;
# Configuration file to read from
my $config_file = "/etc/netdb.conf";
my ( $datadir, $arpFile, $macFile, $intFile, $v6File, $ndFile );
my ( $maxMacs, $configged, $prependNew, $useFQDN );
my %skip_port;
my %use_port;
my %useTrunkPorts;
my %authgroup;
my %authgroup_user;
my %authgroup_pass;
my %authgroup_enable;
#-----------------------------------------------------------------------------
# Load an alternate configuration file, control the debug variable
#-----------------------------------------------------------------------------
sub altHelperConfig {
$config_file = shift;
$DEBUG = shift;
print "|DEBUG|: Helper Loading Alternate Config File: $config_file\n" if $DEBUG>3;
checkConfig();
}
#-----------------------------------------------------------------------------
# Enable prependNew option for output files
#-----------------------------------------------------------------------------
sub setPrependNew {
$prependNew = "new";
}
#-----------------------------------------------------------------------------
# Filter out trunk ports based on maxMacs and interfaces marked as trunks
#
# Input 1: mactable reference
# Input 2: intstatus reference
#-----------------------------------------------------------------------------
sub cleanTrunks {
my $mactable_ref = shift;
my $intstatus_ref = shift;
my @mactable;
my @intstatus;
my @cleanMacTable;
if ( $mactable_ref ) {
@mactable = @$mactable_ref;
}
else {
print "Warning: Empty mac table passed to cleanTrunks\n" if $DEBUG>1;
return;
}
if ( $intstatus_ref ) {
@intstatus = @$intstatus_ref;
}
else {
print "Warning: No interface status information passed to cleanTrunks\n" if $DEBUG>1;
}
my %trunkports;
# Parse Config
checkConfig();
# Process instatus and find trunk ports
foreach my $line ( @intstatus ) {
my ( $host, $port, $state, $vlan ) = split (/\,/, $line );
if ( $vlan eq "trunk" ) {
$trunkports{"$host,$port"} = 1;
print "|DEBUG|: Trunk: Found trunk port from int status: $host $port\n" if $DEBUG>3;
}
}
## Find ports with over $maxMacs
my %portcount;
# Count the occurances of a port
foreach my $line ( @mactable ) {
my ( $host, $mac, $port ) = split( /\,/, $line );
$portcount{"$host$port"}++;
}
# $DEBUG = 6;
# Add to a new final mac table if port count is below $maxMacs and no excluded, or implicitly included
foreach my $line ( @mactable ) {
my ( $host, $mac, $port ) = split( /\,/, $line ); # split the results
if ( $portcount{"$host$port"} < $maxMacs ) { # check mac count on port before proceeding
if ( $use_port{"$host,$port"} || # Explicitly use this port
!$trunkports{"$host,$port"} || # Use port if not a trunk port
$useTrunkPorts{$host} || # Trunk processing requested for this switch
$useTrunkPorts{"DEFAULT"} ) { # Trunk processing on all switches
# Skip port overrides all, otherwise import data
if ( !$skip_port{"$host,$port"} ) {
push( @cleanMacTable, $line );
}
# Skip port debug reporting
else {
print "|DEBUG|: Trunk: Threw out port configured to skip: $host $port $mac\n" if $DEBUG>2;
}
}
# Skip trunk debug reporting
else {
print "|DEBUG|: Trunk: Threw out trunk that did not exceed max MAC count: $host $port $mac\n" if $DEBUG>3;
}
}
# Explicitly use port even if it exceeds max mac if requested
elsif ( $use_port{"$host,$port"} && !$skip_port{"$host,$port"} ) {
push( @cleanMacTable, $line );
print "|DEBUG|: Trunk: Importing data that exceeds max mac count requested: $host,$port\n" if $DEBUG>4;
}
} # END foreach
return \@cleanMacTable;
}
#-----------------------------------------------------------------------------
# Write ARP table to disk, use config file's option if filename not passed
#-----------------------------------------------------------------------------
sub writeARP {
my $results_ref = shift;
my $altFile = shift;
checkConfig();
if ( $altFile ) {
writeFile( $results_ref, $altFile );
}
else {
writeFile( $results_ref, $arpFile );
}
}
sub writeMAC {
my $results_ref = shift;
my $altFile = shift;
checkConfig();
if ( $altFile ) {
writeFile( $results_ref, $altFile );
}
else {
writeFile( $results_ref, $macFile );
}
}
sub writeINT {
my $results_ref = shift;
my $altFile = shift;
checkConfig();
if ( $altFile ) {
writeFile( $results_ref, $altFile );
}
else {
writeFile( $results_ref, $intFile );
}
}
sub writeIPV6 {
my $results_ref = shift;
my $altFile = shift;
checkConfig();
if ( $altFile ) {
writeFile( $results_ref, $altFile );
}
else {
writeFile( $results_ref, $v6File );
}
}
sub writeND {
my $results_ref = shift;
my $altFile = shift;
checkConfig();
if ( $altFile ) {
writeFile( $results_ref, $altFile );
}
else {
writeFile( $results_ref, $ndFile );
}
}
#-----------------------------------------------------------------------------
# Write results to file, use locking mechanism to avoid clobbering
#-----------------------------------------------------------------------------
sub writeFile {
my $results_ref = shift;
my $results_file = shift;
my $pid = $$;
if ( !$results_file ) {
croak "Undefined file handle to write to\n";
}
# Lock file for writing
print "PID($pid): |LOCK| $results_file\n" if $DEBUG>4;
lock( $results_file );
open( my $RESULTS, '>>', "$results_file") or die "Can't write to $results_file";
foreach my $line ( @$results_ref ) {
if ( $line ) {
print $RESULTS "$line\n";
}
}
close $RESULTS;
unlock( $results_file );
}
#-----------------------------------------------------------------------------
# Saves all data in an array of hashrefs, each hash contains a device and its
# configured options.
#-----------------------------------------------------------------------------
sub processDevConfig {
my $line = shift;
my ( $host, $fqdn, $nmac, $narp, $vrfs, $fssh, $ftelnet, $l_max_macs );
my ( $v6, $wifi, $sport, $l_devtype, $nd, $tmp );
my ( $gethost, $nobackup, $dobackup, $authgroup );
my ( $use_port );
# Process Config
checkConfig();
# Strip out spaces, line termination and comments
chomp($line);
$line =~ s/\s+//g;
( $line ) = split(/\#/, $line );
# split out the options
my @dev = split(/\,/, $line);
$fqdn = $dev[0];
# Use the FQDN for the switch name if configured
if ( $useFQDN ) {
print "|DEBUG|: processDevConfig: Using FQDN for switch names on $fqdn\n" if $DEBUG>4;
$host = $fqdn;
}
# Use hostname for switchname (default)
else {
($host) = split(/\./, $fqdn ); # Strip off domain name
}
$nmac = 1;
# Populate options for device
foreach my $devopt ( @dev ) {
$nmac = undef if ( $devopt =~ /^(netdbnomac|nomac)$/ ); # Turn off default mac capture
$wifi = 1 if ( $devopt =~ /^wifi$/ ); # Turn on wifi client capture
$narp = 1 if ( $devopt =~ /^(netdbarp|arp)$/ ); # Turn on ARP table capture
$fssh = 1 if ( $devopt eq 'forcessh' ); # Force SSH Connection
$ftelnet = 1 if ( $devopt eq 'forcetelnet' ); # Force telnet support
$v6 = 1 if ( $devopt =~ /^(netdbv6|ipv6|v6)$/ );
$nd = 1 if ( $devopt =~ /^(nd|cdp|lldp)$/ );
$gethost = 1 if ( $devopt eq 'gethost' );
$nobackup = 1 if ( $devopt eq 'nobackup' );
$dobackup = 1 if ( $devopt eq 'dobackup' );
#skip port entry from dev file
if ( $devopt =~ /skip_port/ ) {
( $tmp, $sport ) = split( /\=/, $devopt );
$skip_port{"$host,$sport"} = 1;
print "SKIPPING $host,$sport\n" if $DEBUG>2;
}
# Always use this port
if ( $devopt =~ /use_port/ ) {
( $tmp, $sport ) = split( /\=/, $devopt );
$use_port{"$host,$sport"} = 1;
print "USING $host,$sport\n" if $DEBUG>2;
}
#use trunks from this device
if ( $devopt =~ /use_trunks/ ) {
$useTrunkPorts{"$host"} = 1;
print "Using Trunks on $host\n" if $DEBUG>2;
}
# custom max macs on a port
if ( $devopt =~ /max_macs/ ) {
my @tmp = split( /\s*\=\s*/, $devopt );
$l_max_macs = $tmp[1];
}
# Check for VRFs
if ( $devopt =~ /^vrf-.+$/ ) {
$devopt =~ s/vrf-//;
$vrfs = $vrfs . "$devopt,";
}
# Check for authgroup
if ( $devopt =~ /authgroup/ ) {
my @tmp = split( /\s*\=\s*/, $devopt );
$authgroup = $tmp[1];
}
# Check device type
if ( $line =~ /devtype/ ) {
( $tmp, $l_devtype ) = split(/devtype\=/, $line );
( $l_devtype ) = split(/\,/, $l_devtype );
}
# SSH Port
if ( $line =~ /ssh_port/ ) {
( $tmp, $ssh_port ) = split(/ssh_port\=/, $line );
( $ssh_port ) = split(/\,/, $ssh_port );
}
#SSH Options
if ( $line =~ /ssh_options/ ) {
( $tmp, $ssh_options ) = split(/ssh_options\=/, $line );
( $ssh_options ) = split(/\,/, $ssh_options );
}
# SSH Timeout
if ( $line =~ /ssh_timeout/ ) {
( $tmp, $ssh_timeout ) = split(/ssh_timeout\=/, $line );
( $ssh_timeout ) = split(/\,/, $ssh_timeout );
}
# Login Timeout
if ( $line =~ /login_timeout/ ) {
( $tmp, $login_timeout ) = split(/login_timeout\=/, $line );
( $login_timeout ) = split(/\,/, $login_timeout );
}
} # END for
# Populate hashref entry for device
if ( $host && ( $nmac || $narp || $v6 || $vrfs || $dobackup ) ) {
my $dref = { host => $host, fqdn => $fqdn, mac => $nmac, arp => $narp,
vrfs => $vrfs, forcessh => $fssh, forcetelnet => $ftelnet,
maxmacs => $l_max_macs, v6nt => $v6, nd => $nd,
devtype => $l_devtype, gethost => $gethost,
nobackup => $nobackup, dobackup => $dobackup,
authgroup => $authgroup, wifi => $wifi,
ssh_timeout => $ssh_timeout, ssh_port => $ssh_port,
ssh_options => $ssh_options, login_timeout => $login_timeout };
print "|DEBUG|: Device: $host, fqdn: $fqdn, mac: $nmac, wifi: $wifi, arp: $narp, vrfs: $vrfs, ipv6: $v6, devtype: $l_devtype, authgroup: $authgroup, ssh_port: $ssh_port, ssh_options: $ssh_options, ssh_timeout: $ssh_timeout, login_timeout: $login_timeout\n" if $DEBUG>2;
return $dref;
}
}
#-----------------------------------------------------------------------------
# Get the username, password and enable from config file based on $dref
# Uses authgroup credentials if they exist, otherwise uses default
#-----------------------------------------------------------------------------
sub getCredentials {
my $dref = shift;
my ( $user, $pass, $enable, $group );
parseConfig();
$group = $authgroup{$$dref{host}} if $authgroup{$$dref{host}}; # From config file
$group = $$dref{authgroup} if $$dref{authgroup}; # From devicelist
# Check for specified authgroup
if ( $group ) {
print "|DEBUG|: $$dref{host} in authgroup $group\n" if $DEBUG>2;
if ( $authgroup_user{$group} ) {
$user = $authgroup_user{$group};
}
else {
$user = $username;
}
if ( $authgroup_pass{$group} ) {
$pass = $authgroup_pass{$group};
}
else {
$pass = $passwd;
}
if ( $authgroup_enable{$group} ) {
$enable = $authgroup_enable{$group};
}
else {
$enable = $enablepasswd;
}
return ( $user, $pass, $enable );
}
# Return default credentials if no authgroup
else {
return ( $username, $passwd, $enablepasswd );
}
} # END sub getCredentials
#-----------------------------------------------------------------------------
# DNS Lookup, returns IPv6 or IPv4 address if if exists,
# croaks if no DNS entry.
# Input:
# Fully qualified domain name: the fqdn to lookup.
# Output:
# Host IP: the IP address (v6 or v4) of the fqdn
#-----------------------------------------------------------------------------
sub getIPfromName {
my $fqdn = shift;
my $hostip;
my $res = Net::DNS::Resolver->new;
my $searchv6 = $res->search( $fqdn, 'AAAA' );
my $searchv4 = $res->search( $fqdn );
# Check for IPv6 first
if ( $searchv6 ) {
my @rrv6 = $searchv6->answer;
# Check for CNAME, get AAAA record and do lookup on that instead
if ( $rrv6[0]->type eq 'CNAME' ) {
$searchv6 = $res->search( $rrv6[0]->cname );
@rrv6 = $searchv6->answer;
}
# AAAA Lookup
if ( $rrv6[0]->type eq 'AAAA' ) {
$hostip = $rrv6[0]->address;
return $hostip;
}
}
# IPv4
if ( $searchv4 ) {
my @rrv4 = $searchv4->answer;
# Search for CNAME, do lookup on that result if exists
if ( $rrv4[0]->type eq 'CNAME' ) {
$searchv4 = $res->search( $rrv4[0]->cname );
@rrv4 = $searchv4->answer;
}
if ( $rrv4[0]->type eq 'A' ) {
$hostip = $rrv4[0]->address;
return $hostip;
}
}
else {
# Try hostfile lookup
my $aton = inet_aton($fqdn);
if ( $aton ) {
$hostip = inet_ntoa($aton);
}
# Lookup failed
if ( !$hostip ) {
croak( "|ERROR|: DNS lookup failure on $fqdn\n" );
}
return $hostip;
}
} # END sub getIPfromName
#-----------------------------------------------------------------------------
# Converts the port full port descriptions to the standard
# short form.
# Input:
# port: full port description
# Output:
# port: standardized short port description
#-----------------------------------------------------------------------------
sub normalizePort {
my $port = shift;
chomp($port);
$port =~ s/TenGigabitEthernet(\d+\/\d+\/?\d*)$/Te$1/;
$port =~ s/10GigabitEthernet(\d+\/\d+\/?\d*)$/$1/;
$port =~ s/^GigabitEthernet(\d+\/\d+\/?\d*)$/Gi$1/;
$port =~ s/^FastEthernet(\d+\/\d+)$/Fa$1/;
$port =~ s/^Ethernet(\d+\/\d+\/?\d*)$/Eth$1/;
$port =~ s/^ethernet(\d+\/?\d*\/?\d*)$/$1/;
$port =~ s/^Port-channel(\d+)$/Po$1/;
return $port;
} # END sub normalizePort
#---------------------------------------------------------------------------------------------
# Compacts results, ie removes stray line endings
# Input:
# results refrence - refrence to raw cmd results
# Output:
# results - refrence to array containg cleaner parseable output
#---------------------------------------------------------------------------------------------
sub compactResults {
my $results_ref = shift;
my @cmdresults = @$results_ref;
my @splitresults;
my @results;
#@results = split( /\n/, $cmdresults[0] );
# Fix line ending issues
foreach my $result ( @cmdresults ) { # parse results
@splitresults = split( /\n/, $result ); # fix line endings
foreach my $line ( @splitresults ) {
$line =~ s/[\n|\r]//g; # Strip stray \r command returns
if ($line){
push( @results, $line ); # save to a single array
}
} # END foreach of split results
@splitresults = undef;
} # END foreach of cmd results
return \@results;
} # END sub compactResults
############################
# #
# SSH connection functions #
# #
############################
#-----------------------------------------------------------------------------
# Test to see if there is an open port listening for SSH on port 22
# Input: ($hostip, #$fqdn)
# IP address: of the host to check
# #Fully Qualified Domain Namem: the fqdn of the device to check
# Output:
# Boolean: true if a port is open, false if the port is closed
#-----------------------------------------------------------------------------
sub testSSH {
my $hostip = shift;
#my $fqdn = shift;
## Test to see if SSH port is open
print "|DEBUG|: Testing port $ssh_port on $hostip for open state\n" if $DEBUG>2;
# Create a Socket Connection
my $remote = IO::Socket::INET6 -> new (
Proto => 'tcp',
Timeout => 4,
PeerAddr => $hostip,
PeerPort => $ssh_port );
# Return true if port is open
if ($remote) {
close $remote;
print "$hostip SSH port open\n" if $DEBUG>2;
return 1;
}
print "$hostip SSH port closed\n" if $DEBUG>2;
return undef;
} # END sub testSSH
#---------------------------------------------------------------------------------------------
# Attempt SSH Session if port is open, return 0 if failure and print to stderr
# Input:
# hostname: DNS resolveable hostname of device to establish an SSH session with.
# disbable_paging: the command to be executed on the device to disable paging if none is
# needed use 'none'.
# Output:
# Session: a SSH session handle.
#---------------------------------------------------------------------------------------------
sub get_SSH_session {
my $hostname = shift;
my $disable_paging = shift;
my $dref = shift;
my $session;
parseConfig();
my ( $user, $pass, $enable ) = getCredentials( $dref );
$login_timeout = $$dref{login_timeout} if $$dref{login_timeout};
#print "\n\n****DREF TIMEOUT****: $$dref{login_timeout}\n\n";
$ssh_port = $$dref{ssh_port} if $$dref{ssh_port};
$ssh_options = $$dref{ssh_options} if $$dref{ssh_options};
if ( !$hostname ){ # verify a hostname is given
croak("Minimum set of arguments undefined in get_SSH_session\n");
return undef;
}
if ( !$disable_paging ){ # check for disable paging command
print "|SSH|: No disable paging command specified for $hostname, using default\n" if $DEBUG>1;
$disable_paging = "terminal length 0";
}
elsif ( $disable_paging =~ /none/i){ # no paging on this device
$disable_paging = undef;
}
# Creating hostprompt for later
( $hostprompt ) = split( /\./, $hostname );
$hostprompt = '((SSH|'."$user".')@)?' . "$hostprompt" . '(.config)?(\-if)?(.)?(>|#)' if $hostprompt;
print "|DEBUG|: Host Prompt to wait for: $hostprompt\n" if $DEBUG>5;
$EVAL_ERROR = undef;
eval {
# Get a new session object
print "|SSH|: Logging in to $hostname (timeout: $login_timeout)\n" if $DEBUG>2;
$session = Net::SSH::Expect->new(
host => $hostname,
port => $ssh_port,
password => $pass,
user => $user,
raw_pty => 1,
timeout => $login_timeout,
ssh_option => $ssh_options
);
$session->login();
my @output;
if ( $disable_paging ){
print "|DEBUG|: Logged in to $hostname, setting $disable_paging\n" if $DEBUG>3;
@output = SSHCommand( $session, $disable_paging );
print "|DEBUG|: Login: @output\n" if $DEBUG>4;
}
if ( $output[0] =~ /Password/ ) {
die "Failed to login to $hostname with primary credentials\n";
}
}; # END eval
# If primary login fails, check for backup credentials and try those
if ($EVAL_ERROR || !$session) {
print "|SSH|: Primary Login Failed to $hostname: $EVAL_ERROR\n" if $DEBUG;
if(defined $username2 and defined $passwd2) {
print "|SSH|: Attempting Secondary Login Credentials to $hostname\n" if $DEBUG;
my @output;
$EVAL_ERROR = undef;
eval {
# Get a new session object
print "|SSH|: Secondary login in to $hostname(timeout: $ssh_timeout)\n" if $DEBUG>3;
$session = Net::SSH::Expect->new(
host => $hostname,
password => $passwd2,
port => $ssh_port,
user => $username2,
raw_pty => 1,
timeout => $login_timeout,
ssh_option => $ssh_options
);
$session->login();
if ( $disable_paging ){
print "|DEBUG|: Logged in to $hostname, setting $disable_paging\n" if $DEBUG>3;
@output = SSHCommand( $session, $disable_paging );
print "|DEBUG|: Login: @output\n" if $DEBUG>4;
}
}; # END eval
if ($EVAL_ERROR || !$session || $output[0] =~ /Password/ ) {
croak( "\nAuthentication Error: Primary and Secondary login failed to $hostname: $EVAL_ERROR\n" );
return undef;
}
}
else {
croak( "\nAuthentication Error: Primary login failed and no secondary login credentials provided\n" );
return undef;
}
} # END if eval
return $session;
} # END sub get_SSH_session
#-----------------------------------------------------------------------------
# Attempts to get enable privileges, brute force,
# if it asks for a password, send it
#-----------------------------------------------------------------------------
sub enable_ssh {
my ($session_obj, $enablepasswd) = @_;
# Try to enable
$session_obj->send('enable');
my @output = $session_obj->waitfor( 'assword|\#' );
# Look for password prompt
if ( $output[0] ) {
SSHCommand( $session_obj, "$enablepasswd" );
}
else {
print "|SSH| Debug: Did not receive password prompt when enabling" if $DEBUG>3;
}
} # END sub enable_ssh
#-----------------------------------------------------------------------------
# Send an SSH command and return results as @output
# Looks for prompt to speed things up
#-----------------------------------------------------------------------------
sub SSHCommand {
my $session = shift;
my $command = shift;
my $timeout = shift;
my $prompt = shift;
# Custom Timeout
if ( !$timeout ) {
$timeout = $ssh_timeout;
#print "****Command Timeout****: $ssh_timeout\n";
}
# Local $prompt overrides all
if ( !$prompt ) {
if ( !$hostprompt ) {
$prompt = "UNKNOWNXYZ";
}
else {
$prompt = $hostprompt;
}
}
print "SSHCommand (command:$command) (timeout:$timeout) (hostprompt:$prompt)\n" if $DEBUG>4;
my @output;
checkConfig();
$session->read_all( 1 ); # Clear any existing input data
$session->send( "$command" ); # Send command
$session->waitfor( "$prompt", $timeout ); #wait for prompt or timeout
@output = $session->before(); #data found before prompt
return @output;
} # END sub SSHCommand
###############################
# Device Session Code (nasty) #
###############################
#-----------------------------------------------------------------------------
# SSH Auto login using credentials
#-----------------------------------------------------------------------------
sub get_cisco_ssh_auto {
my $fqdn = shift;
my $dref = shift;
parseConfig();
my ( $user, $pass, $enable ) = getCredentials( $dref );
return get_cisco_ssh(
{
Host => $fqdn,
User1 => $user,
Pass1 => $pass,
EnablePass1 => $enable,
User2 => $username2,
Pass2 => $passwd2,
EnablePass2 => $enable,
}
);
}
#-----------------------------------------------------------------------------
# Get an SSH Session using Net::SSH::Expect
#-----------------------------------------------------------------------------
sub get_cisco_ssh {
my $session_obj;
my ($arg_ref) = @_;
&parseConfig();
# Hostname of target cisco device
my $hostname = $arg_ref->{Host};
# Primary username and password required
my $user1 = $arg_ref->{User1};
my $pass1 = $arg_ref->{Pass1};
if ( !$hostname ) {
croak("Minimum set of arguments undefined in cisco_get_ssh\n");
}
# Optional username and password if first fails
my $user2 = $arg_ref->{User2};
my $pass2 = $arg_ref->{Pass2};
# Enable passwords if required
my $enable_pass1 = $arg_ref->{EnablePass1};
my $enable_pass2 = $arg_ref->{EnablePass2};
# Attempt primary login
$EVAL_ERROR = undef;
eval {
$session_obj =
attempt_ssh( $hostname, $user1, $pass1 );
};
# If primary login fails, check for backup credentials and try those
if ($EVAL_ERROR) {
if(defined $user2 and defined $pass2) {
print "SSH: Primary Login Failed, Attempting Secondary Login Credentials to $hostname: $EVAL_ERROR\n" if $DEBUG;
$session_obj =
attempt_ssh( $hostname, $user2, $pass2 );
}
else {
croak( "\nAuthentication Error: Primary login failed and no secondary login credentials provided\n" );
}
}
# Attempt to enter enable mode if password defined
if ( $enablepasswd ) {
enable_ssh( $session_obj, $enablepasswd );
}
print "Successfully Logged in, returning login object\n" if $DEBUG>4;
return $session_obj;
}
sub attempt_ssh {
my ( $hostname, $cisco_user, $cisco_passwd ) = @_;
my $session_obj;
# Creating hostprompt for later
( $hostprompt ) = split( /\./, $hostname );
$hostprompt = "$hostprompt" . '(.config)*(\-if)*(.)*(>|#)' if $hostprompt;
print "Host Prompt to wait for: $hostprompt\n" if $DEBUG>4;
# Get a new cisco session object
print "SSH: Logging in to $hostname (timeout: $ssh_timeout)\n" if $DEBUG>3;
$session_obj = Net::SSH::Expect->new(
host => $hostname,
password => $cisco_passwd,
user => $cisco_user,
raw_pty => 1,
timeout => $ssh_timeout,
);
# Login
$session_obj->login();
print "Logged in to $hostname, setting terminal length 0\n" if $DEBUG>3;
my @output = SSHCommand( $session_obj, "terminal length 0" );
# Catch Errors
foreach my $output ( @output ) {
# ASA Term Length Error Detection
if ( $output =~ /Invalid/ ) {
print "Caught bad ASA Parser trying to set term length\n" if $DEBUG>3;
$session_obj->exec( "terminal pager 0" );
}
# Login failure
elsif ( $output =~ /Permission/i ) {
die "Permission Denied";
}
elsif ( $output =~ /Password/i ) {
die "Bad Login";
}
else {
print "SSH login output: $output\n" if $DEBUG>3;
}
}
return $session_obj;
}
#-----------------------------------------------------------------------------
# Use the local username and password from library to login
#-----------------------------------------------------------------------------
sub get_cisco_session_auto {
my $fqdn = shift;
my $dref = shift;
parseConfig();
my ( $user, $pass, $enable ) = getCredentials( $dref );
return get_cisco_session(
{
Host => $fqdn,
User1 => $user,
Pass1 => $pass,
EnablePass1 => $enable,
User2 => $username2,
Pass2 => $passwd2,
EnablePass2 => $enablepasswd,
}
);
}
#############################################################################
# Logs in to device(Host) using primary credentials (User1 and Pass1) and
# returns a session object. Optional values are Timeout and User2 and Pass2.
# You can also pass in EnablePass1 and EnablePass2 if the session needs to
# be enabled. While this is a seemingly needless layer on Telnet::Cisco,
# it saves a lot of code rewrite and login logic for a lot of scripts.
#############################################################################
sub get_cisco_session {
my $session_obj;
my ($arg_ref) = @_;
&parseConfig();
# Hostname of target cisco device
my $hostname = $arg_ref->{Host};
# Primary username and password required
my $user1 = $arg_ref->{User1};
my $pass1 = $arg_ref->{Pass1};
if (!$user1 || !$pass1 || !$hostname ) {
croak("Minimum set of arguments undefined in cisco_get_session\n");
}
# Optional username and password if first fails
my $user2 = $arg_ref->{User2};
my $pass2 = $arg_ref->{Pass2};
# Enable passwords if required
my $enable_pass1 = $arg_ref->{EnablePass1};
my $enable_pass2 = $arg_ref->{EnablePass2};
# Set the timeout for commands
my $cisco_timeout = $arg_ref->{Timeout};
if (!defined $cisco_timeout) {
$cisco_timeout = $default_timeout;
}
# Attempt primary login
$EVAL_ERROR = undef;
eval {
$session_obj =
attempt_session( $hostname, $user1, $pass1, $cisco_timeout );
# Enable if defined
if ($enable_pass1) {
enable_session($session_obj, $enable_pass1);
}
};
# If primary login fails, check for backup credentials if login fails
if ($EVAL_ERROR =~ "login" ) {
# Secondary User Credentials
if(defined $user2 and defined $pass2) {
$EVAL_ERROR = undef;
eval {
$session_obj =
attempt_session( $hostname, $user2, $pass2, $cisco_timeout );