Rev 128 | Blame | Last modification | View Log | Download | RSS feed
#! /usr/bin/env perl
# take persistent storage created by mapSwitches.pl and dump entries
# to a tab delimited text file on STDOUT.
# v1.2 RWR 20200228
# added description field
use strict;
use warnings;
use File::Spec; # find location of script so we can put storage in same directory
use File::Basename;
use YAML::Tiny; # apt-get libyaml-tiny-perl under debian
use POSIX qw( strftime ); # to convert timestamp to something readable
our $VERSION = '1.2';
# where the script is located
my $scriptDir = dirname( File::Spec->rel2abs( __FILE__ ) );
# put the statefile in there
my $STATEFILE = $scriptDir . '/mapSwitches.yaml';
my $tsvFileName = 'mapswitches.tsv';
my %switchports;
# pretty up the MAC addresses by inserting colons between
# every pair of numbers
sub prettyMAC {
my $mac = shift;
my @mac = ( $mac =~ m/../g );
return join( ':', @mac );
}
# change the Unix timestamp into yyyy-mm-dd hh:mm:ss
sub prettyTime {
my $time = shift;
return '' unless $time;
return strftime '%Y-%m-%d %H:%M:%S', localtime( $time );
}
sub dumpLine {
my $startTag = shift;
my $endTag = shift;
# read in values, defaulting to empty string if undef
my @values = map{ $_ ? $_ : '' } @_;
return "<tr>$startTag" . join( $endTag . $startTag, @values ) . "$endTag</tr>\n";
}
# read the saved state into memory if it exists
die "no state file found, looking at $STATEFILE\n" unless -e $STATEFILE;
# get the delimiter and the encapsulation chars
my $delimiter = shift;
my $encapsulate = shift;
# default to tab delimited, no encapsulation if none entered
$delimiter = "\t" unless $delimiter;
$encapsulate = '' unless $encapsulate;
my $yaml = YAML::Tiny->read( $STATEFILE );
%switchports = %{ $yaml->[0] };
print "<html>\n<body>\n";
print "<h1>MapSwitches</h1><h2>Generated: " . &prettyTime(time) . "</h2>\n";
print "<table border='1'>\n";
foreach my $switch ( sort keys %switchports ) {
print "<tr><td colspan='8' align='center'>$switchports{$switch}{'name'} Located at $switchports{$switch}{'location'}</td></tr>\n";
# print the header
print &dumpLine( '<th>', '</th>', 'Switch','Port','Alias','Description','MAC','IP','Host Name','Last Seen' );
foreach my $port ( sort {$a<=>$b} keys %{$switchports{$switch}{'ports'}} ) {
foreach my $connection ( keys %{$switchports{$switch}{'ports'}{$port} } ) {
next if $connection eq 'alias' or $connection eq 'description';
print &dumpLine ( '<td>', '</td>',
$switch,
$port,
$switchports{$switch}{'ports'}{$port}{'alias'},
$switchports{$switch}{'ports'}{$port}{'description'},
&prettyMAC( $switchports{$switch}{'ports'}{$port}{$connection}{'mac'}),
$switchports{$switch}{'ports'}{$port}{$connection}{'ip'},
$switchports{$switch}{'ports'}{$port}{$connection}{'hostname'},
&prettyTime( $switchports{$switch}{'ports'}{$port}{$connection}{'lastseen'} )
) ;
}
}
print "</table>\n<p align='center'><a href='$tsvFileName'>Download as Tab Delimited</a></p></body>\n</html>\n";
}
1;