Rev 133 | Rev 136 | Go to most recent revision | Blame | Compare with Previous | 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
# 20200301 RWR v2.1.0
# added some error checking in snmpwalk when a value is not returned, and also when the MAC address of the switch in
# question show up as bridge 0, which has no port (or, actually, all ports). Also, fixed the ignoreports
# 20200302 RWR v2.2.0
# Added the ability to override or supplement arp and dns searches for mac addresses
# 20230323 RWR v2.3.0
# Added ability to have one or more non_router files, with mac/name/ip in it in case arp lookup failed
# added script to create static html file in addition to csv
#
# 20230327 RWR v3.0.0
# rewrite to make things more efficient, and store data in different format. You MUST remove old yaml file
# before running this.
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("v3.3.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';
my $SWITCHPORTMIB = 'iso.3.6.1.2.1.2.2.1.8'; # returns port number and state, with a state of '1' meaning operational
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
# snmp returns a dotted integer for the mac, but we want mac's as hex with no formatting
# 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 );
}
# mac's from various places can have formatting, like ##:##:##:##:## or ###-###-###
# this will clean all that up by removing anything except hex values
# it will also convert alpha's (a-f) to lower case.
sub cleanMac {
my $mac = shift;
$mac =~ s/[^a-f0-9]//gi;
return lc $mac;
}
# 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;
}
# 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 ( $MIB, $ip, $community, $regex, $order ) = @_;
$order = 12 unless $order;
my $return = {};
my $values = `snmpwalk -v1 -c $community $ip $MIB`;
print "\t\t\tsnmpwalk -v1 -c $community $ip $MIB\n" if $DEBUG > 1;
foreach my $line ( split( "\n", $values ) ) {
next unless $line =~ m/$regex/;
if ( $order == 12 ) {
$return->{$1} = $2;
} else {
$return->{$2} = $1;
}
}
return $return;
}
# Load configuration file, die if we could not find it
# config file is a single page YAML file
sub loadConfig {
my $filename = shift;
my %config;
if ( -e $filename ) {
my $yaml = YAML::Tiny->read( $filename );
%config = %{ $yaml->[0] };
} else {
die "could not locate config file $filename\n";
}
return \%config;
}
# simple display if --help is passed
sub help {
use File::Basename;
print basename($0) . " $VERSION\n";
print <<END
$0 [options]
Options:
--no-snmp - do not actually run snmp commands
--debug - set debug level
--version - display version and exit
--help - This page
END
}
# get information about one single switch
#
sub getSwitchInfo {
my ( $ip, $community, $ignorePorts, $switchInfo ) = @_;
print "Working on $ip with community $community\n" if $DEBUG;
$switchInfo->{$ip}->{'name'} = # get actual device name
&getOneSNMPValue( $DEVICENAMEMIB,
$community,
$ip,
qr/= STRING: "?([^"]*)"?/);
$switchInfo->{$ip}->{'location'} = # and its snmp location
&getOneSNMPValue(
$DEVICELOCMIB,
$community,
$ip,
qr/= STRING: "?([^"]*)"?/ );
# get list of ports into hash with state as the value, '1' is operational
my $ports = &parseSNMPQuery( $SWITCHPORTMIB, $ip, $community, qr/$SWITCHPORTMIB\.(\d+)\s=\sINTEGER:\s+(\d+)/ );
print "=========Ports Hash\n" . Dumper( $ports ) . "\n" if $DEBUG == 4;
foreach my $port ( keys %$ports ) {
next unless $ports->{$port} == 1; # skip any non functional
next if $ignorePorts->{ $port };
# Get information about the ports. This may be possible to skip except on rare occassions?
# get port aliases, set to port number if undef
$switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} =
&getOneSNMPValue(
"$SWITCHIFALIASMIB.$port",
$community,
$ip,
qr/\.\d+\s+=\s+STRING:\s+"?([^"]*)"?$/ );
$switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} = $port unless defined ( $switchInfo->{$ip}->{'ports'}->{$port}->{'alias'} );
# get the port Description, set to port number if undef
$switchInfo->{$ip}->{'ports'}->{$port}->{'description'} =
&getOneSNMPValue(
"$SWITCHIFDESCMIB.$port",
$community,
$ip,
qr/\.\d+ = STRING: "?([^\"]*)"?$/ );
$switchInfo->{$ip}->{'ports'}->{$port}->{'description'} = $port unless defined ( $switchInfo->{$ip}->{'ports'}->{$port}->{'description'} );
}
}
# get all MAC addresses on switch and associate them with the correct port numbers
# https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/44800-mactoport44800.html
sub getSwitchPortMacs {
my ( $ip, $community, $ignoreList, $macList ) = @_;
print "\tFinding Mac Addresses\n" if $DEBUG > 1;
# get the MAC addresses into a list
my $macs = &parseSNMPQuery( $SWITCHMACMIB, $ip, $community, qr/$SWITCHMACMIB\.([0-9.]+)\s=\sHex-STRING:\s+([0-9a-z ]+)$/i );
print "Macs\n" . Dumper( $macs ) if $DEBUG >= 3;
# find which bridges they are on
print "\t\tFinding what bridges the MAC's are on\n" if $DEBUG > 2;
my $macBridges = &parseSNMPQuery( $BRIDGEPORTSMIB, $ip, $community, qr/$BRIDGEPORTSMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
print "MacBridges\n" . Dumper( $macBridges ) if $DEBUG >= 3;
print "\t\tFinding what ports the ports are\n" if $DEBUG > 2;
my $bridgeToPort = &parseSNMPQuery( $BRIDGE2PORTMIB, $ip, $community, qr/$BRIDGE2PORTMIB\.([0-9.]+)\s=\sINTEGER:\s+(\d+)/ );
print "BridgeToPort\n" . Dumper( $bridgeToPort ) if $DEBUG > 3;
# now, merge the three together to figure out what port a particular mac is on
foreach my $mac ( keys %$macs ) {
print "\t\t\t$mac\n" if $DEBUG > 3;
next unless defined ( $macBridges->{$mac} ) and defined ($bridgeToPort->{$macBridges->{$mac}} );
my $port = $bridgeToPort->{$macBridges->{$mac}};
next if $ignoreList->{$port};
$macList->{&makeMAC($mac)}->{'switch'} = $ip;
$macList->{&makeMAC($mac)}->{'port'} = $port;
$macList->{&makeMAC($mac)}->{'originalMAC'} = $mac;
$macList->{&makeMAC($mac)}->{'lastseen'} = time();
}
}
# get IP address from router(s), and hostname from rdns
sub getRouterInfo {
my ( $ip, $community, $routerInfo ) = @_;
print "Working on $ip\n" if $DEBUG;
print "snmpwalk -v1 -c $community $ip $ROUTERIPMACMIB\n" if $DEBUG > 1;
my $values = `snmpwalk -v1 -c $community $ip $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 = &cleanMac( $3 );
$routerInfo->{$mac}->{'ip'} = $ip;
$routerInfo->{$mac}->{'interface'} = $interface;
$routerInfo->{$mac}->{'hostname'} = gethostbyaddr( inet_aton( $ip ), AF_INET );
}
}
# load tab delimited values from $filename into hashref $nonRouterEntries
# format is
# macaddress
# 'ip' = IP Address
# 'mac' = MAC Address
# 'hostname' = HostName
sub loadNonRouterEntries {
my ( $nonRouterEntries, $filename ) = @_;
print "In loadNonRouterEntries with $filename\n" if $DEBUG > 1;
open FN,"<$filename" or die "Could not open $filename: $!\n";
my $line = <FN>;
chomp $line;
my @headers = split( "\t", $line );
my $macIndex = 0;
while ( $headers[$macIndex] !~ 'mac' && $macIndex < @headers ) {
$macIndex++;
}
if ( $macIndex >= @headers ) {
warn "File $filename does not appear to contain a mac column\n";
return;
}
while ( $line = <FN> ) {
next if $line =~ m/^#/;
chomp $line;
my @values = split( "\t", $line );
for( my $i = 0; $i < @headers; $i++ ) {
$nonRouterEntries->{&cleanMac($values[$macIndex])}->{$headers[$i]} = lc $values[$i];
}
}
close FN;
}
# merge nonRouterEntries into $routerARP, with $routerARP having precedence
sub updateRouterWithStatic {
my ( $routerARP, $nonRouterEntries ) = @_;
foreach my $mac ( keys %$nonRouterEntries ) {
# assign the hostname from staticmaps if there is one, and either override is true, or routerARP doesn't have one
$routerARP->{$mac}->{'hostname'} = $nonRouterEntries->{$mac}->{'hostname'}
if ( $nonRouterEntries->{$mac}->{'hostname'}
&& (
! $routerARP->{$mac}->{'hostname'}
|| $nonRouterEntries->{$mac}->{'override'}
)
);
# assign the hostname from staticmaps if there is one, and either override is true, or routerARP doesn't have one
$routerARP->{$mac}->{'ip'} = $nonRouterEntries->{$mac}->{'ip'}
if ( $nonRouterEntries->{$mac}->{'ip'}
&& (
! $routerARP->{$mac}->{'ip'}
|| $nonRouterEntries->{$mac}->{'override'}
)
);
}
}
################################################################################
# Main
################################################################################
# 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
my $nosnmp = 0; # we do NOT want to run snmp commands
GetOptions (
'debug|d=i' => \$DEBUG,
'nosnmp|n' => \$nosnmp,
'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; }
# Get configuration file into $config
my $config = &loadConfig( $CONFIGFILE );
print Dumper( $config ) if $DEBUG > 1;
die if $DEBUG > 4;
my $switchInfo = {}; # stores information about switches
my $macList = {}; # a list of all MAC addresses
# load the information for the switches into $switchInfo.
foreach my $switch ( keys %{$config->{'switches'}} ) {
last if $nosnmp; # do not read switches if $nosnmp set
my %ignoreList = map { $_ => 1 } @{ $config->{'switches'}->{$switch}->{'portsToIgnore'} }; # hash of ports to ignore
my $ignoreList = \%ignoreList;
print "ignoreList for $switch\n" . Dumper ($ignoreList) if $DEBUG > 2;
# just get basic switch information, inlcuding a list of all ports which are active and not in portsToIgnore
&getSwitchInfo( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList, $switchInfo );
# get all the MAC's on this switch
&getSwitchPortMacs( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList, $macList );
}
print "switchInfo\n" . Dumper( $switchInfo ) if $DEBUG > 2;
print "macList\n" . Dumper( $macList ) if $DEBUG > 2;
my $routerARP = {};
# Read the ARP table from the router(s)
foreach my $router ( keys %{$config->{'routers'}} ) {
last if $nosnmp; # do not read routers if $nosnmp set
&getRouterInfo( $router, $config->{'routers'}->{$router}->{'community'}, $routerARP );
}
print "Routers\n" . Dumper ($routerARP ) if $DEBUG > 2;
# load non-router entries, if they exist
my $nonRouterEntries = {};
if ( defined ( $config->{'nonrouter'} ) ) {
foreach my $filename ( @{$config->{'nonrouter'}} ) {
&loadNonRouterEntries( $nonRouterEntries, $scriptDir . '/' . $filename );
}
}
print "Non-Router Entries\n" . Dumper ( $nonRouterEntries ) if $DEBUG > 2;
# add in any staticmaps we may have. Note it will overwrite anything from files above
foreach my $mac ( keys %{$config->{'staticmaps'} } ) {
$nonRouterEntries->{$mac}->{'hostname'} = $config->{'staticmaps'}->{$mac}->{'hostname'} if $config->{'staticmaps'}->{$mac}->{'hostname'};
$nonRouterEntries->{$mac}->{'ip'} = $config->{'staticmaps'}->{$mac}->{'ip'} if $config->{'staticmaps'}->{$mac}->{'ip'};
$nonRouterEntries->{$mac}->{'override'} = $config->{'staticmaps'}->{$mac}->{'override'} if $config->{'staticmaps'}->{$mac}->{'override'};
}
&updateRouterWithStatic( $routerARP, $nonRouterEntries );
print "routerInfo\n" . Dumper ( $routerARP ) if $DEBUG > 2;
#print Dumper( $macList ); die;
my $saveFile = {};
# read the saved state into memory if it exists
if ( -e $STATEFILE ) {
my $yaml = YAML::Tiny->read( $STATEFILE );
$saveFile = \%{ $yaml->[0] };
}
$saveFile->{'switchInfo'} = $switchInfo;
foreach my $mac ( keys %$macList ) {
$saveFile->{'macList'}->{$mac} = $macList->{$mac};
$saveFile->{'macList'}->{$mac}->{'hostname'} = $routerARP->{$mac}->{'hostname'};
$saveFile->{'macList'}->{$mac}->{'ip'} = $routerARP->{$mac}->{'ip'};
}
#print Dumper( $saveFile ); die;
#print Dumper( $switchInfo); die;
# save the file
my $yaml = YAML::Tiny->new( $saveFile );
$yaml->write( $STATEFILE );
1;