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
5 rodolico 55
 
2 rodolico 56
use strict;
57
use warnings;
5 rodolico 58
use Data::Dumper; # only used for debugging
2 rodolico 59
use Socket; # for reverse dns entries
60
use YAML::Tiny; # apt-get libyaml-tiny-perl under debian
61
use File::Spec; # find location of script so we can put storage in same directory
62
use File::Basename;
63
 
63 rodolico 64
my $DEBUG = 0;
25 rodolico 65
 
66 rodolico 66
# define the version number
67
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
68
use version;
69
our $VERSION = version->declare("v2.0.0");
63 rodolico 70
 
66 rodolico 71
# see https://perldoc.perl.org/Getopt/Long.html
72
use Getopt::Long;
73
# allow -vvn (ie, --verbose --verbose --dryrun)
74
Getopt::Long::Configure ("bundling");
2 rodolico 75
 
66 rodolico 76
 
77
 
78
my %config; # we read the configuration file into this
79
 
2 rodolico 80
# where the script is located
81
my $scriptDir = dirname( File::Spec->rel2abs( __FILE__ ) );
82
# put the statefile in there
83
my $STATEFILE = $scriptDir . '/mapSwitches.yaml';
5 rodolico 84
my $CONFIGFILE = $scriptDir . '/mapSwitches.config.yaml';
2 rodolico 85
# main hash that holds the data we collect
86
my %switchports;
87
 
66 rodolico 88
# OID's to read the swtiches
89
# NOTE: for the regular expressions to work, you must use iso. for the OID
90
 
91
#my $SWITCHPORTMIB  = 'iso.3.6.1.2.1.17.4.3.1.2';
92
my $SWITCHPORTMIB  = 'iso.3.6.1.2.1.2.2.1.8';
93
my $SWITCHMACMIB   = 'iso.3.6.1.2.1.17.4.3.1.1'; # dot1dTpFdbAddress, aka mac addresses
94
my $SWITCHIFALIASMIB = 'iso.3.6.1.2.1.31.1.1.1.18'; # ifAlias, the the 'alias' field
95
my $SWITCHIFDESCMIB = 'iso.3.6.1.2.1.2.2.1.2'; # ifDescr, the "description" field
96
my $BRIDGEPORTSMIB = 'iso.3.6.1.2.1.17.4.3.1.2';
97
my $BRIDGE2PORTMIB = 'iso.3.6.1.2.1.17.1.4.1.2';
98
# this is only for the router, to get IP of the device in question
99
my $ROUTERIPMACMIB = 'iso.3.6.1.2.1.4.22.1.2'; # ipNetToMediaPhysAddress #'iso.3.6.1.2.1.3.1.1.2';
100
# this should work for all devices
101
my $DEVICENAMEMIB  = 'iso.3.6.1.2.1.1.5'; # sysname
102
my $DEVICELOCMIB   = 'iso.3.6.1.2.1.1.6'; # syslocation
103
 
104
# take a dotted integer form of a mac and converts it to hex, all lower case
2 rodolico 105
sub makeMAC {
106
   my $string = shift;
107
   my @octets = split( '\.', $string );
108
   for ( my $i = 0; $i < @octets; $i++ ) {
109
      $octets[$i] = sprintf( "%02x", $octets[$i] );
110
   }
111
   return join( '', @octets );
112
}
113
 
66 rodolico 114
# simply updates a value. First parameter ($oldValue) is passed by reference so it can be directly accessed
115
# returns 1 on success, 0 on failure
2 rodolico 116
sub updateValue {
117
   my ( $oldValue, $newValue ) = @_;
118
   $newValue = '' unless defined $newValue;
119
   if ( $newValue ) {
120
      $$oldValue = $newValue unless $newValue eq $$oldValue;
121
      return 1;
122
   }
123
   return 0;
124
}
125
 
66 rodolico 126
# grabs one single SNMP value from string. Assumes $OID returns only one line, then runs $regex against it.
2 rodolico 127
sub getOneSNMPValue {
128
   my ( $oid, $community, $ip, $regex ) = @_;
129
   my $line = `snmpwalk -v1 -c $community $ip $oid`;
130
   $line =~ m/$regex/i;
131
   return $1;
132
}
133
 
66 rodolico 134
# ensures a hash has $name with every value in @keys
135
# call with &initialize( \%hash, 'somename', 'key1','key2');
136
# will ensure $hash->{somename}->{key1} and $hash->{somename}->{key2} exist
2 rodolico 137
sub initialize {
138
   my ( $hash, $name, @keys ) = @_;
139
   foreach my $key ( @keys ) {
140
      $hash->{$name}->{$key} = '' unless $hash->{$name}->{$key};
141
   }
142
}
143
 
66 rodolico 144
# updates the lastseen time on a mac address by searching through $switchports until it finds it. If it doesn't exist, will
145
# add it.
2 rodolico 146
sub updateIP {
147
   my ( $switchports, $ip, $mac ) = @_;
148
   foreach my $switch ( keys %$switchports ) {
149
      my $thisSwitch = $switchports->{$switch}->{'ports'};
150
      foreach my $port ( keys %$thisSwitch ) {
151
         my $thisPort = $thisSwitch->{$port};
152
         foreach my $connection ( keys %$thisPort ) {
25 rodolico 153
            # skip the alias information on a port
66 rodolico 154
            next if $connection eq 'alias' or $connection eq 'description';
2 rodolico 155
            &initialize( $thisPort,$connection,'mac','ip','hostname','lastseen' );
156
            if ( $switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'mac'} eq $mac ) {
157
               my $modified = &updateValue( \$switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'ip'}, $ip );
158
               $modified |= &updateValue( \$switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'hostname'},gethostbyaddr( inet_aton( $ip ), AF_INET ));
159
               $switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'lastseen'} = time() if $modified;
160
               return;
161
            } # if we found it
162
         } # for connection
163
      } # for port
164
   } # for switch
165
} # updateIP
166
 
66 rodolico 167
 
168
# runs an snmpwalk using $MIB, then for each line, splits it with a regex
169
# if order is set to 12, first value of regex is a key, else second value is the key
170
sub parseSNMPQuery {
171
   my ($config, $switch, $MIB, $regex, $order) = @_;
172
   $order = 12 unless $order;
173
   my $return = {};
174
   my $values = `snmpwalk -v1 -c $config{switches}{$switch}{'community'} $switch $MIB`;
175
   foreach my $line ( split( "\n", $values ) ) {
176
      $line =~ m/$regex/;
177
      if ( $order == 12 ) {
178
         $return->{$1} = $2;
179
      } else {
180
         $return->{$2} = $1;
63 rodolico 181
      }
25 rodolico 182
   }
66 rodolico 183
   return $return;
25 rodolico 184
}
185
 
66 rodolico 186
# simple display if --help is passed
187
sub help {
188
   use File::Basename;
189
   print basename($0) . " $VERSION\n";
190
   print <<END
191
$0 [options]
192
Options:
193
   --debug          - set debug level
194
   --version        - display version and exit
195
   --help           - This page
196
END
197
}
25 rodolico 198
 
66 rodolico 199
 
200
# handle any command line parameters that may have been passed in
201
my $version = 0; # just used to determine if we should display the version
202
my $help = 0; # also if we want help
203
GetOptions (
204
            'debug|d=i'     => \$DEBUG,
205
            'help|h'        => \$help,
206
            'version|v'     => \$version,
207
            ) or die "Error parsing command line\n";
208
 
209
 
210
if ( $help ) { &help() ; exit; }
211
if ( $version ) { use File::Basename; print basename($0) . " $VERSION\n"; exit; }
212
 
213
# Load configuration file, die if we could not find it
5 rodolico 214
if ( -e $CONFIGFILE ) {
215
   my $yaml = YAML::Tiny->read( $CONFIGFILE );
216
   %config = %{ $yaml->[0] };
217
} else {
218
   die "could not locate config file $CONFIGFILE\n";
219
}
220
 
2 rodolico 221
# read the saved state into memory if it exists
222
if ( -e $STATEFILE ) {
223
   my $yaml = YAML::Tiny->read( $STATEFILE );
224
   %switchports = %{ $yaml->[0] };
225
}
226
 
227
# first, get all of the MAC/Port assignments from the switches
5 rodolico 228
foreach my $switch ( keys %{$config{'switches'}} ) {
63 rodolico 229
   print "Working on $switch\n" if $DEBUG;
2 rodolico 230
   &initialize( \%switchports, $switch, 'name','location' );
231
   &updateValue(
232
      \$switchports{$switch}{'name'},
66 rodolico 233
      &getOneSNMPValue( $DEVICENAMEMIB,$config{'switches'}{$switch}{'community'},$switch, qr/= STRING: "?([^"]*)"?/ )
2 rodolico 234
      );
235
 
236
   &updateValue(
237
      \$switchports{$switch}{'location'},
66 rodolico 238
      &getOneSNMPValue( $DEVICELOCMIB,$config{'switches'}{$switch}{'community'},$switch, qr/= STRING: "?([^"]*)"?/ )
2 rodolico 239
      );
66 rodolico 240
 
241
   # get list of all active ports not in our ignore list
242
   print "\tGetting Ports\n" if $DEBUG > 1;
243
   my $ports = parseSNMPQuery( \%config, $switch, $SWITCHPORTMIB, qr/$SWITCHPORTMIB\.(\d{1,3})\s=\sINTEGER:\s+(\d+)/ );
244
   #die Dumper( $ports );
245
   print "\tGetting Aliases\n" if $DEBUG > 1;
246
   my $aliases = parseSNMPQuery( \%config, $switch, $SWITCHIFALIASMIB, qr/\.(\d+) = STRING: "?([^\"]*)\"?$/ );
247
   #die Dumper( $aliases );
248
   print "\tGetting Descriptions\n" if $DEBUG > 1;
249
   my $descriptions = parseSNMPQuery( \%config, $switch, $SWITCHIFDESCMIB, qr/\.(\d+) = STRING: "?([^\"]*)"?$/ );
250
   #die Dumper( $descriptions );
25 rodolico 251
 
66 rodolico 252
   foreach my $port ( keys %$ports ) {
253
      if ( $ports->{$port} == 1 ) { # only work with ports that are active
254
         next if $config{'switches'}{$switch}{'portsToIgnore'} && grep( /^$port$/, @{$config{'switches'}{$switch}{'portsToIgnore'}} );
255
         $switchports{$switch}{'ports'}{$port}{'alias'} = $aliases->{$port} ? $aliases->{$port} : '';
256
         $switchports{$switch}{'ports'}{$port}{'description'} = $descriptions->{$port} ? $descriptions->{$port} : '';
257
      }
2 rodolico 258
   }
66 rodolico 259
   # die Dumper( \%switchports );
260
 
261
   # now, get the MAC addresses. See https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/44800-mactoport44800.html
262
   print "\tFinding Mac Addresses\n" if $DEBUG > 1;
263
   my $macs = parseSNMPQuery( \%config, $switch, $SWITCHMACMIB, qr/$SWITCHMACMIB\.([0-9.]+)\s=\sHex-STRING:\s+([0-9a-z ]+)$/i );
264
   #die Dumper( $macs );
265
   # find which bridges they are on
266
   print "\t\tFinding what bridges the MAC's are on\n" if $DEBUG > 2;
267
   my $macBridges = parseSNMPQuery( \%config, $switch, $BRIDGEPORTSMIB, qr/$BRIDGEPORTSMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
268
   #die Dumper( $macBridges );
269
   print "\t\tFinding what ports the ports are\n" if $DEBUG > 2;
270
   my $bridgeToPort = parseSNMPQuery( \%config, $switch, $BRIDGE2PORTMIB, qr/$BRIDGE2PORTMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
271
   #die Dumper( $bridgeToPort );
272
   foreach my $mac ( keys %$macs ) {
273
      $switchports{$switch}{'ports'}{$bridgeToPort->{$macBridges->{$mac}}}{$mac}{'mac'} = &makeMAC($mac);
274
   }
2 rodolico 275
}
276
 
66 rodolico 277
#die Dumper( \%switchports );
2 rodolico 278
 
279
 
280
# Now, try to match up the MAC address. Read the ARP table from the router(s)
5 rodolico 281
foreach my $router ( keys %{$config{'routers'}} ) {
66 rodolico 282
   print "Working on $router\n" if $DEBUG;
5 rodolico 283
   my $values = `snmpwalk -v1 -c $config{routers}{$router}{community} $router $ROUTERIPMACMIB`;
2 rodolico 284
   my @lines = split( "\n", $values );
285
   foreach my $line ( @lines ) {
286
      $line =~ m/$ROUTERIPMACMIB\.([0-9]+)\.([0-9.]+)\s=\sHex-STRING:\s([0-9a-z ]+)/i;
287
      my $interface = $1;
288
      my $ip = $2;
289
      my $mac = lc $3;
290
      $mac =~ s/ //g;
291
      &updateIP( \%switchports, $ip, $mac );
292
   }
293
}
294
 
295
#die Dumper( \%switchports );
296
 
297
# save the state file for later, so we can find things which disappear from the network
298
my $yaml = YAML::Tiny->new( \%switchports );
299
$yaml->write( $STATEFILE );
300
 
301
#print Dumper( \%switchports );
302
1;
303