Subversion Repositories sysadmin_scripts

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 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"
66 rodolico 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
#
2 rodolico 19
# Data is stored in the hash %switchports with the following structure
20
# %switchports =
5 rodolico 21
#     {switch} (from $config{'switches'} key)
2 rodolico 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)
66 rodolico 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
#
2 rodolico 39
 
5 rodolico 40
# 20190407 RWR
41
# converted to use external config file in YAML format
42
# added the ability to ignore ports on the switches
25 rodolico 43
# 20190514 RWR
44
# Added port aliases
33 rodolico 45
# 20190526 RWR
46
# fixed mapSwitchCSV.pl to output in various delimited format (see README)
66 rodolico 47
# 20200107 RWR v1.3
63 rodolico 48
# Fixed problem where alias MIB was not returning values
66 rodolico 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
67 rodolico 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
68 rodolico 57
# question show up as bridge 0, which has no port (or, actually, all ports). Also, fixed the ignoreports
69 rodolico 58
# 20200302 RWR v2.2.0
59
# Added the ability to override or supplement arp and dns searches for mac addresses
130 rodolico 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
5 rodolico 63
 
2 rodolico 64
use strict;
65
use warnings;
5 rodolico 66
use Data::Dumper; # only used for debugging
2 rodolico 67
use Socket; # for reverse dns entries
68
use YAML::Tiny; # apt-get libyaml-tiny-perl under debian
69
use File::Spec; # find location of script so we can put storage in same directory
70
use File::Basename;
71
 
63 rodolico 72
my $DEBUG = 0;
25 rodolico 73
 
66 rodolico 74
# define the version number
75
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
76
use version;
130 rodolico 77
our $VERSION = version->declare("v2.3.0");
63 rodolico 78
 
66 rodolico 79
# see https://perldoc.perl.org/Getopt/Long.html
80
use Getopt::Long;
81
# allow -vvn (ie, --verbose --verbose --dryrun)
82
Getopt::Long::Configure ("bundling");
2 rodolico 83
 
66 rodolico 84
 
85
 
86
my %config; # we read the configuration file into this
87
 
2 rodolico 88
# where the script is located
89
my $scriptDir = dirname( File::Spec->rel2abs( __FILE__ ) );
90
# put the statefile in there
91
my $STATEFILE = $scriptDir . '/mapSwitches.yaml';
5 rodolico 92
my $CONFIGFILE = $scriptDir . '/mapSwitches.config.yaml';
2 rodolico 93
# main hash that holds the data we collect
94
my %switchports;
95
 
66 rodolico 96
# OID's to read the swtiches
97
# NOTE: for the regular expressions to work, you must use iso. for the OID
98
 
99
#my $SWITCHPORTMIB  = 'iso.3.6.1.2.1.17.4.3.1.2';
100
my $SWITCHPORTMIB  = 'iso.3.6.1.2.1.2.2.1.8';
101
my $SWITCHMACMIB   = 'iso.3.6.1.2.1.17.4.3.1.1'; # dot1dTpFdbAddress, aka mac addresses
102
my $SWITCHIFALIASMIB = 'iso.3.6.1.2.1.31.1.1.1.18'; # ifAlias, the the 'alias' field
103
my $SWITCHIFDESCMIB = 'iso.3.6.1.2.1.2.2.1.2'; # ifDescr, the "description" field
104
my $BRIDGEPORTSMIB = 'iso.3.6.1.2.1.17.4.3.1.2';
105
my $BRIDGE2PORTMIB = 'iso.3.6.1.2.1.17.1.4.1.2';
106
# this is only for the router, to get IP of the device in question
107
my $ROUTERIPMACMIB = 'iso.3.6.1.2.1.4.22.1.2'; # ipNetToMediaPhysAddress #'iso.3.6.1.2.1.3.1.1.2';
108
# this should work for all devices
109
my $DEVICENAMEMIB  = 'iso.3.6.1.2.1.1.5'; # sysname
110
my $DEVICELOCMIB   = 'iso.3.6.1.2.1.1.6'; # syslocation
111
 
112
# take a dotted integer form of a mac and converts it to hex, all lower case
2 rodolico 113
sub makeMAC {
114
   my $string = shift;
115
   my @octets = split( '\.', $string );
116
   for ( my $i = 0; $i < @octets; $i++ ) {
117
      $octets[$i] = sprintf( "%02x", $octets[$i] );
118
   }
119
   return join( '', @octets );
120
}
121
 
129 rodolico 122
sub cleanMac {
123
   my $mac = shift;
124
   $mac =~ s/[^a-f0-9]//gi;
125
   return lc $mac;
126
}
127
 
66 rodolico 128
# simply updates a value. First parameter ($oldValue) is passed by reference so it can be directly accessed
129
# returns 1 on success, 0 on failure
2 rodolico 130
sub updateValue {
131
   my ( $oldValue, $newValue ) = @_;
132
   $newValue = '' unless defined $newValue;
133
   if ( $newValue ) {
134
      $$oldValue = $newValue unless $newValue eq $$oldValue;
135
      return 1;
136
   }
137
   return 0;
138
}
139
 
66 rodolico 140
# grabs one single SNMP value from string. Assumes $OID returns only one line, then runs $regex against it.
2 rodolico 141
sub getOneSNMPValue {
142
   my ( $oid, $community, $ip, $regex ) = @_;
143
   my $line = `snmpwalk -v1 -c $community $ip $oid`;
144
   $line =~ m/$regex/i;
145
   return $1;
146
}
147
 
66 rodolico 148
# ensures a hash has $name with every value in @keys
149
# call with &initialize( \%hash, 'somename', 'key1','key2');
150
# will ensure $hash->{somename}->{key1} and $hash->{somename}->{key2} exist
2 rodolico 151
sub initialize {
152
   my ( $hash, $name, @keys ) = @_;
69 rodolico 153
   print "In initialize, name is $name and hash is\n" . Dumper( $hash ) if $DEBUG > 3;
2 rodolico 154
   foreach my $key ( @keys ) {
155
      $hash->{$name}->{$key} = '' unless $hash->{$name}->{$key};
156
   }
157
}
158
 
66 rodolico 159
# updates the lastseen time on a mac address by searching through $switchports until it finds it. If it doesn't exist, will
160
# add it.
2 rodolico 161
sub updateIP {
162
   my ( $switchports, $ip, $mac ) = @_;
163
   foreach my $switch ( keys %$switchports ) {
164
      my $thisSwitch = $switchports->{$switch}->{'ports'};
165
      foreach my $port ( keys %$thisSwitch ) {
166
         my $thisPort = $thisSwitch->{$port};
167
         foreach my $connection ( keys %$thisPort ) {
25 rodolico 168
            # skip the alias information on a port
66 rodolico 169
            next if $connection eq 'alias' or $connection eq 'description';
2 rodolico 170
            &initialize( $thisPort,$connection,'mac','ip','hostname','lastseen' );
171
            if ( $switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'mac'} eq $mac ) {
172
               my $modified = &updateValue( \$switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'ip'}, $ip );
173
               $modified |= &updateValue( \$switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'hostname'},gethostbyaddr( inet_aton( $ip ), AF_INET ));
131 rodolico 174
               $switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'lastseen'} = time();
2 rodolico 175
               return;
176
            } # if we found it
177
         } # for connection
178
      } # for port
179
   } # for switch
180
} # updateIP
181
 
66 rodolico 182
 
183
# runs an snmpwalk using $MIB, then for each line, splits it with a regex
184
# if order is set to 12, first value of regex is a key, else second value is the key
185
sub parseSNMPQuery {
186
   my ($config, $switch, $MIB, $regex, $order) = @_;
187
   $order = 12 unless $order;
188
   my $return = {};
189
   my $values = `snmpwalk -v1 -c $config{switches}{$switch}{'community'} $switch $MIB`;
67 rodolico 190
   print "\t\t\tsnmpwalk -v1 -c $config{switches}{$switch}{'community'} $switch $MIB\n" if $DEBUG > 1;
66 rodolico 191
   foreach my $line ( split( "\n", $values ) ) {
67 rodolico 192
      next unless $line =~ m/$regex/;
66 rodolico 193
      if ( $order == 12 ) {
194
         $return->{$1} = $2;
195
      } else {
196
         $return->{$2} = $1;
63 rodolico 197
      }
25 rodolico 198
   }
66 rodolico 199
   return $return;
25 rodolico 200
}
128 rodolico 201
 
202
# load tab delimited values from $filename into hashref $nonRouterEntries
203
# format is
204
# macaddress
205
#     'ip' = IP Address
206
#     'mac' = MAC Address
207
#     'hostname' = HostName
208
 
209
sub loadNonRouterEntries {
210
   my ( $nonRouterEntries, $filename ) = @_;
211
   open FN,"<$filename" or die "Could not open $filename: $!\n";
212
   my $line = <FN>;
213
   chomp $line;
214
   my @headers = split( "\t", $line );
215
   my $macIndex = 0;
216
   while ( $headers[$macIndex] !~ 'mac' && $macIndex < @headers ) {
217
      $macIndex++;
218
   }
219
   if ( $macIndex >= @headers ) {
220
      warn "File $filename does not appear to contain a mac column\n";
221
      return;
222
   }
223
   while ( $line = <FN> ) {
224
      next if $line =~ m/^#/;
225
      chomp $line;
226
      my @values = split( "\t", $line );
227
      for( my $i = 0; $i < @headers; $i++ ) {
129 rodolico 228
         $nonRouterEntries->{&cleanMac($values[$macIndex])}->{$headers[$i]} = lc $values[$i];
128 rodolico 229
      }
230
   }
231
   close FN;
232
}
25 rodolico 233
 
128 rodolico 234
 
66 rodolico 235
# simple display if --help is passed
236
sub help {
237
   use File::Basename;
238
   print basename($0) . " $VERSION\n";
239
   print <<END
240
$0 [options]
241
Options:
131 rodolico 242
   --no-snmp        - do not actually run snmp commands
66 rodolico 243
   --debug          - set debug level
244
   --version        - display version and exit
245
   --help           - This page
246
END
247
}
25 rodolico 248
 
66 rodolico 249
 
250
# handle any command line parameters that may have been passed in
251
my $version = 0; # just used to determine if we should display the version
252
my $help = 0; # also if we want help
131 rodolico 253
my $nosnmp = 0; # we do NOT want to run snmp commands
66 rodolico 254
GetOptions (
255
            'debug|d=i'     => \$DEBUG,
131 rodolico 256
            'nosnmp|n'      => \$nosnmp,
66 rodolico 257
            'help|h'        => \$help,
258
            'version|v'     => \$version,
259
            ) or die "Error parsing command line\n";
260
 
261
 
262
if ( $help ) { &help() ; exit; }
263
if ( $version ) { use File::Basename; print basename($0) . " $VERSION\n"; exit; }
264
 
265
# Load configuration file, die if we could not find it
5 rodolico 266
if ( -e $CONFIGFILE ) {
267
   my $yaml = YAML::Tiny->read( $CONFIGFILE );
268
   %config = %{ $yaml->[0] };
269
} else {
270
   die "could not locate config file $CONFIGFILE\n";
271
}
272
 
2 rodolico 273
# read the saved state into memory if it exists
274
if ( -e $STATEFILE ) {
275
   my $yaml = YAML::Tiny->read( $STATEFILE );
276
   %switchports = %{ $yaml->[0] };
277
}
278
 
279
# first, get all of the MAC/Port assignments from the switches
5 rodolico 280
foreach my $switch ( keys %{$config{'switches'}} ) {
131 rodolico 281
   last if $nosnmp; # do not read switches if $nosnmp set
63 rodolico 282
   print "Working on $switch\n" if $DEBUG;
2 rodolico 283
   &initialize( \%switchports, $switch, 'name','location' );
284
   &updateValue(
285
      \$switchports{$switch}{'name'},
66 rodolico 286
      &getOneSNMPValue( $DEVICENAMEMIB,$config{'switches'}{$switch}{'community'},$switch, qr/= STRING: "?([^"]*)"?/ )
2 rodolico 287
      );
288
 
289
   &updateValue(
290
      \$switchports{$switch}{'location'},
66 rodolico 291
      &getOneSNMPValue( $DEVICELOCMIB,$config{'switches'}{$switch}{'community'},$switch, qr/= STRING: "?([^"]*)"?/ )
2 rodolico 292
      );
66 rodolico 293
 
294
   # get list of all active ports not in our ignore list
295
   print "\tGetting Ports\n" if $DEBUG > 1;
67 rodolico 296
   my $ports = parseSNMPQuery( \%config, $switch, $SWITCHPORTMIB, qr/$SWITCHPORTMIB\.(\d+)\s=\sINTEGER:\s+(\d+)/ );
66 rodolico 297
   #die Dumper( $ports );
298
   print "\tGetting Aliases\n" if $DEBUG > 1;
67 rodolico 299
   my $aliases = parseSNMPQuery( \%config, $switch, $SWITCHIFALIASMIB, qr/\.(\d+) = STRING: "?([^"]*)"?$/ );
66 rodolico 300
   #die Dumper( $aliases );
301
   print "\tGetting Descriptions\n" if $DEBUG > 1;
302
   my $descriptions = parseSNMPQuery( \%config, $switch, $SWITCHIFDESCMIB, qr/\.(\d+) = STRING: "?([^\"]*)"?$/ );
303
   #die Dumper( $descriptions );
25 rodolico 304
 
66 rodolico 305
   foreach my $port ( keys %$ports ) {
306
      if ( $ports->{$port} == 1 ) { # only work with ports that are active
68 rodolico 307
         print "\t\tGetting alias and description for port $port\n" if $DEBUG > 3;
66 rodolico 308
         $switchports{$switch}{'ports'}{$port}{'alias'} = $aliases->{$port} ? $aliases->{$port} : '';
309
         $switchports{$switch}{'ports'}{$port}{'description'} = $descriptions->{$port} ? $descriptions->{$port} : '';
310
      }
2 rodolico 311
   }
68 rodolico 312
   #die Dumper( \%switchports );
66 rodolico 313
 
314
   # now, get the MAC addresses. See https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/44800-mactoport44800.html
315
   print "\tFinding Mac Addresses\n" if $DEBUG > 1;
316
   my $macs = parseSNMPQuery( \%config, $switch, $SWITCHMACMIB, qr/$SWITCHMACMIB\.([0-9.]+)\s=\sHex-STRING:\s+([0-9a-z ]+)$/i );
317
   #die Dumper( $macs );
318
   # find which bridges they are on
319
   print "\t\tFinding what bridges the MAC's are on\n" if $DEBUG > 2;
320
   my $macBridges = parseSNMPQuery( \%config, $switch, $BRIDGEPORTSMIB, qr/$BRIDGEPORTSMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
321
   #die Dumper( $macBridges );
322
   print "\t\tFinding what ports the ports are\n" if $DEBUG > 2;
323
   my $bridgeToPort = parseSNMPQuery( \%config, $switch, $BRIDGE2PORTMIB, qr/$BRIDGE2PORTMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
324
   #die Dumper( $bridgeToPort );
325
   foreach my $mac ( keys %$macs ) {
67 rodolico 326
      print "\t\t\t$mac\n" if $DEBUG > 2;
327
      next unless defined ( $macBridges->{$mac} ) and defined ($bridgeToPort->{$macBridges->{$mac}} );
68 rodolico 328
      $switchports{$switch}{'ports'}{$bridgeToPort->{$macBridges->{$mac}}}{$mac}{'mac'} = &makeMAC($mac) if defined( $switchports{$switch}{'ports'} );
66 rodolico 329
   }
68 rodolico 330
 
331
   # remove the ports we want to ignore
332
   print "\t\tDeleting ignored ports [" . join(',',@{$config{'switches'}{$switch}{'portsToIgnore'}} ) . "]\n" if $DEBUG > 1;
333
   foreach my $ignore ( @{$config{'switches'}{$switch}{'portsToIgnore'}} ) {
334
#      print join( ',', sort {$a<=>$b} keys %{$ports} ) . "\n";
335
      delete $switchports{$switch}{'ports'}{$ignore};
336
   }
337
#   print join( ',', sort {$a<=>$b} keys %{$ports} ) . "\n";
338
#   die;
339
 
340
 
2 rodolico 341
}
342
 
68 rodolico 343
#print Dumper( \%switchports ); die;
2 rodolico 344
 
345
 
346
# Now, try to match up the MAC address. Read the ARP table from the router(s)
5 rodolico 347
foreach my $router ( keys %{$config{'routers'}} ) {
131 rodolico 348
   last if $nosnmp; # do not read routers if $nosnmp set
66 rodolico 349
   print "Working on $router\n" if $DEBUG;
69 rodolico 350
   print "snmpwalk -v1 -c $config{routers}{$router}{community} $router $ROUTERIPMACMIB\n" if $DEBUG > 1;
5 rodolico 351
   my $values = `snmpwalk -v1 -c $config{routers}{$router}{community} $router $ROUTERIPMACMIB`;
2 rodolico 352
   my @lines = split( "\n", $values );
353
   foreach my $line ( @lines ) {
354
      $line =~ m/$ROUTERIPMACMIB\.([0-9]+)\.([0-9.]+)\s=\sHex-STRING:\s([0-9a-z ]+)/i;
355
      my $interface = $1;
356
      my $ip = $2;
131 rodolico 357
      my $mac = &cleanMac( $3 );
129 rodolico 358
      #$mac =~ s/ //g;
2 rodolico 359
      &updateIP( \%switchports, $ip, $mac );
360
   }
361
}
362
 
128 rodolico 363
# load non-router entries, if they exist
364
my $nonRouterEntries = {};;
365
if ( defined ( $config{'nonrouter'} ) ) {
366
   foreach my $filename ( @{$config{'nonrouter'}} ) {
367
      &loadNonRouterEntries( $nonRouterEntries, $scriptDir . '/' . $filename );
368
   }
369
}
370
 
130 rodolico 371
#print Dumper( $nonRouterEntries ) . "\n"; die;
128 rodolico 372
 
373
# now, process any static maps we might have and, failing that, any non-router entries
69 rodolico 374
if ( defined( $config{'staticmaps'} ) ) {
375
   # let's make sure there is an entry for each one
376
   foreach my $entry ( keys %{$config{'staticmaps'}} ) {
377
      &initialize( \%{$config{'staticmaps'}}, $entry, 'ip','hostname','override' );
378
   }
379
} # if defined
128 rodolico 380
 
130 rodolico 381
#print Dumper( $config{'staticmaps'} );
128 rodolico 382
 
130 rodolico 383
# Go through entire switch array and see if we can figure out any empty hostnames and/or IP addresses from
384
# either the staticmaps or the nonRouterEntries
385
foreach my $switch ( keys %switchports ) {
386
   foreach my $portnum (keys %{ $switchports{$switch}{'ports'} } ) {
387
      foreach my $connection ( keys %{ $switchports{$switch}{'ports'}{$portnum} } ) {
388
         next if $connection eq 'description' or $connection eq 'alias';
389
         my $mac = $switchports{$switch}{'ports'}{$portnum}{$connection}{'mac'};
390
         # we already have a hostname and IP, so skip to next one
391
         # print "Looking up $switch, port $portnum with mac address $mac\n";
131 rodolico 392
         unless ( $switchports{$switch}{'ports'}{$portnum}{$connection}{'hostname'} ) {
393
            if ( defined( $config{'staticmaps'}{$mac}{'ip'} ) && $config{'staticmaps'}{$mac}{'hostname'} ) {
394
               $switchports{$switch}{'ports'}{$portnum}{$connection}{'hostname'} =  $config{'staticmaps'}{$mac}{'hostname'};
395
            } elsif ( defined( $nonRouterEntries->{$mac}->{'hostname'} ) && $nonRouterEntries->{$mac}->{'hostname'} ) {
396
               $switchports{$switch}{'ports'}{$portnum}{$connection}{'hostname'} =  $nonRouterEntries->{$mac}->{'hostname'};
130 rodolico 397
            }
131 rodolico 398
         }
399
         unless ( $switchports{$switch}{'ports'}{$portnum}{$connection}{'ip'} ) {
400
            if ( defined( $config{'staticmaps'}{$mac}{'ip'} ) && $config{'staticmaps'}{$mac}{'ip'} ) {
401
               $switchports{$switch}{'ports'}{$portnum}{$connection}{'ip'} =  $config{'staticmaps'}{$mac}{'ip'};
402
            } elsif ( defined( $nonRouterEntries->{$mac}->{'ip'} ) && $nonRouterEntries->{$mac}->{'ip'} ) {
403
               $switchports{$switch}{'ports'}{$portnum}{$connection}{'ip'} =  $nonRouterEntries->{$mac}->{'ip'};
130 rodolico 404
            }
131 rodolico 405
         }
130 rodolico 406
      } # checking each connection
407
   } # checking each port number
408
} # checking each switch
128 rodolico 409
 
2 rodolico 410
#die Dumper( \%switchports );
411
 
412
# save the state file for later, so we can find things which disappear from the network
413
my $yaml = YAML::Tiny->new( \%switchports );
414
$yaml->write( $STATEFILE );
415
 
416
#print Dumper( \%switchports );
417
1;
418