#!/bin/perl
# @(#)getorgasn2.pl v2.0 09 MAY 2003 Rob Thomas
# Credit to Mattias Ahnberg for the ASN -> AS-NAME translation
# piece.
#
# Usage:  ./getorgasn2.pl <INPUTFILE> <OUTPUTFILE>
#

use Net::Telnet::Cisco;

# Replace ROUTER with the resolveable hostname or IP address of
# your route-server or BGP-speaking router.
my $router = Net::Telnet::Cisco->new( Host => 'ROUTER' );

# Replace LOGIN and PASSWORD with the local, TACACS+, or RADIUS
# login on the route-server or BGP-speaking router.
my $ret_val = $router->login( 'LOGIN', 'PASSWORD');

# Replace ROUTER with the name or IP of your route-server or
# BGP-speaking router.
unless( $ret_val ) {
	die "Can't access ROUTER.\n";
}

open(OUTPUT, "> $ARGV[1]") or
	die "ERROR opening $ARGV[1]: $!\n";

open(PREFIXES, "< $ARGV[0]") or
	die "ERROR opening $ARGV[0]: $!\n";

# Thanks to Mattias for this bit.  :)
# asnames.txt comes from <http://bgp.potaroo.net/as1221/asnames.txt>
open(ASFILE, "< asnames.txt") or
	warn "Can not open asnames.txt: $!\n";

while (<ASFILE>) {
	/AS(\d+?) (.*)/;
	$as{$1} = "$2";
}

close(ASFILE);

$path_num = 0;

@cmd_output = $router->cmd( 'term len 0' );

while (<PREFIXES>) {
	chomp;

	if (!/^#/) {
	# Modify the $prefix value based on the fields in the file.  The
	# split command will handle it nicely.  Remember to modify the
	# printf(OUTPUT ...) as well.
	#   ($prefix, $port, $type) = split /:/;
		$prefix = $_;
		@cmd_output = $router->cmd( "sh ip bgp $prefix" );

		foreach (@cmd_output) {
			chomp;
		
			# Insert a single ASN of a well-connected peer in place
			# of PEER.  Alternately you can cycle through all peers,
			# but this produces redundant output.  If you do that,
			# run the output file through sort -n | uniq before
			# sharing it.  :)
			if ($_ =~ /^  PEER /) {
				($asn_path) = split /:/;
			    $asn_path =~ s/^  //;
			    $asn_path =~ s/, \(aggre..*//;
			    @asn_len = split(/ /, $asn_path);
			    $source_asn = $asn_len[$#asn_len];
				printf(OUTPUT "%-5.5s %-15s   (%s)\n", $source_asn, $prefix, $as{$source_asn});
			    $path_num++;
			}
		}
	}
}

$router->close;
exit;

