Subversion Repositories sysadmin_scripts

Rev

Rev 136 | Rev 139 | 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
#
# 20230324 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.
#
# 20230325 RWR v3.0.1
# Added ability to delete entries which haven't been seen since $config->{'ttl'} seconds. ttl can be
# an integer followed by a unit, with units being single char h,d,w,m,y (hours, days, weeks, months, years)
# added ability to set so it will only refresh dns and device names every $refresh seconds, decreasing
# run time to 33% value when not used. Test system decreases from 15s to 5-7s
# reorganized so system runs smoother (test system decreased from 40 seconds to 15)
#
# 20230326 RWR v3.0.2
# set it up so if net::dns not loadable, will revert to ionet

# for Debian, to get the required libraries
# apt install libyaml-tiny-perl libnet-dns-perl snmp

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.1");

# 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;
}

# do a reverse dns lookup of an IP address and return the hostname
# note that $dns is an instance of Net::DNS
# if it is not set, will revert to using inet_aton, which only
# works off of the resolv.conf on the local machine
sub getHostName {
   my ($dns, $ip ) = @_;
   if ( $dns ) {
      foreach my $resource ( @$dns ) {
         my  $reply = $resource->search( $ip );
         next unless defined $reply;
         my @answer = grep { ! /^((;.*)|(\s*))$/ } split( "\n", $reply->string );
         $answer[0] =~ m/\s([a-z0-9.-]+)\.$/;
         return $1;
      }
   } else {
      return gethostbyaddr( inet_aton( $ip ), AF_INET );
   }
   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
   --refresh         - force a refresh even if not time
   --version         - display version and exit
   --help            - This page
END
}

# get information about one single switch
#
sub getSwitchInfo {
   my ( $ip, $community, $ignorePorts ) = @_;
   my $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'} );
   }
   return $switchInfo->{$ip};
}

# 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)
# since the information is already there, we grab the interface also
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;
   }
}

# load tab delimited values from $filename into hashref $nonRouterEntries
# format is
# macaddress
#     'ip' = IP Address
#     'mac' = MAC Address
#     'hostname' = HostName

sub loadNonRouterEntries {
   my ( $scriptDir, $files, $staticMaps, $routerARP ) = @_;
   # first, load the information from the files
   foreach my $filename ( @$files ) {
      open FN,"<$scriptDir/$filename" or die "Could not open $scriptDir/$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 );
         my $mac = &cleanMac($values[$macIndex]);
         for( my $i = 0; $i < @headers; $i++ ) {
            # update the value if one does not already exist
            $routerARP->{$mac}->{$headers[$i]} = lc $values[$i] unless $routerARP->{$mac}->{$headers[$i]};
         }
      }
      close FN;
   }
   # now, update from our staticmaps
   foreach my $mac ( keys %$staticMaps ) {
      # only update ip if it doesn't exist, or if we have an override
      $routerARP->{$mac}->{'ip'} = $staticMaps->{$mac}->{'ip'} if $staticMaps->{$mac}->{'override'} || ! $routerARP->{$mac}->{'ip'};
      # these don't exist in $routerARP, so we just add them
      $routerARP->{$mac}->{'hostname'} = $staticMaps->{$mac}->{'hostname'};
      $routerARP->{$mac}->{'override'} = $staticMaps->{$mac}->{'override'};
   }
}

   
# 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'} 
                  )
               );
   }
}

# get IP addresses from the list of them we have
sub getIPAddresses {
   my ( $macList, $ipList ) = @_;
   foreach my $mac ( keys %$macList ) {
      $macList->{$mac}->{'ip'} = $ipList->{$mac}->{'ip'} if $ipList->{$mac}->{'ip'};
   }
}

# grab names by reverse DNS from the IP addresses
# if that fails, or if there is an override
# use the name from $routerARP, if it exists;
sub getDNSNames {
   my ( $macList, $dnsResource, $routerARP ) = @_;
   foreach my $mac ( keys %$macList ) {
      if ( $routerARP->{$mac}->{'override'} && $routerARP->{$mac}->{'hostname'} ) {
         $macList->{$mac}->{'hostname'} = $routerARP->{$mac}->{'hostname'};
      } else { # try a DNS lookup
         $macList->{$mac}->{'hostname'} = &getHostName( $dnsResource, $macList->{$mac}->{'ip'} );
         # still didn't find one, so add one from $routerARP if it exists
         $macList->{$mac}->{'hostname'} = $routerARP->{$mac}->{'hostname'} if ! $macList->{$mac}->{'hostname'} && $routerARP->{$mac}->{'hostname'};
      }
   }
}

# given a value of a number follwed by a unit (ie, 2w, 12h, 3m), determine 
# the unixtime for that long ago.
sub calcAge {
   my $time = shift;
   my %seconds = ( 
      's' => 1,
      'h' => 60*60,
      'd' => 86400,
      'w' => 7*86400,
      'm' => 7*30.5*86400,
      'y' => 86400*365.2425
      );
   $time = lc $time;
   $time =~ m/^(\d+)(.*)/;
   $time = $1;
   my $unit = $2;
   $unit = 's' unless $unit;
   return defined( $seconds{$unit} ) ? $time * $seconds{$unit} : 0;
}

# given an integer/modifier (1w, 3d, 10h), remove all mac entries which have not
# been seen since then.
sub cleanUpOldEntries {
   my ( $ttl, $list ) = @_;
   my $currentTime = time;
   my $deleteBefore = &calcAge( $ttl );
   if ( $deleteBefore == 0 ) {
      warn "Invalid ttl definition [$ttl], not cleaning up\n";
      return;
   }
   $deleteBefore = time - $deleteBefore;
   foreach my $mac ( keys %{ $list->{'macList'} } ) {
      if ( $list->{'macList'}->{$mac}->{'lastseen'} < $deleteBefore ) {
#         print 
#            "Deleting $mac with a last seen of " . 
#            $list->{'macList'}->{$mac}->{'lastseen'} . 
#            ", current time is $currentTime for a difference of " . 
#            ( $currentTime - $list->{'macList'}->{$mac}->{'lastseen'} ) . 
#            "\n";
         delete $list->{'macList'}->{$mac} if $list->{'macList'}->{$mac}->{'lastseen'};
      }
   }
}

################################################################################
#              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
my $forceRefres = 0; # force a refresh even if one is not called for now
GetOptions (
            'debug|d=i'     => \$DEBUG,
            'nosnmp|n'      => \$nosnmp,
            'refresh|r'     => \$forceRefres,
            '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;

# load the savefile, if it exists
my $saveFile = { 'macList' => {}, 'switchInfo' => {} };
# read the saved state into memory if it exists
if ( -e $STATEFILE ) {
   my $yaml = YAML::Tiny->read( $STATEFILE );
   $saveFile = \%{ $yaml->[0] };
}


my $dnsResource = 0;
eval {
   use Net::DNS; # dns lookup, apt install libnet-dns-perl
   $dnsResource = [];
   # set up one dns resource for every router we have
   # too many failures when trying to define both of them at the same time
   foreach my $router ( keys %{ $config->{'routers'} } ) {
      push @$dnsResource, Net::DNS::Resolver->new(
       'nameservers' => [ $router ],
       'recurse' => 0
       );
   }
};

my $refresh = 1; # determines if we get extra information like switch info, port aliases, etc...
if ( defined( $config->{'refresh'} ) ) {
   # get the number of seconds between refreshes
   $refresh = &calcAge( $config->{'refresh'} );
   # if we have not recorded a refresh, set the refresh time to run now
   $saveFile->{'lastrefresh'} = time - &calcAge( $config->{'refresh'} ) - 1 
      unless defined $saveFile->{'lastrefresh'};
   $refresh = $saveFile->{'lastrefresh'} + &calcAge( $config->{'refresh'} ) < time || $forceRefres;
   $saveFile->{'lastrefresh'} = time if $refresh;
}

print STDERR "Doing a full refresh\n" if $refresh && $DEBUG > 1;



# 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
   $saveFile->{'switchInfo'}->{$switch} = &getSwitchInfo( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList ) if $refresh;
   # get all the MAC's on this switch
   &getSwitchPortMacs( $switch, $config->{'switches'}->{$switch}->{'community'}, $ignoreList, $saveFile->{'macList'} );
}


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 ) if $refresh;
}
print "Routers\n" . Dumper ($routerARP ) if $DEBUG > 2;
# add in anything we have defined in files or in staticmaps in the config file
&loadNonRouterEntries( $scriptDir, $config->{'nonrouter'}, $config->{'staticmaps'}, $routerARP );
print "Routers after loadNonRouterEntries\n" . Dumper ($routerARP ) if $DEBUG > 2;
# populate the mac list with information from $routerARP
&getIPAddresses( $saveFile->{'macList'}, $routerARP );
print "Routers after getIPAddresses\n" . Dumper ($routerARP ) if $DEBUG > 2;
# get the DNS names
&getDNSNames( $saveFile->{'macList'}, $dnsResource, $routerARP ) if $refresh;
print "Routers after getDNSNames\n" . Dumper ($routerARP ) if $DEBUG > 2;
# clean up any old entries
&cleanUpOldEntries( $config->{'ttl'}, $saveFile ) if $config->{'ttl'} && $refresh;
# save the file
my $yaml = YAML::Tiny->new( $saveFile );
$yaml->write( $STATEFILE );


1;