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