Subversion Repositories sysadmin_scripts

Rev

Go to most recent revision | Details | 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)
133 rodolico 74
 
136 rodolico 75
# for Debian, to get the required libraries
76
# apt install libyaml-tiny-perl libnet-dns-perl snmp
77
 
133 rodolico 78
use strict;
79
use warnings;
80
use Data::Dumper; # only used for debugging
81
use Socket; # for reverse dns entries
82
use YAML::Tiny; # apt-get libyaml-tiny-perl under debian
83
use File::Spec; # find location of script so we can put storage in same directory
84
use File::Basename;
136 rodolico 85
use Net::DNS; # dns lookup, apt install libnet-dns-perl
133 rodolico 86
 
136 rodolico 87
 
133 rodolico 88
my $DEBUG = 0;
89
 
90
# define the version number
91
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
92
use version;
136 rodolico 93
our $VERSION = version->declare("v3.3.1");
133 rodolico 94
 
95
# see https://perldoc.perl.org/Getopt/Long.html
96
use Getopt::Long;
97
# allow -vvn (ie, --verbose --verbose --dryrun)
98
Getopt::Long::Configure ("bundling");
99
 
100
 
101
 
102
my %config; # we read the configuration file into this
103
 
104
# where the script is located
105
my $scriptDir = dirname( File::Spec->rel2abs( __FILE__ ) );
106
# put the statefile in there
107
my $STATEFILE = $scriptDir . '/mapSwitches.yaml';
108
my $CONFIGFILE = $scriptDir . '/mapSwitches.config.yaml';
109
 
136 rodolico 110
 
111
 
133 rodolico 112
my $SWITCHPORTMIB  = 'iso.3.6.1.2.1.2.2.1.8'; # returns port number and state, with a state of '1' meaning operational
113
my $SWITCHMACMIB   = 'iso.3.6.1.2.1.17.4.3.1.1'; # dot1dTpFdbAddress, aka mac addresses
114
my $SWITCHIFALIASMIB = 'iso.3.6.1.2.1.31.1.1.1.18'; # ifAlias, the the 'alias' field
115
my $SWITCHIFDESCMIB = 'iso.3.6.1.2.1.2.2.1.2'; # ifDescr, the "description" field
116
my $BRIDGEPORTSMIB = 'iso.3.6.1.2.1.17.4.3.1.2';
117
my $BRIDGE2PORTMIB = 'iso.3.6.1.2.1.17.1.4.1.2';
118
# this is only for the router, to get IP of the device in question
119
my $ROUTERIPMACMIB = 'iso.3.6.1.2.1.4.22.1.2'; # ipNetToMediaPhysAddress #'iso.3.6.1.2.1.3.1.1.2';
120
# this should work for all devices
121
my $DEVICENAMEMIB  = 'iso.3.6.1.2.1.1.5'; # sysname
122
my $DEVICELOCMIB   = 'iso.3.6.1.2.1.1.6'; # syslocation
123
 
124
# snmp returns a dotted integer for the mac, but we want mac's as hex with no formatting
125
# take a dotted integer form of a mac and converts it to hex, all lower case
126
sub makeMAC {
127
   my $string = shift;
128
   my @octets = split( '\.', $string );
129
   for ( my $i = 0; $i < @octets; $i++ ) {
130
      $octets[$i] = sprintf( "%02x", $octets[$i] );
131
   }
132
   return join( '', @octets );
133
}
134
 
135
# mac's from various places can have formatting, like ##:##:##:##:## or ###-###-###
136
# this will clean all that up by removing anything except hex values
137
# it will also convert alpha's (a-f) to lower case.
138
sub cleanMac {
139
   my $mac = shift;
140
   $mac =~ s/[^a-f0-9]//gi;
141
   return lc $mac;
142
}
143
 
144
# grabs one single SNMP value from string. Assumes $OID returns only one line, then runs $regex against it.
145
sub getOneSNMPValue {
146
   my ( $oid, $community, $ip, $regex ) = @_;
147
   my $line = `snmpwalk -v1 -c $community $ip $oid`;
148
   $line =~ m/$regex/i;
149
   return $1;
150
}
151
 
152
# runs an snmpwalk using $MIB, then for each line, splits it with a regex
153
# if order is set to 12, first value of regex is a key, else second value is the key
154
sub parseSNMPQuery {
155
   my ( $MIB, $ip, $community, $regex, $order ) = @_;
156
   $order = 12 unless $order;
157
   my $return = {};
158
   my $values = `snmpwalk -v1 -c $community $ip $MIB`;
159
   print "\t\t\tsnmpwalk -v1 -c $community $ip $MIB\n" if $DEBUG > 1;
160
   foreach my $line ( split( "\n", $values ) ) {
161
      next unless $line =~ m/$regex/;
162
      if ( $order == 12 ) {
163
         $return->{$1} = $2;
164
      } else {
165
         $return->{$2} = $1;
166
      }
167
   }
168
   return $return;
169
}
170
 
136 rodolico 171
# do a reverse dns lookup of an IP address and return the hostname
172
# note that $dns is an instance of Net::DNS
173
sub getHostName {
174
   my ($dns, $ip ) = @_;
175
   foreach my $resource ( @$dns ) {
176
      my  $reply = $resource->search( $ip );
177
      next unless defined $reply;
178
      my @answer = grep { ! /^((;.*)|(\s*))$/ } split( "\n", $reply->string );
179
      $answer[0] =~ m/\s([a-z0-9.-]+)\.$/;
180
      return $1;
181
   }
182
   return '';
183
}
133 rodolico 184
 
185
# Load configuration file, die if we could not find it
186
# config file is a single page YAML file
187
sub loadConfig {
188
   my $filename = shift;
189
   my %config;
190
   if ( -e $filename ) {
191
      my $yaml = YAML::Tiny->read( $filename );
192
      %config = %{ $yaml->[0] };
193
   } else {
194
      die "could not locate config file $filename\n";
195
   }
196
   return \%config;
197
}
198
 
199
# simple display if --help is passed
200
sub help {
201
   use File::Basename;
202
   print basename($0) . " $VERSION\n";
203
   print <<END
204
$0 [options]
205
Options:
136 rodolico 206
   --no-snmp         - do not actually run snmp commands
207
   --debug           - set debug level
208
   --refresh         - force a refresh even if not time
209
   --version         - display version and exit
210
   --help            - This page
133 rodolico 211
END
212
}
213
 
214
# get information about one single switch
215
#
216
sub getSwitchInfo {
136 rodolico 217
   my ( $ip, $community, $ignorePorts ) = @_;
218
   my $switchInfo = {};
133 rodolico 219
   print "Working on $ip with community $community\n" if $DEBUG;
220
   $switchInfo->{$ip}->{'name'} = # get actual device name
221
      &getOneSNMPValue( $DEVICENAMEMIB,
222
                        $community,
223
                        $ip, 
224
                        qr/= STRING: "?([^"]*)"?/);
225
 
226
   $switchInfo->{$ip}->{'location'} = # and its snmp location
227
      &getOneSNMPValue( 
228
         $DEVICELOCMIB,
229
         $community,
230
         $ip, 
231
         qr/= STRING: "?([^"]*)"?/ );
232
 
233
   # get list of ports into hash with state as the value, '1' is operational
234
   my $ports = &parseSNMPQuery( $SWITCHPORTMIB, $ip, $community, qr/$SWITCHPORTMIB\.(\d+)\s=\sINTEGER:\s+(\d+)/ );
235
   print "=========Ports Hash\n" . Dumper( $ports ) . "\n" if $DEBUG == 4;
236
   foreach my $port ( keys %$ports ) {
237
      next unless $ports->{$port} == 1; # skip any non functional
238
      next if $ignorePorts->{ $port };
239
      # Get information about the ports. This may be possible to skip except on rare occassions?
240
      # get port aliases, set to port number if undef
241
      $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} = 
242
         &getOneSNMPValue( 
243
            "$SWITCHIFALIASMIB.$port", 
244
            $community, 
245
            $ip, 
246
            qr/\.\d+\s+=\s+STRING:\s+"?([^"]*)"?$/ );
247
      $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} = $port unless defined ( $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} );
248
 
249
      # get the port Description, set to port number if undef
250
      $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} = 
251
         &getOneSNMPValue( 
252
            "$SWITCHIFDESCMIB.$port", 
253
            $community, 
254
            $ip, 
255
            qr/\.\d+ = STRING: "?([^\"]*)"?$/ );
256
      $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} = $port unless defined ( $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} );
257
   }
136 rodolico 258
   return $switchInfo->{$ip};
133 rodolico 259
}
260
 
261
# get all MAC addresses on switch and associate them with the correct port numbers
262
# https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/44800-mactoport44800.html
263
sub getSwitchPortMacs {
264
   my ( $ip, $community, $ignoreList, $macList ) = @_;
265
   print "\tFinding Mac Addresses\n" if $DEBUG > 1;
266
   # get the MAC addresses into a list
267
   my $macs = &parseSNMPQuery( $SWITCHMACMIB, $ip, $community, qr/$SWITCHMACMIB\.([0-9.]+)\s=\sHex-STRING:\s+([0-9a-z ]+)$/i );
268
   print "Macs\n" . Dumper( $macs ) if $DEBUG >= 3;
269
   # find which bridges they are on
270
   print "\t\tFinding what bridges the MAC's are on\n" if $DEBUG > 2;
271
   my $macBridges = &parseSNMPQuery( $BRIDGEPORTSMIB, $ip, $community, qr/$BRIDGEPORTSMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
272
   print "MacBridges\n" . Dumper( $macBridges ) if $DEBUG >= 3;
273
   print "\t\tFinding what ports the ports are\n" if $DEBUG > 2;
274
   my $bridgeToPort = &parseSNMPQuery( $BRIDGE2PORTMIB, $ip, $community, qr/$BRIDGE2PORTMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
275
   print "BridgeToPort\n" . Dumper( $bridgeToPort ) if $DEBUG > 3;
276
   # now, merge the three together to figure out what port a particular mac is on
277
   foreach my $mac ( keys %$macs ) {
278
      print "\t\t\t$mac\n" if $DEBUG > 3;
279
      next unless defined ( $macBridges->{$mac} ) and defined ($bridgeToPort->{$macBridges->{$mac}} );
280
      my $port = $bridgeToPort->{$macBridges->{$mac}};
281
      next if $ignoreList->{$port};
282
      $macList->{&makeMAC($mac)}->{'switch'} = $ip;
283
      $macList->{&makeMAC($mac)}->{'port'} = $port;
284
      $macList->{&makeMAC($mac)}->{'originalMAC'} = $mac;
285
      $macList->{&makeMAC($mac)}->{'lastseen'} = time();
286
   }
287
}
288
 
136 rodolico 289
# get IP address from router(s)
290
# since the information is already there, we grab the interface also
133 rodolico 291
sub getRouterInfo {
292
   my ( $ip, $community, $routerInfo ) = @_;
293
   print "Working on $ip\n" if $DEBUG;
294
   print "snmpwalk -v1 -c $community $ip $ROUTERIPMACMIB\n" if $DEBUG > 1;
295
   my $values = `snmpwalk -v1 -c $community $ip $ROUTERIPMACMIB`;
296
   my @lines = split( "\n", $values );
297
   foreach my $line ( @lines ) {
298
      $line =~ m/$ROUTERIPMACMIB\.([0-9]+)\.([0-9.]+)\s=\sHex-STRING:\s([0-9a-z ]+)/i;
299
      my $interface = $1;
300
      my $ip = $2;
301
      my $mac = &cleanMac( $3 );
302
      $routerInfo->{$mac}->{'ip'} = $ip;
303
      $routerInfo->{$mac}->{'interface'} = $interface;
304
   }
305
}
306
 
307
# load tab delimited values from $filename into hashref $nonRouterEntries
308
# format is
309
# macaddress
310
#     'ip' = IP Address
311
#     'mac' = MAC Address
312
#     'hostname' = HostName
313
 
314
sub loadNonRouterEntries {
136 rodolico 315
   my ( $scriptDir, $files, $staticMaps, $routerARP ) = @_;
316
   # first, load the information from the files
317
   foreach my $filename ( @$files ) {
318
      open FN,"<$scriptDir/$filename" or die "Could not open $scriptDir/$filename: $!\n";
319
      my $line = <FN>;
133 rodolico 320
      chomp $line;
136 rodolico 321
      my @headers = split( "\t", $line );
322
      my $macIndex = 0;
323
      while ( $headers[$macIndex] !~ 'mac' && $macIndex < @headers ) {
324
         $macIndex++;
133 rodolico 325
      }
136 rodolico 326
      if ( $macIndex >= @headers ) {
327
         warn "File $filename does not appear to contain a mac column\n";
328
         return;
329
      }
330
      while ( $line = <FN> ) {
331
         next if $line =~ m/^#/;
332
         chomp $line;
333
         my @values = split( "\t", $line );
334
         my $mac = &cleanMac($values[$macIndex]);
335
         for( my $i = 0; $i < @headers; $i++ ) {
336
            # update the value if one does not already exist
337
            $routerARP->{$mac}->{$headers[$i]} = lc $values[$i] unless $routerARP->{$mac}->{$headers[$i]};
338
         }
339
      }
340
      close FN;
133 rodolico 341
   }
136 rodolico 342
   # now, update from our staticmaps
343
   foreach my $mac ( keys %$staticMaps ) {
344
      # only update ip if it doesn't exist, or if we have an override
345
      $routerARP->{$mac}->{'ip'} = $staticMaps->{$mac}->{'ip'} if $staticMaps->{$mac}->{'override'} || ! $routerARP->{$mac}->{'ip'};
346
      # these don't exist in $routerARP, so we just add them
347
      $routerARP->{$mac}->{'hostname'} = $staticMaps->{$mac}->{'hostname'};
348
      $routerARP->{$mac}->{'override'} = $staticMaps->{$mac}->{'override'};
349
   }
133 rodolico 350
}
136 rodolico 351
 
133 rodolico 352
 
353
# merge nonRouterEntries into $routerARP, with $routerARP having precedence
354
sub updateRouterWithStatic {
355
   my ( $routerARP, $nonRouterEntries ) = @_;
356
   foreach my $mac ( keys %$nonRouterEntries ) {
357
      # assign the hostname from staticmaps if there is one, and either override is true, or routerARP doesn't have one
358
      $routerARP->{$mac}->{'hostname'} = $nonRouterEntries->{$mac}->{'hostname'}
359
         if ( $nonRouterEntries->{$mac}->{'hostname'} 
360
               && ( 
361
                  ! $routerARP->{$mac}->{'hostname'} 
362
                  || $nonRouterEntries->{$mac}->{'override'} 
363
                  )
364
               );
365
      # assign the hostname from staticmaps if there is one, and either override is true, or routerARP doesn't have one
366
      $routerARP->{$mac}->{'ip'} = $nonRouterEntries->{$mac}->{'ip'}
367
         if ( $nonRouterEntries->{$mac}->{'ip'} 
368
               && ( 
369
                  ! $routerARP->{$mac}->{'ip'} 
370
                  || $nonRouterEntries->{$mac}->{'override'} 
371
                  )
372
               );
373
   }
374
}
375
 
136 rodolico 376
# get IP addresses from the list of them we have
377
sub getIPAddresses {
378
   my ( $macList, $ipList ) = @_;
379
   foreach my $mac ( keys %$macList ) {
380
      $macList->{$mac}->{'ip'} = $ipList->{$mac}->{'ip'} if $ipList->{$mac}->{'ip'};
381
   }
382
}
383
 
384
# grab names by reverse DNS from the IP addresses
385
# if that fails, or if there is an override
386
# use the name from $routerARP, if it exists;
387
sub getDNSNames {
388
   my ( $macList, $dnsResource, $routerARP ) = @_;
389
   foreach my $mac ( keys %$macList ) {
390
      if ( $routerARP->{$mac}->{'override'} && $routerARP->{$mac}->{'hostname'} ) {
391
         $macList->{$mac}->{'hostname'} = $routerARP->{$mac}->{'hostname'};
392
      } else { # try a DNS lookup
393
         $macList->{$mac}->{'hostname'} = &getHostName( $dnsResource, $macList->{$mac}->{'ip'} );
394
         # still didn't find one, so add one from $routerARP if it exists
395
         $macList->{$mac}->{'hostname'} = $routerARP->{$mac}->{'hostname'} if ! $macList->{$mac}->{'hostname'} && $routerARP->{$mac}->{'hostname'};
396
      }
397
   }
398
}
399
 
400
# given a value of a number follwed by a unit (ie, 2w, 12h, 3m), determine 
401
# the unixtime for that long ago.
402
sub calcAge {
403
   my $time = shift;
404
   my %seconds = ( 
405
      's' => 1,
406
      'h' => 60*60,
407
      'd' => 86400,
408
      'w' => 7*86400,
409
      'm' => 7*30.5*86400,
410
      'y' => 86400*365.2425
411
      );
412
   $time = lc $time;
413
   $time =~ m/^(\d+)(.*)/;
414
   $time = $1;
415
   my $unit = $2;
416
   $unit = 's' unless $unit;
417
   return defined( $seconds{$unit} ) ? $time * $seconds{$unit} : 0;
418
}
419
 
420
# given an integer/modifier (1w, 3d, 10h), remove all mac entries which have not
421
# been seen since then.
422
sub cleanUpOldEntries {
423
   my ( $ttl, $list ) = @_;
424
   my $currentTime = time;
425
   my $deleteBefore = &calcAge( $ttl );
426
   if ( $deleteBefore == 0 ) {
427
      warn "Invalid ttl definition [$ttl], not cleaning up\n";
428
      return;
429
   }
430
   $deleteBefore = time - $deleteBefore;
431
   foreach my $mac ( keys %{ $list->{'macList'} } ) {
432
      if ( $list->{'macList'}->{$mac}->{'lastseen'} < $deleteBefore ) {
433
#         print 
434
#            "Deleting $mac with a last seen of " . 
435
#            $list->{'macList'}->{$mac}->{'lastseen'} . 
436
#            ", current time is $currentTime for a difference of " . 
437
#            ( $currentTime - $list->{'macList'}->{$mac}->{'lastseen'} ) . 
438
#            "\n";
439
         delete $list->{'macList'}->{$mac} if $list->{'macList'}->{$mac}->{'lastseen'};
440
      }
441
   }
442
}
443
 
133 rodolico 444
################################################################################
445
#              Main
446
################################################################################
447
 
448
# handle any command line parameters that may have been passed in
449
my $version = 0; # just used to determine if we should display the version
450
my $help = 0; # also if we want help
451
my $nosnmp = 0; # we do NOT want to run snmp commands
136 rodolico 452
my $forceRefres = 0; # force a refresh even if one is not called for now
133 rodolico 453
GetOptions (
454
            'debug|d=i'     => \$DEBUG,
455
            'nosnmp|n'      => \$nosnmp,
136 rodolico 456
            'refresh|r'     => \$forceRefres,
133 rodolico 457
            'help|h'        => \$help,
458
            'version|v'     => \$version,
459
            ) or die "Error parsing command line\n";
460
 
461
 
462
if ( $help ) { &help() ; exit; }
463
if ( $version ) { use File::Basename; print basename($0) . " $VERSION\n"; exit; }
464
 
465
# Get configuration file into $config
466
my $config = &loadConfig( $CONFIGFILE );
136 rodolico 467
print Dumper( $config ) if $DEBUG > 1; die if $DEBUG > 4;
133 rodolico 468
 
136 rodolico 469
# load the savefile, if it exists
470
my $saveFile = { 'macList' => {}, 'switchInfo' => {} };
471
# read the saved state into memory if it exists
472
if ( -e $STATEFILE ) {
473
   my $yaml = YAML::Tiny->read( $STATEFILE );
474
   $saveFile = \%{ $yaml->[0] };
475
}
134 rodolico 476
 
136 rodolico 477
# set up one dns resource for every router we have
478
# too many failures when trying to define both of them at the same time
479
my $dnsResource = [];
480
foreach my $router ( keys %{ $config->{'routers'} } ) {
481
   push @$dnsResource, Net::DNS::Resolver->new(
482
    'nameservers' => [ $router ],
483
    'recurse' => 0
484
    );
485
}
133 rodolico 486
 
136 rodolico 487
my $refresh = 1; # determines if we get extra information like switch info, port aliases, etc...
488
if ( defined( $config->{'refresh'} ) ) {
489
   # get the number of seconds between refreshes
490
   $refresh = &calcAge( $config->{'refresh'} );
491
   # if we have not recorded a refresh, set the refresh time to run now
492
   $saveFile->{'lastrefresh'} = time - &calcAge( $config->{'refresh'} ) - 1 
493
      unless defined $saveFile->{'lastrefresh'};
494
   $refresh = $saveFile->{'lastrefresh'} + &calcAge( $config->{'refresh'} ) < time || $forceRefres;
495
   $saveFile->{'lastrefresh'} = time if $refresh;
496
}
497
 
498
print STDERR "Doing a full refresh\n" if $refresh && $DEBUG > 1;
499
 
500
 
501
 
133 rodolico 502
# load the information for the switches into $switchInfo.
503
foreach my $switch ( keys %{$config->{'switches'}} ) {
504
   last if $nosnmp; # do not read switches if $nosnmp set
136 rodolico 505
   my $ignoreList = { map { $_ => 1 } @{ $config->{'switches'}->{$switch}->{'portsToIgnore'} } }; # hash of ports to ignore
506
   #my $ignoreList = \%ignoreList;
133 rodolico 507
   print "ignoreList for $switch\n" . Dumper ($ignoreList) if $DEBUG > 2;
508
   # just get basic switch information, inlcuding a list of all ports which are active and not in portsToIgnore
136 rodolico 509
   $saveFile->{'switchInfo'}->{$switch} = &getSwitchInfo( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList ) if $refresh;
133 rodolico 510
   # get all the MAC's on this switch
136 rodolico 511
   &getSwitchPortMacs( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList, $saveFile->{'macList'} );
133 rodolico 512
}
513
 
136 rodolico 514
 
133 rodolico 515
my $routerARP = {};
516
# Read the ARP table from the router(s)
517
foreach my $router ( keys %{$config->{'routers'}} ) {
136 rodolico 518
   #last if $nosnmp; # do not read routers if $nosnmp set
519
   &getRouterInfo( $router,  $config->{'routers'}->{$router}->{'community'}, $routerARP ) if $refresh;
133 rodolico 520
}
521
print "Routers\n" . Dumper ($routerARP ) if $DEBUG > 2;
136 rodolico 522
# add in anything we have defined in files or in staticmaps in the config file
523
&loadNonRouterEntries( $scriptDir, $config->{'nonrouter'}, $config->{'staticmaps'}, $routerARP );
524
print "Routers after loadNonRouterEntries\n" . Dumper ($routerARP ) if $DEBUG > 2;
525
# populate the mac list with information from $routerARP
526
&getIPAddresses( $saveFile->{'macList'}, $routerARP );
527
print "Routers after getIPAddresses\n" . Dumper ($routerARP ) if $DEBUG > 2;
528
# get the DNS names
529
&getDNSNames( $saveFile->{'macList'}, $dnsResource, $routerARP ) if $refresh;
530
print "Routers after getDNSNames\n" . Dumper ($routerARP ) if $DEBUG > 2;
531
# clean up any old entries
532
&cleanUpOldEntries( $config->{'ttl'}, $saveFile ) if $config->{'ttl'} && $refresh;
133 rodolico 533
# save the file
534
my $yaml = YAML::Tiny->new( $saveFile );
535
$yaml->write( $STATEFILE );
536
 
537
 
538
1;
539