Subversion Repositories sysadmin_scripts

Rev

Rev 133 | Rev 136 | 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
#
64
# 20230327 RWR v3.0.0
65
# rewrite to make things more efficient, and store data in different format. You MUST remove old yaml file
66
# before running this.
67
 
68
use strict;
69
use warnings;
70
use Data::Dumper; # only used for debugging
71
use Socket; # for reverse dns entries
72
use YAML::Tiny; # apt-get libyaml-tiny-perl under debian
73
use File::Spec; # find location of script so we can put storage in same directory
74
use File::Basename;
75
 
76
my $DEBUG = 0;
77
 
78
# define the version number
79
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
80
use version;
81
our $VERSION = version->declare("v3.3.0");
82
 
83
# see https://perldoc.perl.org/Getopt/Long.html
84
use Getopt::Long;
85
# allow -vvn (ie, --verbose --verbose --dryrun)
86
Getopt::Long::Configure ("bundling");
87
 
88
 
89
 
90
my %config; # we read the configuration file into this
91
 
92
# where the script is located
93
my $scriptDir = dirname( File::Spec->rel2abs( __FILE__ ) );
94
# put the statefile in there
95
my $STATEFILE = $scriptDir . '/mapSwitches.yaml';
96
my $CONFIGFILE = $scriptDir . '/mapSwitches.config.yaml';
97
 
98
my $SWITCHPORTMIB  = 'iso.3.6.1.2.1.2.2.1.8'; # returns port number and state, with a state of '1' meaning operational
99
my $SWITCHMACMIB   = 'iso.3.6.1.2.1.17.4.3.1.1'; # dot1dTpFdbAddress, aka mac addresses
100
my $SWITCHIFALIASMIB = 'iso.3.6.1.2.1.31.1.1.1.18'; # ifAlias, the the 'alias' field
101
my $SWITCHIFDESCMIB = 'iso.3.6.1.2.1.2.2.1.2'; # ifDescr, the "description" field
102
my $BRIDGEPORTSMIB = 'iso.3.6.1.2.1.17.4.3.1.2';
103
my $BRIDGE2PORTMIB = 'iso.3.6.1.2.1.17.1.4.1.2';
104
# this is only for the router, to get IP of the device in question
105
my $ROUTERIPMACMIB = 'iso.3.6.1.2.1.4.22.1.2'; # ipNetToMediaPhysAddress #'iso.3.6.1.2.1.3.1.1.2';
106
# this should work for all devices
107
my $DEVICENAMEMIB  = 'iso.3.6.1.2.1.1.5'; # sysname
108
my $DEVICELOCMIB   = 'iso.3.6.1.2.1.1.6'; # syslocation
109
 
110
# snmp returns a dotted integer for the mac, but we want mac's as hex with no formatting
111
# take a dotted integer form of a mac and converts it to hex, all lower case
112
sub makeMAC {
113
   my $string = shift;
114
   my @octets = split( '\.', $string );
115
   for ( my $i = 0; $i < @octets; $i++ ) {
116
      $octets[$i] = sprintf( "%02x", $octets[$i] );
117
   }
118
   return join( '', @octets );
119
}
120
 
121
# mac's from various places can have formatting, like ##:##:##:##:## or ###-###-###
122
# this will clean all that up by removing anything except hex values
123
# it will also convert alpha's (a-f) to lower case.
124
sub cleanMac {
125
   my $mac = shift;
126
   $mac =~ s/[^a-f0-9]//gi;
127
   return lc $mac;
128
}
129
 
130
# grabs one single SNMP value from string. Assumes $OID returns only one line, then runs $regex against it.
131
sub getOneSNMPValue {
132
   my ( $oid, $community, $ip, $regex ) = @_;
133
   my $line = `snmpwalk -v1 -c $community $ip $oid`;
134
   $line =~ m/$regex/i;
135
   return $1;
136
}
137
 
138
# runs an snmpwalk using $MIB, then for each line, splits it with a regex
139
# if order is set to 12, first value of regex is a key, else second value is the key
140
sub parseSNMPQuery {
141
   my ( $MIB, $ip, $community, $regex, $order ) = @_;
142
   $order = 12 unless $order;
143
   my $return = {};
144
   my $values = `snmpwalk -v1 -c $community $ip $MIB`;
145
   print "\t\t\tsnmpwalk -v1 -c $community $ip $MIB\n" if $DEBUG > 1;
146
   foreach my $line ( split( "\n", $values ) ) {
147
      next unless $line =~ m/$regex/;
148
      if ( $order == 12 ) {
149
         $return->{$1} = $2;
150
      } else {
151
         $return->{$2} = $1;
152
      }
153
   }
154
   return $return;
155
}
156
 
157
 
158
 
159
# Load configuration file, die if we could not find it
160
# config file is a single page YAML file
161
sub loadConfig {
162
   my $filename = shift;
163
   my %config;
164
   if ( -e $filename ) {
165
      my $yaml = YAML::Tiny->read( $filename );
166
      %config = %{ $yaml->[0] };
167
   } else {
168
      die "could not locate config file $filename\n";
169
   }
170
   return \%config;
171
}
172
 
173
# simple display if --help is passed
174
sub help {
175
   use File::Basename;
176
   print basename($0) . " $VERSION\n";
177
   print <<END
178
$0 [options]
179
Options:
180
   --no-snmp        - do not actually run snmp commands
181
   --debug          - set debug level
182
   --version        - display version and exit
183
   --help           - This page
184
END
185
}
186
 
187
# get information about one single switch
188
#
189
sub getSwitchInfo {
190
   my ( $ip, $community, $ignorePorts, $switchInfo ) = @_;
191
   print "Working on $ip with community $community\n" if $DEBUG;
192
   $switchInfo->{$ip}->{'name'} = # get actual device name
193
      &getOneSNMPValue( $DEVICENAMEMIB,
194
                        $community,
195
                        $ip, 
196
                        qr/= STRING: "?([^"]*)"?/);
197
 
198
   $switchInfo->{$ip}->{'location'} = # and its snmp location
199
      &getOneSNMPValue( 
200
         $DEVICELOCMIB,
201
         $community,
202
         $ip, 
203
         qr/= STRING: "?([^"]*)"?/ );
204
 
205
   # get list of ports into hash with state as the value, '1' is operational
206
   my $ports = &parseSNMPQuery( $SWITCHPORTMIB, $ip, $community, qr/$SWITCHPORTMIB\.(\d+)\s=\sINTEGER:\s+(\d+)/ );
207
   print "=========Ports Hash\n" . Dumper( $ports ) . "\n" if $DEBUG == 4;
208
   foreach my $port ( keys %$ports ) {
209
      next unless $ports->{$port} == 1; # skip any non functional
210
      next if $ignorePorts->{ $port };
211
      # Get information about the ports. This may be possible to skip except on rare occassions?
212
      # get port aliases, set to port number if undef
213
      $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} = 
214
         &getOneSNMPValue( 
215
            "$SWITCHIFALIASMIB.$port", 
216
            $community, 
217
            $ip, 
218
            qr/\.\d+\s+=\s+STRING:\s+"?([^"]*)"?$/ );
219
      $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} = $port unless defined ( $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} );
220
 
221
      # get the port Description, set to port number if undef
222
      $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} = 
223
         &getOneSNMPValue( 
224
            "$SWITCHIFDESCMIB.$port", 
225
            $community, 
226
            $ip, 
227
            qr/\.\d+ = STRING: "?([^\"]*)"?$/ );
228
      $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} = $port unless defined ( $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} );
229
   }
230
}
231
 
232
# get all MAC addresses on switch and associate them with the correct port numbers
233
# https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/44800-mactoport44800.html
234
sub getSwitchPortMacs {
235
   my ( $ip, $community, $ignoreList, $macList ) = @_;
236
   print "\tFinding Mac Addresses\n" if $DEBUG > 1;
237
   # get the MAC addresses into a list
238
   my $macs = &parseSNMPQuery( $SWITCHMACMIB, $ip, $community, qr/$SWITCHMACMIB\.([0-9.]+)\s=\sHex-STRING:\s+([0-9a-z ]+)$/i );
239
   print "Macs\n" . Dumper( $macs ) if $DEBUG >= 3;
240
   # find which bridges they are on
241
   print "\t\tFinding what bridges the MAC's are on\n" if $DEBUG > 2;
242
   my $macBridges = &parseSNMPQuery( $BRIDGEPORTSMIB, $ip, $community, qr/$BRIDGEPORTSMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
243
   print "MacBridges\n" . Dumper( $macBridges ) if $DEBUG >= 3;
244
   print "\t\tFinding what ports the ports are\n" if $DEBUG > 2;
245
   my $bridgeToPort = &parseSNMPQuery( $BRIDGE2PORTMIB, $ip, $community, qr/$BRIDGE2PORTMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
246
   print "BridgeToPort\n" . Dumper( $bridgeToPort ) if $DEBUG > 3;
247
   # now, merge the three together to figure out what port a particular mac is on
248
   foreach my $mac ( keys %$macs ) {
249
      print "\t\t\t$mac\n" if $DEBUG > 3;
250
      next unless defined ( $macBridges->{$mac} ) and defined ($bridgeToPort->{$macBridges->{$mac}} );
251
      my $port = $bridgeToPort->{$macBridges->{$mac}};
252
      next if $ignoreList->{$port};
253
      $macList->{&makeMAC($mac)}->{'switch'} = $ip;
254
      $macList->{&makeMAC($mac)}->{'port'} = $port;
255
      $macList->{&makeMAC($mac)}->{'originalMAC'} = $mac;
256
      $macList->{&makeMAC($mac)}->{'lastseen'} = time();
257
   }
258
}
259
 
260
# get IP address from router(s), and hostname from rdns
261
sub getRouterInfo {
262
   my ( $ip, $community, $routerInfo ) = @_;
263
   print "Working on $ip\n" if $DEBUG;
264
   print "snmpwalk -v1 -c $community $ip $ROUTERIPMACMIB\n" if $DEBUG > 1;
265
   my $values = `snmpwalk -v1 -c $community $ip $ROUTERIPMACMIB`;
266
   my @lines = split( "\n", $values );
267
   foreach my $line ( @lines ) {
268
      $line =~ m/$ROUTERIPMACMIB\.([0-9]+)\.([0-9.]+)\s=\sHex-STRING:\s([0-9a-z ]+)/i;
269
      my $interface = $1;
270
      my $ip = $2;
271
      my $mac = &cleanMac( $3 );
272
      $routerInfo->{$mac}->{'ip'} = $ip;
273
      $routerInfo->{$mac}->{'interface'} = $interface;
274
      $routerInfo->{$mac}->{'hostname'} = gethostbyaddr( inet_aton( $ip ), AF_INET );
275
   }
276
}
277
 
278
# load tab delimited values from $filename into hashref $nonRouterEntries
279
# format is
280
# macaddress
281
#     'ip' = IP Address
282
#     'mac' = MAC Address
283
#     'hostname' = HostName
284
 
285
sub loadNonRouterEntries {
286
   my ( $nonRouterEntries, $filename ) = @_;
287
   print "In loadNonRouterEntries with $filename\n" if $DEBUG > 1;
288
   open FN,"<$filename" or die "Could not open $filename: $!\n";
289
   my $line = <FN>;
290
   chomp $line;
291
   my @headers = split( "\t", $line );
292
   my $macIndex = 0;
293
   while ( $headers[$macIndex] !~ 'mac' && $macIndex < @headers ) {
294
      $macIndex++;
295
   }
296
   if ( $macIndex >= @headers ) {
297
      warn "File $filename does not appear to contain a mac column\n";
298
      return;
299
   }
300
   while ( $line = <FN> ) {
301
      next if $line =~ m/^#/;
302
      chomp $line;
303
      my @values = split( "\t", $line );
304
      for( my $i = 0; $i < @headers; $i++ ) {
305
         $nonRouterEntries->{&cleanMac($values[$macIndex])}->{$headers[$i]} = lc $values[$i];
306
      }
307
   }
308
   close FN;
309
}
310
 
311
# merge nonRouterEntries into $routerARP, with $routerARP having precedence
312
sub updateRouterWithStatic {
313
   my ( $routerARP, $nonRouterEntries ) = @_;
314
   foreach my $mac ( keys %$nonRouterEntries ) {
315
      # assign the hostname from staticmaps if there is one, and either override is true, or routerARP doesn't have one
316
      $routerARP->{$mac}->{'hostname'} = $nonRouterEntries->{$mac}->{'hostname'}
317
         if ( $nonRouterEntries->{$mac}->{'hostname'} 
318
               && ( 
319
                  ! $routerARP->{$mac}->{'hostname'} 
320
                  || $nonRouterEntries->{$mac}->{'override'} 
321
                  )
322
               );
323
      # assign the hostname from staticmaps if there is one, and either override is true, or routerARP doesn't have one
324
      $routerARP->{$mac}->{'ip'} = $nonRouterEntries->{$mac}->{'ip'}
325
         if ( $nonRouterEntries->{$mac}->{'ip'} 
326
               && ( 
327
                  ! $routerARP->{$mac}->{'ip'} 
328
                  || $nonRouterEntries->{$mac}->{'override'} 
329
                  )
330
               );
331
   }
332
}
333
 
334
 
335
################################################################################
336
#              Main
337
################################################################################
338
 
339
# handle any command line parameters that may have been passed in
340
my $version = 0; # just used to determine if we should display the version
341
my $help = 0; # also if we want help
342
my $nosnmp = 0; # we do NOT want to run snmp commands
343
GetOptions (
344
            'debug|d=i'     => \$DEBUG,
345
            'nosnmp|n'      => \$nosnmp,
346
            'help|h'        => \$help,
347
            'version|v'     => \$version,
348
            ) or die "Error parsing command line\n";
349
 
350
 
351
if ( $help ) { &help() ; exit; }
352
if ( $version ) { use File::Basename; print basename($0) . " $VERSION\n"; exit; }
353
 
354
# Get configuration file into $config
355
my $config = &loadConfig( $CONFIGFILE );
356
print Dumper( $config ) if $DEBUG > 1;
357
 
134 rodolico 358
die if $DEBUG > 4;
359
 
133 rodolico 360
my $switchInfo = {}; # stores information about switches
361
my $macList = {}; # a list of all MAC addresses
362
 
363
# load the information for the switches into $switchInfo.
364
foreach my $switch ( keys %{$config->{'switches'}} ) {
365
   last if $nosnmp; # do not read switches if $nosnmp set
366
   my %ignoreList = map { $_ => 1 } @{ $config->{'switches'}->{$switch}->{'portsToIgnore'} }; # hash of ports to ignore
367
   my $ignoreList = \%ignoreList;
368
   print "ignoreList for $switch\n" . Dumper ($ignoreList) if $DEBUG > 2;
369
   # just get basic switch information, inlcuding a list of all ports which are active and not in portsToIgnore
370
   &getSwitchInfo( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList, $switchInfo );
371
   # get all the MAC's on this switch
372
   &getSwitchPortMacs( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList, $macList );
373
}
374
print "switchInfo\n" . Dumper( $switchInfo ) if $DEBUG > 2;
375
print "macList\n" . Dumper( $macList ) if $DEBUG > 2;
376
 
377
my $routerARP = {};
378
# Read the ARP table from the router(s)
379
foreach my $router ( keys %{$config->{'routers'}} ) {
380
   last if $nosnmp; # do not read routers if $nosnmp set
381
   &getRouterInfo( $router,  $config->{'routers'}->{$router}->{'community'}, $routerARP );
382
}
383
print "Routers\n" . Dumper ($routerARP ) if $DEBUG > 2;
384
 
385
# load non-router entries, if they exist
386
my $nonRouterEntries = {};
387
if ( defined ( $config->{'nonrouter'} ) ) {
388
   foreach my $filename ( @{$config->{'nonrouter'}} ) {
389
      &loadNonRouterEntries( $nonRouterEntries, $scriptDir . '/' . $filename );
390
   }
391
}
392
 
393
print "Non-Router Entries\n" . Dumper ( $nonRouterEntries ) if $DEBUG > 2;
394
 
395
# add in any staticmaps we may have. Note it will overwrite anything from files above
396
foreach my $mac ( keys %{$config->{'staticmaps'} } ) {
397
   $nonRouterEntries->{$mac}->{'hostname'} = $config->{'staticmaps'}->{$mac}->{'hostname'} if $config->{'staticmaps'}->{$mac}->{'hostname'};
398
   $nonRouterEntries->{$mac}->{'ip'} = $config->{'staticmaps'}->{$mac}->{'ip'} if $config->{'staticmaps'}->{$mac}->{'ip'};
399
   $nonRouterEntries->{$mac}->{'override'} = $config->{'staticmaps'}->{$mac}->{'override'} if $config->{'staticmaps'}->{$mac}->{'override'};
400
}
401
 
402
&updateRouterWithStatic( $routerARP, $nonRouterEntries );
403
 
404
print "routerInfo\n" . Dumper ( $routerARP ) if $DEBUG > 2;
405
 
406
#print Dumper( $macList ); die;
407
 
408
my $saveFile = {};
409
# read the saved state into memory if it exists
410
if ( -e $STATEFILE ) {
411
   my $yaml = YAML::Tiny->read( $STATEFILE );
412
   $saveFile = \%{ $yaml->[0] };
413
}
414
 
415
$saveFile->{'switchInfo'} = $switchInfo;
416
 
417
foreach my $mac ( keys %$macList ) {
418
   $saveFile->{'macList'}->{$mac} = $macList->{$mac};
419
   $saveFile->{'macList'}->{$mac}->{'hostname'} = $routerARP->{$mac}->{'hostname'};
420
   $saveFile->{'macList'}->{$mac}->{'ip'} = $routerARP->{$mac}->{'ip'};
421
}
422
 
423
#print Dumper( $saveFile ); die;
424
 
425
#print Dumper( $switchInfo); die;
426
 
427
# save the file
428
my $yaml = YAML::Tiny->new( $saveFile );
429
$yaml->write( $STATEFILE );
430
 
431
 
432
1;
433