Subversion Repositories sysadmin_scripts

Rev

Rev 138 | Rev 157 | 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 ) = @_;
139 rodolico 178
   return '' unless $ip;
138 rodolico 179
   if ( $dns ) {
180
      foreach my $resource ( @$dns ) {
181
         my  $reply = $resource->search( $ip );
182
         next unless defined $reply;
183
         my @answer = grep { ! /^((;.*)|(\s*))$/ } split( "\n", $reply->string );
184
         $answer[0] =~ m/\s([a-z0-9.-]+)\.$/;
185
         return $1;
186
      }
187
   } else {
188
      return gethostbyaddr( inet_aton( $ip ), AF_INET );
136 rodolico 189
   }
190
   return '';
191
}
133 rodolico 192
 
193
# Load configuration file, die if we could not find it
194
# config file is a single page YAML file
195
sub loadConfig {
196
   my $filename = shift;
197
   my %config;
198
   if ( -e $filename ) {
199
      my $yaml = YAML::Tiny->read( $filename );
200
      %config = %{ $yaml->[0] };
201
   } else {
202
      die "could not locate config file $filename\n";
203
   }
204
   return \%config;
205
}
206
 
207
# simple display if --help is passed
208
sub help {
209
   use File::Basename;
210
   print basename($0) . " $VERSION\n";
211
   print <<END
212
$0 [options]
213
Options:
136 rodolico 214
   --no-snmp         - do not actually run snmp commands
215
   --debug           - set debug level
216
   --refresh         - force a refresh even if not time
217
   --version         - display version and exit
218
   --help            - This page
133 rodolico 219
END
220
}
221
 
222
# get information about one single switch
223
#
224
sub getSwitchInfo {
136 rodolico 225
   my ( $ip, $community, $ignorePorts ) = @_;
226
   my $switchInfo = {};
133 rodolico 227
   print "Working on $ip with community $community\n" if $DEBUG;
228
   $switchInfo->{$ip}->{'name'} = # get actual device name
229
      &getOneSNMPValue( $DEVICENAMEMIB,
230
                        $community,
231
                        $ip, 
232
                        qr/= STRING: "?([^"]*)"?/);
233
 
234
   $switchInfo->{$ip}->{'location'} = # and its snmp location
235
      &getOneSNMPValue( 
236
         $DEVICELOCMIB,
237
         $community,
238
         $ip, 
239
         qr/= STRING: "?([^"]*)"?/ );
240
 
241
   # get list of ports into hash with state as the value, '1' is operational
242
   my $ports = &parseSNMPQuery( $SWITCHPORTMIB, $ip, $community, qr/$SWITCHPORTMIB\.(\d+)\s=\sINTEGER:\s+(\d+)/ );
243
   print "=========Ports Hash\n" . Dumper( $ports ) . "\n" if $DEBUG == 4;
244
   foreach my $port ( keys %$ports ) {
245
      next unless $ports->{$port} == 1; # skip any non functional
246
      next if $ignorePorts->{ $port };
247
      # Get information about the ports. This may be possible to skip except on rare occassions?
248
      # get port aliases, set to port number if undef
249
      $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} = 
250
         &getOneSNMPValue( 
251
            "$SWITCHIFALIASMIB.$port", 
252
            $community, 
253
            $ip, 
254
            qr/\.\d+\s+=\s+STRING:\s+"?([^"]*)"?$/ );
255
      $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} = $port unless defined ( $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} );
256
 
257
      # get the port Description, set to port number if undef
258
      $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} = 
259
         &getOneSNMPValue( 
260
            "$SWITCHIFDESCMIB.$port", 
261
            $community, 
262
            $ip, 
263
            qr/\.\d+ = STRING: "?([^\"]*)"?$/ );
264
      $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} = $port unless defined ( $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} );
265
   }
136 rodolico 266
   return $switchInfo->{$ip};
133 rodolico 267
}
268
 
269
# get all MAC addresses on switch and associate them with the correct port numbers
270
# https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/44800-mactoport44800.html
271
sub getSwitchPortMacs {
272
   my ( $ip, $community, $ignoreList, $macList ) = @_;
273
   print "\tFinding Mac Addresses\n" if $DEBUG > 1;
274
   # get the MAC addresses into a list
275
   my $macs = &parseSNMPQuery( $SWITCHMACMIB, $ip, $community, qr/$SWITCHMACMIB\.([0-9.]+)\s=\sHex-STRING:\s+([0-9a-z ]+)$/i );
276
   print "Macs\n" . Dumper( $macs ) if $DEBUG >= 3;
277
   # find which bridges they are on
278
   print "\t\tFinding what bridges the MAC's are on\n" if $DEBUG > 2;
279
   my $macBridges = &parseSNMPQuery( $BRIDGEPORTSMIB, $ip, $community, qr/$BRIDGEPORTSMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
280
   print "MacBridges\n" . Dumper( $macBridges ) if $DEBUG >= 3;
281
   print "\t\tFinding what ports the ports are\n" if $DEBUG > 2;
282
   my $bridgeToPort = &parseSNMPQuery( $BRIDGE2PORTMIB, $ip, $community, qr/$BRIDGE2PORTMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
283
   print "BridgeToPort\n" . Dumper( $bridgeToPort ) if $DEBUG > 3;
284
   # now, merge the three together to figure out what port a particular mac is on
285
   foreach my $mac ( keys %$macs ) {
286
      print "\t\t\t$mac\n" if $DEBUG > 3;
287
      next unless defined ( $macBridges->{$mac} ) and defined ($bridgeToPort->{$macBridges->{$mac}} );
288
      my $port = $bridgeToPort->{$macBridges->{$mac}};
289
      next if $ignoreList->{$port};
290
      $macList->{&makeMAC($mac)}->{'switch'} = $ip;
291
      $macList->{&makeMAC($mac)}->{'port'} = $port;
292
      $macList->{&makeMAC($mac)}->{'originalMAC'} = $mac;
293
      $macList->{&makeMAC($mac)}->{'lastseen'} = time();
294
   }
295
}
296
 
136 rodolico 297
# get IP address from router(s)
298
# since the information is already there, we grab the interface also
133 rodolico 299
sub getRouterInfo {
300
   my ( $ip, $community, $routerInfo ) = @_;
301
   print "Working on $ip\n" if $DEBUG;
302
   print "snmpwalk -v1 -c $community $ip $ROUTERIPMACMIB\n" if $DEBUG > 1;
303
   my $values = `snmpwalk -v1 -c $community $ip $ROUTERIPMACMIB`;
304
   my @lines = split( "\n", $values );
305
   foreach my $line ( @lines ) {
306
      $line =~ m/$ROUTERIPMACMIB\.([0-9]+)\.([0-9.]+)\s=\sHex-STRING:\s([0-9a-z ]+)/i;
307
      my $interface = $1;
308
      my $ip = $2;
309
      my $mac = &cleanMac( $3 );
310
      $routerInfo->{$mac}->{'ip'} = $ip;
311
      $routerInfo->{$mac}->{'interface'} = $interface;
312
   }
313
}
314
 
315
# load tab delimited values from $filename into hashref $nonRouterEntries
316
# format is
317
# macaddress
318
#     'ip' = IP Address
319
#     'mac' = MAC Address
320
#     'hostname' = HostName
321
 
322
sub loadNonRouterEntries {
136 rodolico 323
   my ( $scriptDir, $files, $staticMaps, $routerARP ) = @_;
324
   # first, load the information from the files
325
   foreach my $filename ( @$files ) {
326
      open FN,"<$scriptDir/$filename" or die "Could not open $scriptDir/$filename: $!\n";
327
      my $line = <FN>;
133 rodolico 328
      chomp $line;
136 rodolico 329
      my @headers = split( "\t", $line );
330
      my $macIndex = 0;
331
      while ( $headers[$macIndex] !~ 'mac' && $macIndex < @headers ) {
332
         $macIndex++;
133 rodolico 333
      }
136 rodolico 334
      if ( $macIndex >= @headers ) {
335
         warn "File $filename does not appear to contain a mac column\n";
336
         return;
337
      }
338
      while ( $line = <FN> ) {
339
         next if $line =~ m/^#/;
340
         chomp $line;
341
         my @values = split( "\t", $line );
342
         my $mac = &cleanMac($values[$macIndex]);
343
         for( my $i = 0; $i < @headers; $i++ ) {
344
            # update the value if one does not already exist
345
            $routerARP->{$mac}->{$headers[$i]} = lc $values[$i] unless $routerARP->{$mac}->{$headers[$i]};
346
         }
347
      }
348
      close FN;
133 rodolico 349
   }
136 rodolico 350
   # now, update from our staticmaps
351
   foreach my $mac ( keys %$staticMaps ) {
352
      # only update ip if it doesn't exist, or if we have an override
353
      $routerARP->{$mac}->{'ip'} = $staticMaps->{$mac}->{'ip'} if $staticMaps->{$mac}->{'override'} || ! $routerARP->{$mac}->{'ip'};
354
      # these don't exist in $routerARP, so we just add them
355
      $routerARP->{$mac}->{'hostname'} = $staticMaps->{$mac}->{'hostname'};
356
      $routerARP->{$mac}->{'override'} = $staticMaps->{$mac}->{'override'};
357
   }
133 rodolico 358
}
136 rodolico 359
 
133 rodolico 360
 
361
# merge nonRouterEntries into $routerARP, with $routerARP having precedence
362
sub updateRouterWithStatic {
363
   my ( $routerARP, $nonRouterEntries ) = @_;
364
   foreach my $mac ( keys %$nonRouterEntries ) {
365
      # assign the hostname from staticmaps if there is one, and either override is true, or routerARP doesn't have one
366
      $routerARP->{$mac}->{'hostname'} = $nonRouterEntries->{$mac}->{'hostname'}
367
         if ( $nonRouterEntries->{$mac}->{'hostname'} 
368
               && ( 
369
                  ! $routerARP->{$mac}->{'hostname'} 
370
                  || $nonRouterEntries->{$mac}->{'override'} 
371
                  )
372
               );
373
      # assign the hostname from staticmaps if there is one, and either override is true, or routerARP doesn't have one
374
      $routerARP->{$mac}->{'ip'} = $nonRouterEntries->{$mac}->{'ip'}
375
         if ( $nonRouterEntries->{$mac}->{'ip'} 
376
               && ( 
377
                  ! $routerARP->{$mac}->{'ip'} 
378
                  || $nonRouterEntries->{$mac}->{'override'} 
379
                  )
380
               );
381
   }
382
}
383
 
136 rodolico 384
# get IP addresses from the list of them we have
385
sub getIPAddresses {
386
   my ( $macList, $ipList ) = @_;
387
   foreach my $mac ( keys %$macList ) {
388
      $macList->{$mac}->{'ip'} = $ipList->{$mac}->{'ip'} if $ipList->{$mac}->{'ip'};
389
   }
390
}
391
 
392
# grab names by reverse DNS from the IP addresses
393
# if that fails, or if there is an override
394
# use the name from $routerARP, if it exists;
395
sub getDNSNames {
396
   my ( $macList, $dnsResource, $routerARP ) = @_;
397
   foreach my $mac ( keys %$macList ) {
398
      if ( $routerARP->{$mac}->{'override'} && $routerARP->{$mac}->{'hostname'} ) {
399
         $macList->{$mac}->{'hostname'} = $routerARP->{$mac}->{'hostname'};
400
      } else { # try a DNS lookup
401
         $macList->{$mac}->{'hostname'} = &getHostName( $dnsResource, $macList->{$mac}->{'ip'} );
402
         # still didn't find one, so add one from $routerARP if it exists
403
         $macList->{$mac}->{'hostname'} = $routerARP->{$mac}->{'hostname'} if ! $macList->{$mac}->{'hostname'} && $routerARP->{$mac}->{'hostname'};
404
      }
405
   }
406
}
407
 
408
# given a value of a number follwed by a unit (ie, 2w, 12h, 3m), determine 
409
# the unixtime for that long ago.
410
sub calcAge {
411
   my $time = shift;
412
   my %seconds = ( 
413
      's' => 1,
414
      'h' => 60*60,
415
      'd' => 86400,
416
      'w' => 7*86400,
417
      'm' => 7*30.5*86400,
418
      'y' => 86400*365.2425
419
      );
420
   $time = lc $time;
421
   $time =~ m/^(\d+)(.*)/;
422
   $time = $1;
423
   my $unit = $2;
424
   $unit = 's' unless $unit;
425
   return defined( $seconds{$unit} ) ? $time * $seconds{$unit} : 0;
426
}
427
 
428
# given an integer/modifier (1w, 3d, 10h), remove all mac entries which have not
429
# been seen since then.
430
sub cleanUpOldEntries {
431
   my ( $ttl, $list ) = @_;
432
   my $currentTime = time;
433
   my $deleteBefore = &calcAge( $ttl );
434
   if ( $deleteBefore == 0 ) {
435
      warn "Invalid ttl definition [$ttl], not cleaning up\n";
436
      return;
437
   }
438
   $deleteBefore = time - $deleteBefore;
439
   foreach my $mac ( keys %{ $list->{'macList'} } ) {
440
      if ( $list->{'macList'}->{$mac}->{'lastseen'} < $deleteBefore ) {
441
#         print 
442
#            "Deleting $mac with a last seen of " . 
443
#            $list->{'macList'}->{$mac}->{'lastseen'} . 
444
#            ", current time is $currentTime for a difference of " . 
445
#            ( $currentTime - $list->{'macList'}->{$mac}->{'lastseen'} ) . 
446
#            "\n";
447
         delete $list->{'macList'}->{$mac} if $list->{'macList'}->{$mac}->{'lastseen'};
448
      }
449
   }
450
}
451
 
133 rodolico 452
################################################################################
453
#              Main
454
################################################################################
455
 
456
# handle any command line parameters that may have been passed in
457
my $version = 0; # just used to determine if we should display the version
458
my $help = 0; # also if we want help
459
my $nosnmp = 0; # we do NOT want to run snmp commands
136 rodolico 460
my $forceRefres = 0; # force a refresh even if one is not called for now
133 rodolico 461
GetOptions (
462
            'debug|d=i'     => \$DEBUG,
463
            'nosnmp|n'      => \$nosnmp,
136 rodolico 464
            'refresh|r'     => \$forceRefres,
133 rodolico 465
            'help|h'        => \$help,
466
            'version|v'     => \$version,
467
            ) or die "Error parsing command line\n";
468
 
469
 
470
if ( $help ) { &help() ; exit; }
471
if ( $version ) { use File::Basename; print basename($0) . " $VERSION\n"; exit; }
472
 
473
# Get configuration file into $config
474
my $config = &loadConfig( $CONFIGFILE );
136 rodolico 475
print Dumper( $config ) if $DEBUG > 1; die if $DEBUG > 4;
133 rodolico 476
 
136 rodolico 477
# load the savefile, if it exists
478
my $saveFile = { 'macList' => {}, 'switchInfo' => {} };
479
# read the saved state into memory if it exists
480
if ( -e $STATEFILE ) {
481
   my $yaml = YAML::Tiny->read( $STATEFILE );
482
   $saveFile = \%{ $yaml->[0] };
483
}
134 rodolico 484
 
133 rodolico 485
 
138 rodolico 486
my $dnsResource = 0;
139 rodolico 487
eval "use Net::DNS;"; # dns lookup, apt install libnet-dns-perl
488
if ( $@ ) {
489
   $dnsResource = 0;
490
} else {
138 rodolico 491
   $dnsResource = [];
492
   # set up one dns resource for every router we have
493
   # too many failures when trying to define both of them at the same time
494
   foreach my $router ( keys %{ $config->{'routers'} } ) {
495
      push @$dnsResource, Net::DNS::Resolver->new(
496
       'nameservers' => [ $router ],
497
       'recurse' => 0
498
       );
499
   }
500
};
501
 
136 rodolico 502
my $refresh = 1; # determines if we get extra information like switch info, port aliases, etc...
503
if ( defined( $config->{'refresh'} ) ) {
504
   # get the number of seconds between refreshes
505
   $refresh = &calcAge( $config->{'refresh'} );
506
   # if we have not recorded a refresh, set the refresh time to run now
507
   $saveFile->{'lastrefresh'} = time - &calcAge( $config->{'refresh'} ) - 1 
508
      unless defined $saveFile->{'lastrefresh'};
509
   $refresh = $saveFile->{'lastrefresh'} + &calcAge( $config->{'refresh'} ) < time || $forceRefres;
510
   $saveFile->{'lastrefresh'} = time if $refresh;
511
}
512
 
513
print STDERR "Doing a full refresh\n" if $refresh && $DEBUG > 1;
514
 
515
 
516
 
133 rodolico 517
# load the information for the switches into $switchInfo.
518
foreach my $switch ( keys %{$config->{'switches'}} ) {
519
   last if $nosnmp; # do not read switches if $nosnmp set
136 rodolico 520
   my $ignoreList = { map { $_ => 1 } @{ $config->{'switches'}->{$switch}->{'portsToIgnore'} } }; # hash of ports to ignore
521
   #my $ignoreList = \%ignoreList;
133 rodolico 522
   print "ignoreList for $switch\n" . Dumper ($ignoreList) if $DEBUG > 2;
523
   # just get basic switch information, inlcuding a list of all ports which are active and not in portsToIgnore
136 rodolico 524
   $saveFile->{'switchInfo'}->{$switch} = &getSwitchInfo( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList ) if $refresh;
133 rodolico 525
   # get all the MAC's on this switch
136 rodolico 526
   &getSwitchPortMacs( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList, $saveFile->{'macList'} );
133 rodolico 527
}
528
 
136 rodolico 529
 
133 rodolico 530
my $routerARP = {};
531
# Read the ARP table from the router(s)
532
foreach my $router ( keys %{$config->{'routers'}} ) {
136 rodolico 533
   #last if $nosnmp; # do not read routers if $nosnmp set
534
   &getRouterInfo( $router,  $config->{'routers'}->{$router}->{'community'}, $routerARP ) if $refresh;
133 rodolico 535
}
536
print "Routers\n" . Dumper ($routerARP ) if $DEBUG > 2;
136 rodolico 537
# add in anything we have defined in files or in staticmaps in the config file
538
&loadNonRouterEntries( $scriptDir, $config->{'nonrouter'}, $config->{'staticmaps'}, $routerARP );
539
print "Routers after loadNonRouterEntries\n" . Dumper ($routerARP ) if $DEBUG > 2;
540
# populate the mac list with information from $routerARP
541
&getIPAddresses( $saveFile->{'macList'}, $routerARP );
542
print "Routers after getIPAddresses\n" . Dumper ($routerARP ) if $DEBUG > 2;
543
# get the DNS names
544
&getDNSNames( $saveFile->{'macList'}, $dnsResource, $routerARP ) if $refresh;
545
print "Routers after getDNSNames\n" . Dumper ($routerARP ) if $DEBUG > 2;
546
# clean up any old entries
547
&cleanUpOldEntries( $config->{'ttl'}, $saveFile ) if $config->{'ttl'} && $refresh;
133 rodolico 548
# save the file
549
my $yaml = YAML::Tiny->new( $saveFile );
550
$yaml->write( $STATEFILE );
551
 
552
 
553
1;
554