Rev 130 | 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
# 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
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.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';
# 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 );
}
sub cleanMac {
my $mac = shift;
$mac =~ s/[^a-f0-9]//gi;
return lc $mac;
}
# 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 ) = @_;
print "In initialize, name is $name and hash is\n" . Dumper( $hash ) if $DEBUG > 3;
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();
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`;
print "\t\t\tsnmpwalk -v1 -c $config{switches}{$switch}{'community'} $switch $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 tab delimited values from $filename into hashref $nonRouterEntries
# format is
# macaddress
# 'ip' = IP Address
# 'mac' = MAC Address
# 'hostname' = HostName
sub loadNonRouterEntries {
my ( $nonRouterEntries, $filename ) = @_;
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;
}
# 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
}
# 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; }
# 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'}} ) {
last if $nosnmp; # do not read switches if $nosnmp set
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+)\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
print "\t\tGetting alias and description for port $port\n" if $DEBUG > 3;
$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 ) {
print "\t\t\t$mac\n" if $DEBUG > 2;
next unless defined ( $macBridges->{$mac} ) and defined ($bridgeToPort->{$macBridges->{$mac}} );
$switchports{$switch}{'ports'}{$bridgeToPort->{$macBridges->{$mac}}}{$mac}{'mac'} = &makeMAC($mac) if defined( $switchports{$switch}{'ports'} );
}
# remove the ports we want to ignore
print "\t\tDeleting ignored ports [" . join(',',@{$config{'switches'}{$switch}{'portsToIgnore'}} ) . "]\n" if $DEBUG > 1;
foreach my $ignore ( @{$config{'switches'}{$switch}{'portsToIgnore'}} ) {
# print join( ',', sort {$a<=>$b} keys %{$ports} ) . "\n";
delete $switchports{$switch}{'ports'}{$ignore};
}
# print join( ',', sort {$a<=>$b} keys %{$ports} ) . "\n";
# die;
}
#print Dumper( \%switchports ); die;
# Now, try to match up the MAC address. Read the ARP table from the router(s)
foreach my $router ( keys %{$config{'routers'}} ) {
last if $nosnmp; # do not read routers if $nosnmp set
print "Working on $router\n" if $DEBUG;
print "snmpwalk -v1 -c $config{routers}{$router}{community} $router $ROUTERIPMACMIB\n" if $DEBUG > 1;
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 = &cleanMac( $3 );
#$mac =~ s/ //g;
&updateIP( \%switchports, $ip, $mac );
}
}
# load non-router entries, if they exist
my $nonRouterEntries = {};;
if ( defined ( $config{'nonrouter'} ) ) {
foreach my $filename ( @{$config{'nonrouter'}} ) {
&loadNonRouterEntries( $nonRouterEntries, $scriptDir . '/' . $filename );
}
}
#print Dumper( $nonRouterEntries ) . "\n"; die;
# now, process any static maps we might have and, failing that, any non-router entries
if ( defined( $config{'staticmaps'} ) ) {
# let's make sure there is an entry for each one
foreach my $entry ( keys %{$config{'staticmaps'}} ) {
&initialize( \%{$config{'staticmaps'}}, $entry, 'ip','hostname','override' );
}
} # if defined
#print Dumper( $config{'staticmaps'} );
# Go through entire switch array and see if we can figure out any empty hostnames and/or IP addresses from
# either the staticmaps or the nonRouterEntries
foreach my $switch ( keys %switchports ) {
foreach my $portnum (keys %{ $switchports{$switch}{'ports'} } ) {
foreach my $connection ( keys %{ $switchports{$switch}{'ports'}{$portnum} } ) {
next if $connection eq 'description' or $connection eq 'alias';
my $mac = $switchports{$switch}{'ports'}{$portnum}{$connection}{'mac'};
# we already have a hostname and IP, so skip to next one
# print "Looking up $switch, port $portnum with mac address $mac\n";
unless ( $switchports{$switch}{'ports'}{$portnum}{$connection}{'hostname'} ) {
if ( defined( $config{'staticmaps'}{$mac}{'ip'} ) && $config{'staticmaps'}{$mac}{'hostname'} ) {
$switchports{$switch}{'ports'}{$portnum}{$connection}{'hostname'} = $config{'staticmaps'}{$mac}{'hostname'};
} elsif ( defined( $nonRouterEntries->{$mac}->{'hostname'} ) && $nonRouterEntries->{$mac}->{'hostname'} ) {
$switchports{$switch}{'ports'}{$portnum}{$connection}{'hostname'} = $nonRouterEntries->{$mac}->{'hostname'};
}
}
unless ( $switchports{$switch}{'ports'}{$portnum}{$connection}{'ip'} ) {
if ( defined( $config{'staticmaps'}{$mac}{'ip'} ) && $config{'staticmaps'}{$mac}{'ip'} ) {
$switchports{$switch}{'ports'}{$portnum}{$connection}{'ip'} = $config{'staticmaps'}{$mac}{'ip'};
} elsif ( defined( $nonRouterEntries->{$mac}->{'ip'} ) && $nonRouterEntries->{$mac}->{'ip'} ) {
$switchports{$switch}{'ports'}{$portnum}{$connection}{'ip'} = $nonRouterEntries->{$mac}->{'ip'};
}
}
} # checking each connection
} # checking each port number
} # checking each switch
#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;