switchmac.in 13.2 KB
Newer Older
1 2 3
#!/usr/bin/perl -w

#
4
# Copyright (c) 2003-2012 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
24 25 26 27 28 29 30 31
#

#
# switchmac - a tool for getting MAC address listings from Cisco switches.
# Reports all MACs learned on all experimental switches.
#
# The output of this script is supposed to be machine-readable, rather than
# human-readable. The output is:
32
# <mac>,<switch>/<module>.<port>,<vlan>,<interface>,<class>
33 34 35 36 37 38
#
# <mac> is the learned MAC address, no puncuation, in lowercase.
# <switch>, <module>, and <port> are what they sound like.
# <vlan> indicates which VLAN the MAC was learned in
# <interface> is the <node>:<iface> of the interface that matches the MAC
#     address, if any. 'unknown' if the MAC is not in our database
39
# <class> is 'experimental' or 'control', depending on the primary function
Leigh Stoller's avatar
Leigh Stoller committed
40
#     of the switch the MAC address was learned from. 
41 42 43 44
#

use lib '@prefix@/lib';
use libdb;
Leigh Stoller's avatar
Leigh Stoller committed
45
use libxmlrpc;
46 47 48 49 50 51
use SNMP;
use Getopt::Long;
use strict;

# Optional alternate version of libraries.
use lib '@prefix@/lib/snmpit_test';
52 53
use snmpit_lib;
use snmpit_cisco;
54
use snmpit_foundry;
55
use snmpit_nortel;
56
use snmpit_hp;
57 58

my $MASTER_COMMUNITY = "@SNMP_RW_COMMUNITY@";
Leigh Stoller's avatar
Leigh Stoller committed
59 60 61 62
my $ELABINELAB = @ELABINELAB@;
my $RPCSERVER  = "@OUTERBOSS_NODENAME@";
my $RPCPORT    = "@OUTERBOSS_XMLRPCPORT@";
my $RPCCERT    = "@OUTERBOSS_SSLCERTNAME@";
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

#
# We use SNMP directly, because we have to use some pretty dumb tricks that I
# don't want to have to teach the snmpit libraries.
#
my $mibpath = "/usr/local/share/snmp/mibs";
my @mibs = ("$mibpath/SNMPv2-SMI.txt", "$mibpath/SNMPv2-TC.txt",
    "$mibpath/SNMPv2-MIB.txt", "$mibpath/IANAifType-MIB.txt",
    "$mibpath/IF-MIB.txt", "$mibpath/BRIDGE-MIB.txt");

#
# Don't know what damage users could do with this script, but why not, let's be
# paranoid about it.
#
if (!TBAdmin($>)) {
    die "Sorry, only admins can use this script\n";
}

81
my (@test_switches, @control_switches);
82
my $debug = 0;
83 84 85 86
my %opt = ("v+" => \$debug,
	   "E=s" => \@test_switches,
	   "C=s" => \@control_switches);
GetOptions(%opt);
87 88 89 90 91

sub DEBUG {
    if ($debug) {
	print STDERR @_;
    }
92 93
}

Leigh Stoller's avatar
Leigh Stoller committed
94 95 96 97
#
# ElabinElab is special; Ask outer boss for the info.
#
if ($ELABINELAB) {
98 99 100
    if ($debug) {
        DEBUG "ELABINELAB mode\n";
    }
Leigh Stoller's avatar
Leigh Stoller committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    libxmlrpc::Config({"server"  => $RPCSERVER,
		       "verbose" => 0,
		       "cert"    => $RPCCERT,
		       "portnum" => $RPCPORT});

    my $rval = libxmlrpc::CallMethod("elabinelab", "switchmac", {});

    if (!defined($rval)) {
	exit(-1);
    }
      
    #
    # Convert the stuff the RPC server back into the proper string format.
    #
    foreach my $mac (keys(%{ $rval })) {
	my $aref        = $rval->{$mac};
	my $iface       = $aref->{"iface"};
	my $role        = $aref->{"role"};
	my $switch_id   = $aref->{"switch_id"};
	my $switch_card = $aref->{"switch_card"};
	my $switch_port = $aref->{"switch_port"};

	print "${mac},${switch_id}/${switch_card}.${switch_port},".
	    "elabinelab,${iface},${role}\n";
    }
    exit(0);
}
&SNMP::addMibFiles(@mibs);
&SNMP::initMib();

131
#
132 133 134
# If explicit switches were listed, we use them as listed in the roles
# specified with no checking.  The caller had better know what they are
# doing!
135
#
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
if (@test_switches > 0) {
    if ($test_switches[0] eq "none") {
	@test_switches = ();
    } else {
	@test_switches = map {[$_,"experimental"]} @test_switches;
    }
} else {
    #
    # Yeah, it's slow, but we want to use all the test switches so that we don't
    # have to worry about missing something, and don't have to get the user to
    # guess which switch they're using
    #
    @test_switches = map {[$_,"experimental"]} getTestSwitches();
    if (!@test_switches) {
	die "Error: No experimental net switches found in database - you need\n" .
	    "to add them before running this script\n";
    }
153
}
154

155 156 157 158 159
#
# Get trunk ports so that we can skip MACs learned on them
#
my %trunks = getTrunkHash();

160 161 162 163 164 165 166 167 168 169 170 171
if (@control_switches > 0) {
    if ($control_switches[0] eq "none") {
	@control_switches = ();
    } else {
	@control_switches = map {[$_,"control"]} @control_switches;
    }
} else {
    @control_switches = map {[$_,"control"]} getControlSwitches();
    if (!@control_switches) {
	warn "Warning - No control switches found - you probably want to add them " .
	    "to the nodes table\n";
    }
172 173 174 175
}

my @switches = (@test_switches, @control_switches);

176 177 178 179 180
if ($debug) {
    DEBUG "switches in database:\n";
    foreach my $switch (@switches) {
        my ($name, $type) = @$switch;
        DEBUG "  $name ($type)\n";
181 182 183 184
    }
}

#
185
# Loop through each switch individually
186
#
187
SWITCHLOOP:
188 189 190
foreach my $switchref (@switches) {
    my ($switch, $class) = @$switchref;
    DEBUG "Looking at switch $switch, class $class\n";
191

Leigh Stoller's avatar
Leigh Stoller committed
192 193 194
    my $class_str = (($class eq "experimental") ?
		     TBDB_IFACEROLE_EXPERIMENT() : TBDB_IFACEROLE_CONTROL());

195 196 197 198
    #
    # I have _no_ idea if this will work on other switches!
    #
    my $type = getDeviceType($switch);
199
    my ($snmpversion, $useindexing, $switchtype);
200
    my $cisco_29xx = 0;
201 202
SWITCH:
    for ($type) {
203 204 205 206 207
	(/^cisco/ || /^catalyst/) && do {
            $snmpversion = "2c"; $useindexing = 1; $switchtype = "cisco";
            if ($type =~ /29\d\d/) { DEBUG "Cisco 29xx\n"; $cisco_29xx = 1; }
            last;
        };
208 209 210 211
	(/^intel/) && do { $snmpversion = "1"; $useindexing = 0;
	    $switchtype = "intel"; last;};
	(/^nortel/) && do { $snmpversion = "1"; $useindexing = 0;
	    $switchtype = "nortel"; last;};
212
	(/^hp/) && do { $snmpversion = "2c"; $useindexing = 0;
213
	    $switchtype = "hp"; last;};
214 215
	(/^foundry/) && do { $snmpversion = "1"; $useindexing = 0;
	    $switchtype = "foundry"; last;};
216 217 218

	warn "WARNING: Switch type $type is not supported for $switch!\n";
	next SWITCHLOOP;
219 220
    }

221

222 223 224 225 226 227 228
    #
    # Get the community string for this switch
    #
    my $community = "public";
    if ($MASTER_COMMUNITY) {
	$community = $MASTER_COMMUNITY;
    }
229

230
    my $stack = getSwitchPrimaryStack($switch);
231 232 233 234 235 236 237 238 239 240 241
    if (!$stack) {
	die "No stack found for switch $switch\n";
    }
    my $stack_community = (getStackType($stack))[3];
    if ($stack_community) {
	$community = $stack_community;
    }

    DEBUG "Decided on community $community";
    
    #
242 243
    # Get a list of VLANS from the switch - we'll need them later. But, only
    # for some types of switches.
244
    #
245 246 247
    my @vlanList;
    my $device;
    if ($useindexing) {
248
	$device = new snmpit_cisco($switch,$debug,$community);
249
	@vlanList = ([1,1,[]],$device->listVlans());
250 251 252 253 254
    } else {
	#
	# Make up a fake VLAN, just so we get into the loop below
	#
	@vlanList = ([0,0,[]]);
255 256 257
	if ($switchtype eq "foundry") {
	    $device = new snmpit_foundry($switch,$debug,$community);
	}
258 259 260
	if ($switchtype eq "nortel") {
	    $device = new snmpit_nortel($switch,$debug,$community);
	}
261 262 263
	if ($switchtype eq "hp") {
	    $device = new snmpit_hp($switch,$debug,$community);
	}
264
    }
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

    #
    # Loop through all VLANs - we have to start a new session for each one.
    #
    foreach my $vlan (@vlanList) {

	my ($vlan_id, $vlan_number, $memberref) = @$vlan;
	DEBUG "Looking at VLAN $vlan_number\n";

	#
	# We have to start a new session every time, because - get this - the
	# community string we use affects which VLAN we see MACs for. How sick
	# is that?! (This abomination, BTW, is called 'Community String
	# Indexing')
	#
280 281 282 283 284 285 286 287
	my $thiscommunity;
	if ($useindexing) {
	    $thiscommunity = "$community\@$vlan_number";
	} else {
	    $thiscommunity = $community;
	}
	my $session = new SNMP::Session(DestHost => $switch,
		Version => "$snmpversion", Community => "$thiscommunity");
288
	if (!$session) {
289
	    die "Unable to open session to $switch $thiscommunity\n";
290 291 292 293 294
	}

	#
	# Walk the table that contains the MACs for this VLAN
	#
295 296 297 298 299 300 301 302 303 304 305 306
	my $rows;
	if ($snmpversion eq "2c") {
	    ($rows) = $session->bulkwalk(0,32,["dot1dTpFdbTable"]);
	} else {
	    my $oid = ["dot1dTpFdbTable",0];
	    $session->get($oid);
	    while ($$oid[0] =~ /^dot1dTpFdb/) {
		push @$rows, [@$oid];
		$session->getnext($oid);
	    }
	}

307 308 309 310
	my %MACs;
	my %interfaces;
	my %bridgeports;
	my %status;
311 312 313 314 315 316
	my $firsttime = 1;

	#
	# What we loop on here depends on whether we're using bulkwalk with
	# v2c, or the old, slow, getnext() walking with version 1
	#
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
	foreach my $rowref (@$rows) {
	    my ($oid, $index, $value) = @$rowref;

	    #
	    # Convert the index into something perl is more comfortable with
	    #
	    $index = unpack("H*",$index);

	    SWITCH: for ($oid) {
		/^dot1dTpFdbAddress/ && do {
		    #
		    # This is a MAC - we need to move it from a binay string to
		    # a set of octets
		    #
		    my $MAC = unpack("H*",$value);

		    #
		    # Check to see if this MAC is in the database
		    #
		    my $res = DBQueryFatal("select node_id, iface from " .
			"interfaces where mac ='$MAC'");
		    my $interface;
		    if (!$res->num_rows()) {
			$interface = "unknown";
		    } else {
			my ($node_id, $iface) = $res->fetchrow();
			$interface  = "$node_id:$iface";
		    }

		    $MACs{$index} = $MAC;
		    $interfaces{$index} = $interface;
		    DEBUG "Got MAC $MAC (index $index)\n";
		    last SWITCH;
		};
		/^dot1dTpFdbPort/ && do {
		    #
		    # Just record for later use
		    #
		    $bridgeports{$index} = $value;
		    DEBUG "Got port $value (index $index)\n";
		    last SWITCH;
		};
		/^dot1dTpFdbStatus/ && do {
		    #
		    # Just record for later use
		    #
363
		    DEBUG "Got status $value (index $index)\n";
364 365 366 367 368 369 370 371 372 373 374 375 376 377
		    $status{$index} = $value;
		    last SWITCH;
		};

	    } # SWITCH

	}

	#
	# So many layers of indirection! Get the table that maps port numbers
	# returned by the BRIDGE-MIB to the REAL ifIndices!
	#
	my %realports;
	if (keys %MACs) {
378 379 380 381 382 383 384 385 386 387 388
	    my $rows;
	    if ($snmpversion eq "2c") {
		($rows) = $session->bulkwalk(0,32,["dot1dBasePortIfIndex"]);
	    } else {
		my $oid = ["dot1dBasePortIfIndex",0];
		$session->get($oid);
		while ($$oid[0] =~ /^dot1dBasePortIfIndex/) {
		    push @$rows, [@$oid];
		    $session->getnext($oid);
		}
	    }
389 390 391 392 393 394 395 396 397 398 399 400 401
	    my %ifIndexMap;
	    foreach my $rowref (@$rows) {
		my ($oid, $index, $value) = @$rowref;
		$ifIndexMap{$index} = $value;
		DEBUG "Put $index => $value into \%ifIndexMap\n";
	    }

	    #
	    # Ask the snmpit module to convert the ifIndex to
	    # module.port format for us
	    #
	    foreach my $index (keys %bridgeports) {
		my $bridgeport = $bridgeports{$index};
402 403 404 405 406 407 408 409 410 411 412
                
                #
                # Funny special case for cisco 29xx series - it doesn't need
                # to go throug the map!
                #
		my $ifIndex;
                if ($cisco_29xx) {
                    $ifIndex = $bridgeport;
                } else {
                    $ifIndex = $ifIndexMap{$bridgeport};
                }
413
		if (!$ifIndex) {
414 415 416 417 418 419 420 421 422 423
			DEBUG "ifIndex conversion failed for $bridgeport!\n";
			next;
		}

		#
		# If the device is a Cisco, we have to convert ifindex to a
		# module.port number - for now, the other switches we support
		# have only one module, and require no ifindex conversion.
		#
		my $modport;
424
		if (($switchtype eq "cisco") || ($switchtype eq "foundry") ||
425
		    ($switchtype eq "hp") || ($switchtype eq "nortel")) {
Robert Ricci's avatar
Robert Ricci committed
426
		    ($modport) = $device->convertPortFormat(2, $ifIndex);
427 428
		} else {
		    $modport = "1.$ifIndex";
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
		}
		my $switchport;
		if ($modport) {
		    $switchport = $switch . "/" . $modport;
		} else {
		    $switchport = $switch . "/ifIndex." . $bridgeport;
		}

		$realports{$index} = $switchport;
	    }
	}

	#
	# Okay, now print them out
	#
	foreach my $index (keys %MACs) {
	    #
	    # We only want to see learned MAC addresses - not ones internal
	    # to the switch, etc. Also skip ones that we couldn't figure
	    # out a name for - this means they probably came from
	    # off-switch (eg. a trunk port)
	    #
	    DEBUG "printing for index $index\n";
452 453 454 455 456
	    if (!($status{$index} && ($status{$index} eq "learned" || 
		$status{$index} eq "3"))) {
                DEBUG "   Skipping MAC that wasn't learned\n";
                next;
            }
457 458 459 460 461
	    #
	    # As far as I can tell, this is a bug with (at least some versions
	    # of) CatOS - we sometimes get back MACs that are not even in
	    # this vlan, and those end up with an empty $realport
	    #
462 463 464 465 466
	    if ((!$realports{$index}) || ($realports{$index} =~ /ifIndex/)) {
                DEBUG "   Skipping MAC with bad realport ($realports{$index})\n";
                next;
            }

467 468 469 470
            #
            # Skip ports that belong to known trunks - we only want to learn
            # about nodes that are directly connected to each switch
            #
471 472 473 474
            if ($trunks{$realports{$index}}) {
                DEBUG "   Skipping MAC on a trunk\n";
                next;
            }
475

476
	    print "$MACs{$index},$realports{$index},$vlan_number,". 
Leigh Stoller's avatar
Leigh Stoller committed
477
		"$interfaces{$index},$class_str\n";
478 479 480
	}
    }
}