Subversion Repositories sysadmin_scripts

Rev

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