Subversion Repositories sysadmin_scripts

Rev

Rev 139 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
133 rodolico 1
#! /usr/bin/env perl
2
 
3
# Script does an snmp walk through the ports of one or more network
4
# switch, gathering MAC addresses assigned to each port.
5
# 
6
# It then does an snmp walk through the arp table of one or
7
# more routers to determine IP and DNS entries for the MAC address
8
# 
9
# Information gathered is stored in persistent storage (a yaml formatted file
10
# in the same directory), then reloaded at the next start of the program.
11
# As new entries become available, they are added. A time stamp
12
# records the last time an entry was "seen"
13
#
14
# requires snmp running on this machine. Also uses YAML::Tiny perl module
15
# under debian and derivatives, use the following command to install
16
# apt-get -y install snmp libyaml-tiny-perl
17
#
18
#
19
# Data is stored in the hash %switchports with the following structure
20
# %switchports =
21
#     {switch} (from $config{'switches'} key)
22
#        {name} (scalar, from snmp)
23
#        {location} (scalar, from snmp)
24
#        {'ports'} (constant key for sub hash)
25
#           {port number} (from snmp)
26
#              {connection} (uniqe id from snmp, basically the MAC)
27
#                 {mac} (from snmp walk of switch)
28
#                 {ip}  (from snmp walk of router)
29
#                 {hostname} (from reverse dns query)
30
#                 {lastseen} (last time this was active as unix timestamp)
31
#
32
# Uses two external files, both in the same directory as the script
33
# mapSwitches.config.yaml - Configuration file. See makeConfig.pl.sample for documentation. This can be created if  you, like
34
#                           me, are more comfortable with perl syntax. Once edited, run it to create the .yaml config file
35
# mapSwitches.yaml -        a state file which maintains information across executions. This allows us to track connections
36
#                           which are not on all the time. Can be deleted at any time for a fresh start. Can be dumped into a
37
#                           tab delimited text file (to STDOUT) with helper script mapSwitchesCSV.pl
38
#
39
 
40
# 20190407 RWR
41
# converted to use external config file in YAML format
42
# added the ability to ignore ports on the switches
43
# 20190514 RWR
44
# Added port aliases
45
# 20190526 RWR
46
# fixed mapSwitchCSV.pl to output in various delimited format (see README)
47
# 20200107 RWR v1.3
48
# Fixed problem where alias MIB was not returning values
49
# 20200228 RWR v1.4
50
# added description MIB and field
51
# 20200229 RWR v2.0.0
52
# rewrite, with 80% of the code changed. Found serious flaws with the way the ports were being read and fixed them.
53
# also set it up so it is a little more concise by combining redundant code into one routine, parseSNMPQuery, which
54
# reads an snmp walk and returns the results as a hash
55
# 20200301 RWR v2.1.0
56
# added some error checking in snmpwalk when a value is not returned, and also when the MAC address of the switch in
57
# question show up as bridge 0, which has no port (or, actually, all ports). Also, fixed the ignoreports
58
# 20200302 RWR v2.2.0
59
# Added the ability to override or supplement arp and dns searches for mac addresses
60
# 20230323 RWR v2.3.0
61
# Added ability to have one or more non_router files, with mac/name/ip in it in case arp lookup failed
62
# added script to create static html file in addition to csv
63
#
136 rodolico 64
# 20230324 RWR v3.0.0
133 rodolico 65
# rewrite to make things more efficient, and store data in different format. You MUST remove old yaml file
66
# before running this.
136 rodolico 67
#
68
# 20230325 RWR v3.0.1
69
# Added ability to delete entries which haven't been seen since $config->{'ttl'} seconds. ttl can be
70
# an integer followed by a unit, with units being single char h,d,w,m,y (hours, days, weeks, months, years)
71
# added ability to set so it will only refresh dns and device names every $refresh seconds, decreasing
72
# run time to 33% value when not used. Test system decreases from 15s to 5-7s
73
# reorganized so system runs smoother (test system decreased from 40 seconds to 15)
138 rodolico 74
#
75
# 20230326 RWR v3.0.2
76
# set it up so if net::dns not loadable, will revert to ionet
157 rodolico 77
# 20240810 RWR v3.4.0
78
# Added code in getDNSNames to use dig if it is available and all other ways have failed to find a hostname
133 rodolico 79
 
157 rodolico 80
 
136 rodolico 81
# for Debian, to get the required libraries
82
# apt install libyaml-tiny-perl libnet-dns-perl snmp
83
 
133 rodolico 84
use strict;
85
use warnings;
86
use Data::Dumper; # only used for debugging
87
use Socket; # for reverse dns entries
88
use YAML::Tiny; # apt-get libyaml-tiny-perl under debian
89
use File::Spec; # find location of script so we can put storage in same directory
90
use File::Basename;
91
 
92
my $DEBUG = 0;
93
 
94
# define the version number
95
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
96
use version;
157 rodolico 97
our $VERSION = version->declare("v3.4.0");
133 rodolico 98
 
99
# see https://perldoc.perl.org/Getopt/Long.html
100
use Getopt::Long;
101
# allow -vvn (ie, --verbose --verbose --dryrun)
102
Getopt::Long::Configure ("bundling");
103
 
104
 
105
 
106
my %config; # we read the configuration file into this
107
 
108
# where the script is located
109
my $scriptDir = dirname( File::Spec->rel2abs( __FILE__ ) );
110
# put the statefile in there
111
my $STATEFILE = $scriptDir . '/mapSwitches.yaml';
112
my $CONFIGFILE = $scriptDir . '/mapSwitches.config.yaml';
113
 
136 rodolico 114
 
115
 
133 rodolico 116
my $SWITCHPORTMIB  = 'iso.3.6.1.2.1.2.2.1.8'; # returns port number and state, with a state of '1' meaning operational
117
my $SWITCHMACMIB   = 'iso.3.6.1.2.1.17.4.3.1.1'; # dot1dTpFdbAddress, aka mac addresses
118
my $SWITCHIFALIASMIB = 'iso.3.6.1.2.1.31.1.1.1.18'; # ifAlias, the the 'alias' field
119
my $SWITCHIFDESCMIB = 'iso.3.6.1.2.1.2.2.1.2'; # ifDescr, the "description" field
120
my $BRIDGEPORTSMIB = 'iso.3.6.1.2.1.17.4.3.1.2';
121
my $BRIDGE2PORTMIB = 'iso.3.6.1.2.1.17.1.4.1.2';
122
# this is only for the router, to get IP of the device in question
123
my $ROUTERIPMACMIB = 'iso.3.6.1.2.1.4.22.1.2'; # ipNetToMediaPhysAddress #'iso.3.6.1.2.1.3.1.1.2';
124
# this should work for all devices
125
my $DEVICENAMEMIB  = 'iso.3.6.1.2.1.1.5'; # sysname
126
my $DEVICELOCMIB   = 'iso.3.6.1.2.1.1.6'; # syslocation
127
 
128
# snmp returns a dotted integer for the mac, but we want mac's as hex with no formatting
129
# take a dotted integer form of a mac and converts it to hex, all lower case
130
sub makeMAC {
131
   my $string = shift;
132
   my @octets = split( '\.', $string );
133
   for ( my $i = 0; $i < @octets; $i++ ) {
134
      $octets[$i] = sprintf( "%02x", $octets[$i] );
135
   }
136
   return join( '', @octets );
137
}
138
 
139
# mac's from various places can have formatting, like ##:##:##:##:## or ###-###-###
140
# this will clean all that up by removing anything except hex values
141
# it will also convert alpha's (a-f) to lower case.
142
sub cleanMac {
143
   my $mac = shift;
144
   $mac =~ s/[^a-f0-9]//gi;
145
   return lc $mac;
146
}
147
 
148
# grabs one single SNMP value from string. Assumes $OID returns only one line, then runs $regex against it.
149
sub getOneSNMPValue {
150
   my ( $oid, $community, $ip, $regex ) = @_;
151
   my $line = `snmpwalk -v1 -c $community $ip $oid`;
152
   $line =~ m/$regex/i;
153
   return $1;
154
}
155
 
156
# runs an snmpwalk using $MIB, then for each line, splits it with a regex
157
# if order is set to 12, first value of regex is a key, else second value is the key
158
sub parseSNMPQuery {
159
   my ( $MIB, $ip, $community, $regex, $order ) = @_;
160
   $order = 12 unless $order;
161
   my $return = {};
162
   my $values = `snmpwalk -v1 -c $community $ip $MIB`;
163
   print "\t\t\tsnmpwalk -v1 -c $community $ip $MIB\n" if $DEBUG > 1;
164
   foreach my $line ( split( "\n", $values ) ) {
165
      next unless $line =~ m/$regex/;
166
      if ( $order == 12 ) {
167
         $return->{$1} = $2;
168
      } else {
169
         $return->{$2} = $1;
170
      }
171
   }
172
   return $return;
173
}
174
 
136 rodolico 175
# do a reverse dns lookup of an IP address and return the hostname
176
# note that $dns is an instance of Net::DNS
138 rodolico 177
# if it is not set, will revert to using inet_aton, which only
178
# works off of the resolv.conf on the local machine
136 rodolico 179
sub getHostName {
180
   my ($dns, $ip ) = @_;
139 rodolico 181
   return '' unless $ip;
138 rodolico 182
   if ( $dns ) {
183
      foreach my $resource ( @$dns ) {
184
         my  $reply = $resource->search( $ip );
185
         next unless defined $reply;
186
         my @answer = grep { ! /^((;.*)|(\s*))$/ } split( "\n", $reply->string );
187
         $answer[0] =~ m/\s([a-z0-9.-]+)\.$/;
188
         return $1;
189
      }
190
   } else {
191
      return gethostbyaddr( inet_aton( $ip ), AF_INET );
136 rodolico 192
   }
193
   return '';
194
}
133 rodolico 195
 
196
# Load configuration file, die if we could not find it
197
# config file is a single page YAML file
198
sub loadConfig {
199
   my $filename = shift;
200
   my %config;
201
   if ( -e $filename ) {
202
      my $yaml = YAML::Tiny->read( $filename );
203
      %config = %{ $yaml->[0] };
204
   } else {
205
      die "could not locate config file $filename\n";
206
   }
207
   return \%config;
208
}
209
 
210
# simple display if --help is passed
211
sub help {
212
   use File::Basename;
213
   print basename($0) . " $VERSION\n";
214
   print <<END
215
$0 [options]
216
Options:
136 rodolico 217
   --no-snmp         - do not actually run snmp commands
218
   --debug           - set debug level
219
   --refresh         - force a refresh even if not time
220
   --version         - display version and exit
221
   --help            - This page
133 rodolico 222
END
223
}
224
 
225
# get information about one single switch
226
#
227
sub getSwitchInfo {
136 rodolico 228
   my ( $ip, $community, $ignorePorts ) = @_;
229
   my $switchInfo = {};
133 rodolico 230
   print "Working on $ip with community $community\n" if $DEBUG;
231
   $switchInfo->{$ip}->{'name'} = # get actual device name
232
      &getOneSNMPValue( $DEVICENAMEMIB,
233
                        $community,
234
                        $ip, 
235
                        qr/= STRING: "?([^"]*)"?/);
236
 
237
   $switchInfo->{$ip}->{'location'} = # and its snmp location
238
      &getOneSNMPValue( 
239
         $DEVICELOCMIB,
240
         $community,
241
         $ip, 
242
         qr/= STRING: "?([^"]*)"?/ );
243
 
244
   # get list of ports into hash with state as the value, '1' is operational
245
   my $ports = &parseSNMPQuery( $SWITCHPORTMIB, $ip, $community, qr/$SWITCHPORTMIB\.(\d+)\s=\sINTEGER:\s+(\d+)/ );
246
   print "=========Ports Hash\n" . Dumper( $ports ) . "\n" if $DEBUG == 4;
247
   foreach my $port ( keys %$ports ) {
248
      next unless $ports->{$port} == 1; # skip any non functional
249
      next if $ignorePorts->{ $port };
250
      # Get information about the ports. This may be possible to skip except on rare occassions?
251
      # get port aliases, set to port number if undef
252
      $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} = 
253
         &getOneSNMPValue( 
254
            "$SWITCHIFALIASMIB.$port", 
255
            $community, 
256
            $ip, 
257
            qr/\.\d+\s+=\s+STRING:\s+"?([^"]*)"?$/ );
258
      $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} = $port unless defined ( $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} );
259
 
260
      # get the port Description, set to port number if undef
261
      $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} = 
262
         &getOneSNMPValue( 
263
            "$SWITCHIFDESCMIB.$port", 
264
            $community, 
265
            $ip, 
266
            qr/\.\d+ = STRING: "?([^\"]*)"?$/ );
267
      $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} = $port unless defined ( $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} );
268
   }
136 rodolico 269
   return $switchInfo->{$ip};
133 rodolico 270
}
271
 
272
# get all MAC addresses on switch and associate them with the correct port numbers
273
# https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/44800-mactoport44800.html
274
sub getSwitchPortMacs {
275
   my ( $ip, $community, $ignoreList, $macList ) = @_;
276
   print "\tFinding Mac Addresses\n" if $DEBUG > 1;
277
   # get the MAC addresses into a list
278
   my $macs = &parseSNMPQuery( $SWITCHMACMIB, $ip, $community, qr/$SWITCHMACMIB\.([0-9.]+)\s=\sHex-STRING:\s+([0-9a-z ]+)$/i );
279
   print "Macs\n" . Dumper( $macs ) if $DEBUG >= 3;
280
   # find which bridges they are on
281
   print "\t\tFinding what bridges the MAC's are on\n" if $DEBUG > 2;
282
   my $macBridges = &parseSNMPQuery( $BRIDGEPORTSMIB, $ip, $community, qr/$BRIDGEPORTSMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
283
   print "MacBridges\n" . Dumper( $macBridges ) if $DEBUG >= 3;
284
   print "\t\tFinding what ports the ports are\n" if $DEBUG > 2;
285
   my $bridgeToPort = &parseSNMPQuery( $BRIDGE2PORTMIB, $ip, $community, qr/$BRIDGE2PORTMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
286
   print "BridgeToPort\n" . Dumper( $bridgeToPort ) if $DEBUG > 3;
287
   # now, merge the three together to figure out what port a particular mac is on
288
   foreach my $mac ( keys %$macs ) {
289
      print "\t\t\t$mac\n" if $DEBUG > 3;
290
      next unless defined ( $macBridges->{$mac} ) and defined ($bridgeToPort->{$macBridges->{$mac}} );
291
      my $port = $bridgeToPort->{$macBridges->{$mac}};
292
      next if $ignoreList->{$port};
293
      $macList->{&makeMAC($mac)}->{'switch'} = $ip;
294
      $macList->{&makeMAC($mac)}->{'port'} = $port;
295
      $macList->{&makeMAC($mac)}->{'originalMAC'} = $mac;
296
      $macList->{&makeMAC($mac)}->{'lastseen'} = time();
297
   }
298
}
299
 
136 rodolico 300
# get IP address from router(s)
301
# since the information is already there, we grab the interface also
133 rodolico 302
sub getRouterInfo {
303
   my ( $ip, $community, $routerInfo ) = @_;
304
   print "Working on $ip\n" if $DEBUG;
305
   print "snmpwalk -v1 -c $community $ip $ROUTERIPMACMIB\n" if $DEBUG > 1;
306
   my $values = `snmpwalk -v1 -c $community $ip $ROUTERIPMACMIB`;
307
   my @lines = split( "\n", $values );
308
   foreach my $line ( @lines ) {
309
      $line =~ m/$ROUTERIPMACMIB\.([0-9]+)\.([0-9.]+)\s=\sHex-STRING:\s([0-9a-z ]+)/i;
310
      my $interface = $1;
311
      my $ip = $2;
312
      my $mac = &cleanMac( $3 );
313
      $routerInfo->{$mac}->{'ip'} = $ip;
314
      $routerInfo->{$mac}->{'interface'} = $interface;
315
   }
316
}
317
 
318
# load tab delimited values from $filename into hashref $nonRouterEntries
319
# format is
320
# macaddress
321
#     'ip' = IP Address
322
#     'mac' = MAC Address
323
#     'hostname' = HostName
324
 
325
sub loadNonRouterEntries {
136 rodolico 326
   my ( $scriptDir, $files, $staticMaps, $routerARP ) = @_;
327
   # first, load the information from the files
328
   foreach my $filename ( @$files ) {
329
      open FN,"<$scriptDir/$filename" or die "Could not open $scriptDir/$filename: $!\n";
330
      my $line = <FN>;
133 rodolico 331
      chomp $line;
136 rodolico 332
      my @headers = split( "\t", $line );
333
      my $macIndex = 0;
334
      while ( $headers[$macIndex] !~ 'mac' && $macIndex < @headers ) {
335
         $macIndex++;
133 rodolico 336
      }
136 rodolico 337
      if ( $macIndex >= @headers ) {
338
         warn "File $filename does not appear to contain a mac column\n";
339
         return;
340
      }
341
      while ( $line = <FN> ) {
342
         next if $line =~ m/^#/;
343
         chomp $line;
344
         my @values = split( "\t", $line );
345
         my $mac = &cleanMac($values[$macIndex]);
346
         for( my $i = 0; $i < @headers; $i++ ) {
347
            # update the value if one does not already exist
348
            $routerARP->{$mac}->{$headers[$i]} = lc $values[$i] unless $routerARP->{$mac}->{$headers[$i]};
349
         }
350
      }
351
      close FN;
133 rodolico 352
   }
136 rodolico 353
   # now, update from our staticmaps
354
   foreach my $mac ( keys %$staticMaps ) {
355
      # only update ip if it doesn't exist, or if we have an override
356
      $routerARP->{$mac}->{'ip'} = $staticMaps->{$mac}->{'ip'} if $staticMaps->{$mac}->{'override'} || ! $routerARP->{$mac}->{'ip'};
357
      # these don't exist in $routerARP, so we just add them
358
      $routerARP->{$mac}->{'hostname'} = $staticMaps->{$mac}->{'hostname'};
359
      $routerARP->{$mac}->{'override'} = $staticMaps->{$mac}->{'override'};
360
   }
133 rodolico 361
}
136 rodolico 362
 
133 rodolico 363
 
364
# merge nonRouterEntries into $routerARP, with $routerARP having precedence
365
sub updateRouterWithStatic {
366
   my ( $routerARP, $nonRouterEntries ) = @_;
367
   foreach my $mac ( keys %$nonRouterEntries ) {
368
      # assign the hostname from staticmaps if there is one, and either override is true, or routerARP doesn't have one
369
      $routerARP->{$mac}->{'hostname'} = $nonRouterEntries->{$mac}->{'hostname'}
370
         if ( $nonRouterEntries->{$mac}->{'hostname'} 
371
               && ( 
372
                  ! $routerARP->{$mac}->{'hostname'} 
373
                  || $nonRouterEntries->{$mac}->{'override'} 
374
                  )
375
               );
376
      # assign the hostname from staticmaps if there is one, and either override is true, or routerARP doesn't have one
377
      $routerARP->{$mac}->{'ip'} = $nonRouterEntries->{$mac}->{'ip'}
378
         if ( $nonRouterEntries->{$mac}->{'ip'} 
379
               && ( 
380
                  ! $routerARP->{$mac}->{'ip'} 
381
                  || $nonRouterEntries->{$mac}->{'override'} 
382
                  )
383
               );
384
   }
385
}
386
 
136 rodolico 387
# get IP addresses from the list of them we have
388
sub getIPAddresses {
389
   my ( $macList, $ipList ) = @_;
390
   foreach my $mac ( keys %$macList ) {
391
      $macList->{$mac}->{'ip'} = $ipList->{$mac}->{'ip'} if $ipList->{$mac}->{'ip'};
392
   }
393
}
394
 
395
# grab names by reverse DNS from the IP addresses
396
# if that fails, or if there is an override
397
# use the name from $routerARP, if it exists;
398
sub getDNSNames {
399
   my ( $macList, $dnsResource, $routerARP ) = @_;
400
   foreach my $mac ( keys %$macList ) {
401
      if ( $routerARP->{$mac}->{'override'} && $routerARP->{$mac}->{'hostname'} ) {
402
         $macList->{$mac}->{'hostname'} = $routerARP->{$mac}->{'hostname'};
403
      } else { # try a DNS lookup
404
         $macList->{$mac}->{'hostname'} = &getHostName( $dnsResource, $macList->{$mac}->{'ip'} );
405
         # still didn't find one, so add one from $routerARP if it exists
406
         $macList->{$mac}->{'hostname'} = $routerARP->{$mac}->{'hostname'} if ! $macList->{$mac}->{'hostname'} && $routerARP->{$mac}->{'hostname'};
407
      }
408
   }
409
}
410
 
157 rodolico 411
# As a last ditch effort, we will use dig (if available) to try an get rdns entries
412
# for the IP's we've found.
413
sub doDig {
414
   return unless `which dig`;
415
   my $macList = shift;
416
   my @dnsServers = @_;
417
   foreach my $mac ( keys %$macList ) {
418
      next if $macList->{$mac}->{'hostname'}; # we already have a name
419
      next unless $macList->{$mac}->{'ip'}; # can't process if we have no IP
420
      foreach my $ns ( @dnsServers ) {
421
         my $name = `dig \@$ns -x $macList->{$mac}->{ip} +short`;
422
         chomp $name;
423
         if ( $name ) {
424
            $macList->{$mac}->{'hostname'} = $name;
425
            last;
426
         }
427
      }
428
   }
429
}
430
 
136 rodolico 431
# given a value of a number follwed by a unit (ie, 2w, 12h, 3m), determine 
432
# the unixtime for that long ago.
433
sub calcAge {
434
   my $time = shift;
435
   my %seconds = ( 
436
      's' => 1,
437
      'h' => 60*60,
438
      'd' => 86400,
439
      'w' => 7*86400,
440
      'm' => 7*30.5*86400,
441
      'y' => 86400*365.2425
442
      );
443
   $time = lc $time;
444
   $time =~ m/^(\d+)(.*)/;
445
   $time = $1;
446
   my $unit = $2;
447
   $unit = 's' unless $unit;
448
   return defined( $seconds{$unit} ) ? $time * $seconds{$unit} : 0;
449
}
450
 
451
# given an integer/modifier (1w, 3d, 10h), remove all mac entries which have not
452
# been seen since then.
453
sub cleanUpOldEntries {
454
   my ( $ttl, $list ) = @_;
455
   my $currentTime = time;
456
   my $deleteBefore = &calcAge( $ttl );
457
   if ( $deleteBefore == 0 ) {
458
      warn "Invalid ttl definition [$ttl], not cleaning up\n";
459
      return;
460
   }
461
   $deleteBefore = time - $deleteBefore;
462
   foreach my $mac ( keys %{ $list->{'macList'} } ) {
463
      if ( $list->{'macList'}->{$mac}->{'lastseen'} < $deleteBefore ) {
464
#         print 
465
#            "Deleting $mac with a last seen of " . 
466
#            $list->{'macList'}->{$mac}->{'lastseen'} . 
467
#            ", current time is $currentTime for a difference of " . 
468
#            ( $currentTime - $list->{'macList'}->{$mac}->{'lastseen'} ) . 
469
#            "\n";
470
         delete $list->{'macList'}->{$mac} if $list->{'macList'}->{$mac}->{'lastseen'};
471
      }
472
   }
473
}
474
 
133 rodolico 475
################################################################################
476
#              Main
477
################################################################################
478
 
479
# handle any command line parameters that may have been passed in
480
my $version = 0; # just used to determine if we should display the version
481
my $help = 0; # also if we want help
482
my $nosnmp = 0; # we do NOT want to run snmp commands
136 rodolico 483
my $forceRefres = 0; # force a refresh even if one is not called for now
133 rodolico 484
GetOptions (
485
            'debug|d=i'     => \$DEBUG,
486
            'nosnmp|n'      => \$nosnmp,
136 rodolico 487
            'refresh|r'     => \$forceRefres,
133 rodolico 488
            'help|h'        => \$help,
489
            'version|v'     => \$version,
490
            ) or die "Error parsing command line\n";
491
 
492
 
493
if ( $help ) { &help() ; exit; }
494
if ( $version ) { use File::Basename; print basename($0) . " $VERSION\n"; exit; }
495
 
496
# Get configuration file into $config
497
my $config = &loadConfig( $CONFIGFILE );
136 rodolico 498
print Dumper( $config ) if $DEBUG > 1; die if $DEBUG > 4;
133 rodolico 499
 
136 rodolico 500
# load the savefile, if it exists
501
my $saveFile = { 'macList' => {}, 'switchInfo' => {} };
502
# read the saved state into memory if it exists
503
if ( -e $STATEFILE ) {
504
   my $yaml = YAML::Tiny->read( $STATEFILE );
505
   $saveFile = \%{ $yaml->[0] };
506
}
134 rodolico 507
 
133 rodolico 508
 
138 rodolico 509
my $dnsResource = 0;
139 rodolico 510
eval "use Net::DNS;"; # dns lookup, apt install libnet-dns-perl
511
if ( $@ ) {
512
   $dnsResource = 0;
513
} else {
138 rodolico 514
   $dnsResource = [];
515
   # set up one dns resource for every router we have
516
   # too many failures when trying to define both of them at the same time
517
   foreach my $router ( keys %{ $config->{'routers'} } ) {
518
      push @$dnsResource, Net::DNS::Resolver->new(
519
       'nameservers' => [ $router ],
520
       'recurse' => 0
521
       );
522
   }
523
};
524
 
136 rodolico 525
my $refresh = 1; # determines if we get extra information like switch info, port aliases, etc...
526
if ( defined( $config->{'refresh'} ) ) {
527
   # get the number of seconds between refreshes
528
   $refresh = &calcAge( $config->{'refresh'} );
529
   # if we have not recorded a refresh, set the refresh time to run now
530
   $saveFile->{'lastrefresh'} = time - &calcAge( $config->{'refresh'} ) - 1 
531
      unless defined $saveFile->{'lastrefresh'};
532
   $refresh = $saveFile->{'lastrefresh'} + &calcAge( $config->{'refresh'} ) < time || $forceRefres;
533
   $saveFile->{'lastrefresh'} = time if $refresh;
534
}
535
 
536
print STDERR "Doing a full refresh\n" if $refresh && $DEBUG > 1;
537
 
538
 
539
 
133 rodolico 540
# load the information for the switches into $switchInfo.
541
foreach my $switch ( keys %{$config->{'switches'}} ) {
542
   last if $nosnmp; # do not read switches if $nosnmp set
136 rodolico 543
   my $ignoreList = { map { $_ => 1 } @{ $config->{'switches'}->{$switch}->{'portsToIgnore'} } }; # hash of ports to ignore
544
   #my $ignoreList = \%ignoreList;
133 rodolico 545
   print "ignoreList for $switch\n" . Dumper ($ignoreList) if $DEBUG > 2;
546
   # just get basic switch information, inlcuding a list of all ports which are active and not in portsToIgnore
136 rodolico 547
   $saveFile->{'switchInfo'}->{$switch} = &getSwitchInfo( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList ) if $refresh;
133 rodolico 548
   # get all the MAC's on this switch
136 rodolico 549
   &getSwitchPortMacs( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList, $saveFile->{'macList'} );
133 rodolico 550
}
551
 
136 rodolico 552
 
133 rodolico 553
my $routerARP = {};
554
# Read the ARP table from the router(s)
555
foreach my $router ( keys %{$config->{'routers'}} ) {
136 rodolico 556
   #last if $nosnmp; # do not read routers if $nosnmp set
557
   &getRouterInfo( $router,  $config->{'routers'}->{$router}->{'community'}, $routerARP ) if $refresh;
133 rodolico 558
}
559
print "Routers\n" . Dumper ($routerARP ) if $DEBUG > 2;
136 rodolico 560
# add in anything we have defined in files or in staticmaps in the config file
561
&loadNonRouterEntries( $scriptDir, $config->{'nonrouter'}, $config->{'staticmaps'}, $routerARP );
562
print "Routers after loadNonRouterEntries\n" . Dumper ($routerARP ) if $DEBUG > 2;
563
# populate the mac list with information from $routerARP
564
&getIPAddresses( $saveFile->{'macList'}, $routerARP );
565
print "Routers after getIPAddresses\n" . Dumper ($routerARP ) if $DEBUG > 2;
566
# get the DNS names
567
&getDNSNames( $saveFile->{'macList'}, $dnsResource, $routerARP ) if $refresh;
568
print "Routers after getDNSNames\n" . Dumper ($routerARP ) if $DEBUG > 2;
157 rodolico 569
&doDig( $saveFile->{'macList'}, keys %{$config->{'routers'}} );
136 rodolico 570
# clean up any old entries
571
&cleanUpOldEntries( $config->{'ttl'}, $saveFile ) if $config->{'ttl'} && $refresh;
133 rodolico 572
# save the file
573
my $yaml = YAML::Tiny->new( $saveFile );
574
$yaml->write( $STATEFILE );
575
 
576
 
577
1;
578