Skip to content

Instantly share code, notes, and snippets.

@JohnMertz
Created April 10, 2020 11:30
Show Gist options
  • Save JohnMertz/d6515a274e941998602ae43e28b382e2 to your computer and use it in GitHub Desktop.
Save JohnMertz/d6515a274e941998602ae43e28b382e2 to your computer and use it in GitHub Desktop.
Script to get network interfaces as nested hashes
#!/usr/bin/perl
use strict;
use warnings;
my $addr = `ip addr`;
my %links;
my $current;
foreach (split '\n', $addr) {
if ($_ =~ m/^\d+:/) {
$current = $_;
$current =~ s/\d+: ([^:]+):.*/$1/;
$links{$current} = { 'status' => 'down' };
$_ =~ s/^[^<]*<([^>]*)>.*/$1/;
foreach my $i (split ',', $_) {
if ($i eq 'UP') {
$links{$current}{status} = 'up';
}
}
} elsif ($_ =~ m/^\ +link/) {
$_ =~ s/^\ +link\///;
$_ =~ s/\ +$//;
my $bl;
if ($_ =~ m/\ /) {
($links{$current}{type}, $links{$current}{mac}, $bl, $links{$current}{brd}) = split '\ ', $_;
} else {
$links{$current}{type} = $_;
}
} elsif ($_ =~ m/ inet /) {
$_ =~ s/ +inet (\d+\.\d+\.\d+\.\d+)[ \/].*/$1/;
$links{$current}{ip4} = $_;
} elsif ($_ =~ m/ inet6 /) {
$_ =~ s/ +inet6 (:*([0-9a-f]{4}::?)*[0-9a-f]+)\/.*/$1/;
$links{$current}{ip6} = $_;
}
}
if (defined $links{tun0}) {
open my $fh, '<', "/etc/openvpn/openvpn.log";
while (<$fh>) {
if ($_ =~ m/^\[/) {
$links{tun0}{name} = $_;
}
}
close $fh;
chomp $links{tun0}{name};
$links{tun0}{name} =~ s/\[([^\]]+)\].*/$1/;
}
use Data::Dump;
print Data::Dump::dump \%links;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment