Rev 63 | Blame | Last modification | View Log | Download | RSS feed
#! /usr/bin/env perl
# Script does an snmp walk through the ports of one or more network
# switch, gathering MAC addresses assigned to each port.
#
# It then does an snmp walk through the arp table of one or
# more routers to determine IP and DNS entries for the MAC address
#
# Information gathered is stored in persistent storage (a yaml formatted file
# in the same directory), then reloaded at the next start of the program.
# As new entries become available, they are added. A time stamp
# records the last time an entry was "seen"
#
# requires snmp running on this machine. Also uses YAML::Tiny perl module
# under debian and derivatives, use the following command to install
# apt-get -y install snmp libyaml-tiny-perl
#
#
# Data is stored in the hash %switchports with the following structure
# %switchports =
# {switch} (from $config{'switches'} key)
# {name} (scalar, from snmp)
# {location} (scalar, from snmp)
# {'ports'} (constant key for sub hash)
# {port number} (from snmp)
# {connection} (uniqe id from snmp, basically the MAC)
# {mac} (from snmp walk of switch)
# {ip} (from snmp walk of router)
# {hostname} (from reverse dns query)
# {lastseen} (last time this was active as unix timestamp)
#
# Uses two external files, both in the same directory as the script
# mapSwitches.config.yaml - Configuration file. See makeConfig.pl.sample for documentation. This can be created if you, like
# me, are more comfortable with perl syntax. Once edited, run it to create the .yaml config file
# mapSwitches.yaml - a state file which maintains information across executions. This allows us to track connections
# which are not on all the time. Can be deleted at any time for a fresh start. Can be dumped into a
# tab delimited text file (to STDOUT) with helper script mapSwitchesCSV.pl
#
# 20190407 RWR
# converted to use external config file in YAML format
# added the ability to ignore ports on the switches
# 20190514 RWR
# Added port aliases
# 20190526 RWR
# fixed mapSwitchCSV.pl to output in various delimited format (see README)
# 20200107 RWR v1.3
# Fixed problem where alias MIB was not returning values
# 20200228 RWR v1.4
# added description MIB and field
# 20200229 RWR v2.0.0
# rewrite, with 80% of the code changed. Found serious flaws with the way the ports were being read and fixed them.
# also set it up so it is a little more concise by combining redundant code into one routine, parseSNMPQuery, which
# reads an snmp walk and returns the results as a hash
use strict;
use warnings;
use Data::Dumper; # only used for debugging
use Socket; # for reverse dns entries
use YAML::Tiny; # apt-get libyaml-tiny-perl under debian
use File::Spec; # find location of script so we can put storage in same directory
use File::Basename;
my $DEBUG = 0;
# define the version number
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
use version;
our $VERSION = version->declare("v2.0.0");
# see https://perldoc.perl.org/Getopt/Long.html
use Getopt::Long;
# allow -vvn (ie, --verbose --verbose --dryrun)
Getopt::Long::Configure ("bundling");
my %config; # we read the configuration file into this
# where the script is located
my $scriptDir = dirname( File::Spec->rel2abs( __FILE__ ) );
# put the statefile in there
my $STATEFILE = $scriptDir . '/mapSwitches.yaml';
my $CONFIGFILE = $scriptDir . '/mapSwitches.config.yaml';
# main hash that holds the data we collect
my %switchports;
# OID's to read the swtiches
# NOTE: for the regular expressions to work, you must use iso. for the OID
#my $SWITCHPORTMIB = 'iso.3.6.1.2.1.17.4.3.1.2';
my $SWITCHPORTMIB = 'iso.3.6.1.2.1.2.2.1.8';
my $SWITCHMACMIB = 'iso.3.6.1.2.1.17.4.3.1.1'; # dot1dTpFdbAddress, aka mac addresses
my $SWITCHIFALIASMIB = 'iso.3.6.1.2.1.31.1.1.1.18'; # ifAlias, the the 'alias' field
my $SWITCHIFDESCMIB = 'iso.3.6.1.2.1.2.2.1.2'; # ifDescr, the "description" field
my $BRIDGEPORTSMIB = 'iso.3.6.1.2.1.17.4.3.1.2';
my $BRIDGE2PORTMIB = 'iso.3.6.1.2.1.17.1.4.1.2';
# this is only for the router, to get IP of the device in question
my $ROUTERIPMACMIB = 'iso.3.6.1.2.1.4.22.1.2'; # ipNetToMediaPhysAddress #'iso.3.6.1.2.1.3.1.1.2';
# this should work for all devices
my $DEVICENAMEMIB = 'iso.3.6.1.2.1.1.5'; # sysname
my $DEVICELOCMIB = 'iso.3.6.1.2.1.1.6'; # syslocation
# take a dotted integer form of a mac and converts it to hex, all lower case
sub makeMAC {
my $string = shift;
my @octets = split( '\.', $string );
for ( my $i = 0; $i < @octets; $i++ ) {
$octets[$i] = sprintf( "%02x", $octets[$i] );
}
return join( '', @octets );
}
# simply updates a value. First parameter ($oldValue) is passed by reference so it can be directly accessed
# returns 1 on success, 0 on failure
sub updateValue {
my ( $oldValue, $newValue ) = @_;
$newValue = '' unless defined $newValue;
if ( $newValue ) {
$$oldValue = $newValue unless $newValue eq $$oldValue;
return 1;
}
return 0;
}
# grabs one single SNMP value from string. Assumes $OID returns only one line, then runs $regex against it.
sub getOneSNMPValue {
my ( $oid, $community, $ip, $regex ) = @_;
my $line = `snmpwalk -v1 -c $community $ip $oid`;
$line =~ m/$regex/i;
return $1;
}
# ensures a hash has $name with every value in @keys
# call with &initialize( \%hash, 'somename', 'key1','key2');
# will ensure $hash->{somename}->{key1} and $hash->{somename}->{key2} exist
sub initialize {
my ( $hash, $name, @keys ) = @_;
foreach my $key ( @keys ) {
$hash->{$name}->{$key} = '' unless $hash->{$name}->{$key};
}
}
# updates the lastseen time on a mac address by searching through $switchports until it finds it. If it doesn't exist, will
# add it.
sub updateIP {
my ( $switchports, $ip, $mac ) = @_;
foreach my $switch ( keys %$switchports ) {
my $thisSwitch = $switchports->{$switch}->{'ports'};
foreach my $port ( keys %$thisSwitch ) {
my $thisPort = $thisSwitch->{$port};
foreach my $connection ( keys %$thisPort ) {
# skip the alias information on a port
next if $connection eq 'alias' or $connection eq 'description';
&initialize( $thisPort,$connection,'mac','ip','hostname','lastseen' );
if ( $switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'mac'} eq $mac ) {
my $modified = &updateValue( \$switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'ip'}, $ip );
$modified |= &updateValue( \$switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'hostname'},gethostbyaddr( inet_aton( $ip ), AF_INET ));
$switchports->{$switch}->{'ports'}->{$port}->{$connection}->{'lastseen'} = time() if $modified;
return;
} # if we found it
} # for connection
} # for port
} # for switch
} # updateIP
# runs an snmpwalk using $MIB, then for each line, splits it with a regex
# if order is set to 12, first value of regex is a key, else second value is the key
sub parseSNMPQuery {
my ($config, $switch, $MIB, $regex, $order) = @_;
$order = 12 unless $order;
my $return = {};
my $values = `snmpwalk -v1 -c $config{switches}{$switch}{'community'} $switch $MIB`;
foreach my $line ( split( "\n", $values ) ) {
$line =~ m/$regex/;
if ( $order == 12 ) {
$return->{$1} = $2;
} else {
$return->{$2} = $1;
}
}
return $return;
}
# simple display if --help is passed
sub help {
use File::Basename;
print basename($0) . " $VERSION\n";
print <<END
$0 [options]
Options:
--debug - set debug level
--version - display version and exit
--help - This page
END
}
# handle any command line parameters that may have been passed in
my $version = 0; # just used to determine if we should display the version
my $help = 0; # also if we want help
GetOptions (
'debug|d=i' => \$DEBUG,
'help|h' => \$help,
'version|v' => \$version,
) or die "Error parsing command line\n";
if ( $help ) { &help() ; exit; }
if ( $version ) { use File::Basename; print basename($0) . " $VERSION\n"; exit; }
# Load configuration file, die if we could not find it
if ( -e $CONFIGFILE ) {
my $yaml = YAML::Tiny->read( $CONFIGFILE );
%config = %{ $yaml->[0] };
} else {
die "could not locate config file $CONFIGFILE\n";
}
# read the saved state into memory if it exists
if ( -e $STATEFILE ) {
my $yaml = YAML::Tiny->read( $STATEFILE );
%switchports = %{ $yaml->[0] };
}
# first, get all of the MAC/Port assignments from the switches
foreach my $switch ( keys %{$config{'switches'}} ) {
print "Working on $switch\n" if $DEBUG;
&initialize( \%switchports, $switch, 'name','location' );
&updateValue(
\$switchports{$switch}{'name'},
&getOneSNMPValue( $DEVICENAMEMIB,$config{'switches'}{$switch}{'community'},$switch, qr/= STRING: "?([^"]*)"?/ )
);
&updateValue(
\$switchports{$switch}{'location'},
&getOneSNMPValue( $DEVICELOCMIB,$config{'switches'}{$switch}{'community'},$switch, qr/= STRING: "?([^"]*)"?/ )
);
# get list of all active ports not in our ignore list
print "\tGetting Ports\n" if $DEBUG > 1;
my $ports = parseSNMPQuery( \%config, $switch, $SWITCHPORTMIB, qr/$SWITCHPORTMIB\.(\d{1,3})\s=\sINTEGER:\s+(\d+)/ );
#die Dumper( $ports );
print "\tGetting Aliases\n" if $DEBUG > 1;
my $aliases = parseSNMPQuery( \%config, $switch, $SWITCHIFALIASMIB, qr/\.(\d+) = STRING: "?([^\"]*)\"?$/ );
#die Dumper( $aliases );
print "\tGetting Descriptions\n" if $DEBUG > 1;
my $descriptions = parseSNMPQuery( \%config, $switch, $SWITCHIFDESCMIB, qr/\.(\d+) = STRING: "?([^\"]*)"?$/ );
#die Dumper( $descriptions );
foreach my $port ( keys %$ports ) {
if ( $ports->{$port} == 1 ) { # only work with ports that are active
next if $config{'switches'}{$switch}{'portsToIgnore'} && grep( /^$port$/, @{$config{'switches'}{$switch}{'portsToIgnore'}} );
$switchports{$switch}{'ports'}{$port}{'alias'} = $aliases->{$port} ? $aliases->{$port} : '';
$switchports{$switch}{'ports'}{$port}{'description'} = $descriptions->{$port} ? $descriptions->{$port} : '';
}
}
# die Dumper( \%switchports );
# now, get the MAC addresses. See https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/44800-mactoport44800.html
print "\tFinding Mac Addresses\n" if $DEBUG > 1;
my $macs = parseSNMPQuery( \%config, $switch, $SWITCHMACMIB, qr/$SWITCHMACMIB\.([0-9.]+)\s=\sHex-STRING:\s+([0-9a-z ]+)$/i );
#die Dumper( $macs );
# find which bridges they are on
print "\t\tFinding what bridges the MAC's are on\n" if $DEBUG > 2;
my $macBridges = parseSNMPQuery( \%config, $switch, $BRIDGEPORTSMIB, qr/$BRIDGEPORTSMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
#die Dumper( $macBridges );
print "\t\tFinding what ports the ports are\n" if $DEBUG > 2;
my $bridgeToPort = parseSNMPQuery( \%config, $switch, $BRIDGE2PORTMIB, qr/$BRIDGE2PORTMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
#die Dumper( $bridgeToPort );
foreach my $mac ( keys %$macs ) {
$switchports{$switch}{'ports'}{$bridgeToPort->{$macBridges->{$mac}}}{$mac}{'mac'} = &makeMAC($mac);
}
}
#die Dumper( \%switchports );
# Now, try to match up the MAC address. Read the ARP table from the router(s)
foreach my $router ( keys %{$config{'routers'}} ) {
print "Working on $router\n" if $DEBUG;
my $values = `snmpwalk -v1 -c $config{routers}{$router}{community} $router $ROUTERIPMACMIB`;
my @lines = split( "\n", $values );
foreach my $line ( @lines ) {
$line =~ m/$ROUTERIPMACMIB\.([0-9]+)\.([0-9.]+)\s=\sHex-STRING:\s([0-9a-z ]+)/i;
my $interface = $1;
my $ip = $2;
my $mac = lc $3;
$mac =~ s/ //g;
&updateIP( \%switchports, $ip, $mac );
}
}
#die Dumper( \%switchports );
# save the state file for later, so we can find things which disappear from the network
my $yaml = YAML::Tiny->new( \%switchports );
$yaml->write( $STATEFILE );
#print Dumper( \%switchports );
1;
Generated by GNU Enscript 1.6.5.90.