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
}
192
 
66 rodolico 193
# simple display if --help is passed
194
sub help {
195
   use File::Basename;
196
   print basename($0) . " $VERSION\n";
197
   print <<END
198
$0 [options]
199
Options:
200
   --debug          - set debug level
201
   --version        - display version and exit
202
   --help           - This page
203
END
204
}
25 rodolico 205
 
66 rodolico 206
 
207
# handle any command line parameters that may have been passed in
208
my $version = 0; # just used to determine if we should display the version
209
my $help = 0; # also if we want help
210
GetOptions (
211
            'debug|d=i'     => \$DEBUG,
212
            'help|h'        => \$help,
213
            'version|v'     => \$version,
214
            ) or die "Error parsing command line\n";
215
 
216
 
217
if ( $help ) { &help() ; exit; }
218
if ( $version ) { use File::Basename; print basename($0) . " $VERSION\n"; exit; }
219
 
220
# Load configuration file, die if we could not find it
5 rodolico 221
if ( -e $CONFIGFILE ) {
222
   my $yaml = YAML::Tiny->read( $CONFIGFILE );
223
   %config = %{ $yaml->[0] };
224
} else {
225
   die "could not locate config file $CONFIGFILE\n";
226
}
227
 
2 rodolico 228
# read the saved state into memory if it exists
229
if ( -e $STATEFILE ) {
230
   my $yaml = YAML::Tiny->read( $STATEFILE );
231
   %switchports = %{ $yaml->[0] };
232
}
233
 
234
# first, get all of the MAC/Port assignments from the switches
5 rodolico 235
foreach my $switch ( keys %{$config{'switches'}} ) {
63 rodolico 236
   print "Working on $switch\n" if $DEBUG;
2 rodolico 237
   &initialize( \%switchports, $switch, 'name','location' );
238
   &updateValue(
239
      \$switchports{$switch}{'name'},
66 rodolico 240
      &getOneSNMPValue( $DEVICENAMEMIB,$config{'switches'}{$switch}{'community'},$switch, qr/= STRING: "?([^"]*)"?/ )
2 rodolico 241
      );
242
 
243
   &updateValue(
244
      \$switchports{$switch}{'location'},
66 rodolico 245
      &getOneSNMPValue( $DEVICELOCMIB,$config{'switches'}{$switch}{'community'},$switch, qr/= STRING: "?([^"]*)"?/ )
2 rodolico 246
      );
66 rodolico 247
 
248
   # get list of all active ports not in our ignore list
249
   print "\tGetting Ports\n" if $DEBUG > 1;
67 rodolico 250
   my $ports = parseSNMPQuery( \%config, $switch, $SWITCHPORTMIB, qr/$SWITCHPORTMIB\.(\d+)\s=\sINTEGER:\s+(\d+)/ );
66 rodolico 251
   #die Dumper( $ports );
252
   print "\tGetting Aliases\n" if $DEBUG > 1;
67 rodolico 253
   my $aliases = parseSNMPQuery( \%config, $switch, $SWITCHIFALIASMIB, qr/\.(\d+) = STRING: "?([^"]*)"?$/ );
66 rodolico 254
   #die Dumper( $aliases );
255
   print "\tGetting Descriptions\n" if $DEBUG > 1;
256
   my $descriptions = parseSNMPQuery( \%config, $switch, $SWITCHIFDESCMIB, qr/\.(\d+) = STRING: "?([^\"]*)"?$/ );
257
   #die Dumper( $descriptions );
25 rodolico 258
 
66 rodolico 259
   foreach my $port ( keys %$ports ) {
260
      if ( $ports->{$port} == 1 ) { # only work with ports that are active
68 rodolico 261
         print "\t\tGetting alias and description for port $port\n" if $DEBUG > 3;
66 rodolico 262
         $switchports{$switch}{'ports'}{$port}{'alias'} = $aliases->{$port} ? $aliases->{$port} : '';
263
         $switchports{$switch}{'ports'}{$port}{'description'} = $descriptions->{$port} ? $descriptions->{$port} : '';
264
      }
2 rodolico 265
   }
68 rodolico 266
   #die Dumper( \%switchports );
66 rodolico 267
 
268
   # now, get the MAC addresses. See https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/44800-mactoport44800.html
269
   print "\tFinding Mac Addresses\n" if $DEBUG > 1;
270
   my $macs = parseSNMPQuery( \%config, $switch, $SWITCHMACMIB, qr/$SWITCHMACMIB\.([0-9.]+)\s=\sHex-STRING:\s+([0-9a-z ]+)$/i );
271
   #die Dumper( $macs );
272
   # find which bridges they are on
273
   print "\t\tFinding what bridges the MAC's are on\n" if $DEBUG > 2;
274
   my $macBridges = parseSNMPQuery( \%config, $switch, $BRIDGEPORTSMIB, qr/$BRIDGEPORTSMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
275
   #die Dumper( $macBridges );
276
   print "\t\tFinding what ports the ports are\n" if $DEBUG > 2;
277
   my $bridgeToPort = parseSNMPQuery( \%config, $switch, $BRIDGE2PORTMIB, qr/$BRIDGE2PORTMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
278
   #die Dumper( $bridgeToPort );
279
   foreach my $mac ( keys %$macs ) {
67 rodolico 280
      print "\t\t\t$mac\n" if $DEBUG > 2;
281
      next unless defined ( $macBridges->{$mac} ) and defined ($bridgeToPort->{$macBridges->{$mac}} );
68 rodolico 282
      $switchports{$switch}{'ports'}{$bridgeToPort->{$macBridges->{$mac}}}{$mac}{'mac'} = &makeMAC($mac) if defined( $switchports{$switch}{'ports'} );
66 rodolico 283
   }
68 rodolico 284
 
285
   # remove the ports we want to ignore
286
   print "\t\tDeleting ignored ports [" . join(',',@{$config{'switches'}{$switch}{'portsToIgnore'}} ) . "]\n" if $DEBUG > 1;
287
   foreach my $ignore ( @{$config{'switches'}{$switch}{'portsToIgnore'}} ) {
288
#      print join( ',', sort {$a<=>$b} keys %{$ports} ) . "\n";
289
      delete $switchports{$switch}{'ports'}{$ignore};
290
   }
291
#   print join( ',', sort {$a<=>$b} keys %{$ports} ) . "\n";
292
#   die;
293
 
294
 
2 rodolico 295
}
296
 
68 rodolico 297
#print Dumper( \%switchports ); die;
2 rodolico 298
 
299
 
300
# Now, try to match up the MAC address. Read the ARP table from the router(s)
5 rodolico 301
foreach my $router ( keys %{$config{'routers'}} ) {
66 rodolico 302
   print "Working on $router\n" if $DEBUG;
69 rodolico 303
   print "snmpwalk -v1 -c $config{routers}{$router}{community} $router $ROUTERIPMACMIB\n" if $DEBUG > 1;
5 rodolico 304
   my $values = `snmpwalk -v1 -c $config{routers}{$router}{community} $router $ROUTERIPMACMIB`;
2 rodolico 305
   my @lines = split( "\n", $values );
306
   foreach my $line ( @lines ) {
307
      $line =~ m/$ROUTERIPMACMIB\.([0-9]+)\.([0-9.]+)\s=\sHex-STRING:\s([0-9a-z ]+)/i;
308
      my $interface = $1;
309
      my $ip = $2;
310
      my $mac = lc $3;
311
      $mac =~ s/ //g;
312
      &updateIP( \%switchports, $ip, $mac );
313
   }
314
}
315
 
69 rodolico 316
# now, process any static maps we might have
317
if ( defined( $config{'staticmaps'} ) ) {
318
   # let's make sure there is an entry for each one
319
   foreach my $entry ( keys %{$config{'staticmaps'}} ) {
320
      &initialize( \%{$config{'staticmaps'}}, $entry, 'ip','hostname','override' );
321
   }
322
   # this seems counter productive to make a pass through the whole switchport hash when there may only be one staticmap
323
   # but this way, we only make one pass whereas if we were to go through each static map, we would make one pass for
324
   # each mapping.
325
   foreach my $switch ( keys %switchports ) {
326
      foreach my $portnum (keys %{ $switchports{$switch}{'ports'} } ) {
327
         foreach my $connection ( keys %{ $switchports{$switch}{'ports'}{$portnum} } ) {
328
            next if $connection eq 'description' or $connection eq 'alias';
329
            my $mac = $switchports{$switch}{'ports'}{$portnum}{$connection}{'mac'};
330
            if ( defined ( $config{'staticmaps'}{$mac} ) ) {
331
               if ( $config{'staticmaps'}{$mac}{'ip'} && ( $config{'staticmaps'}{$mac}{'override'} || ! $switchports{$switch}{'ports'}{$portnum}{$connection}{'ip'} ) ) {
332
                  $switchports{$switch}{'ports'}{$portnum}{$connection}{'ip'} = $config{'staticmaps'}{$mac}{'ip'};
333
               }
334
               if ( $config{'staticmaps'}{$mac}{'hostname'} && ( $config{'staticmaps'}{$mac}{'override'} || ! $switchports{$switch}{'ports'}{$portnum}{$connection}{'hostname'} ) ) {
335
                  $switchports{$switch}{'ports'}{$portnum}{$connection}{'hostname'} = $config{'staticmaps'}{$mac}{'hostname'};
336
               }
337
            } # if there is an entry
338
         } # checking each connection
339
      } # checking each port number
340
   } # checking each switch
341
} # if defined
342
 
2 rodolico 343
#die Dumper( \%switchports );
344
 
345
# save the state file for later, so we can find things which disappear from the network
346
my $yaml = YAML::Tiny->new( \%switchports );
347
$yaml->write( $STATEFILE );
348
 
349
#print Dumper( \%switchports );
350
1;
351