| 1 |
#! /usr/bin/perl |
| 2 |
|
| 3 |
# print only new MAC addresses, which are not yet known |
| 4 |
# (c) Thomas Lange, 2007-2018 |
| 5 |
|
| 6 |
# fai-new-mac -tad |
| 7 |
# tcpdump -pnlqte udp and src port bootpc and broadcast | fai-new-mac |
| 8 |
|
| 9 |
# -a add arp entries to list of known MAC addresses |
| 10 |
# -d add dhcpd entries to list of known MAC addresses |
| 11 |
# -t read from tcpdump. If not given, read from stdin |
| 12 |
# -p <pattern> only print MACs matching the pattern |
| 13 |
|
| 14 |
use strict; |
| 15 |
use Getopt::Std; |
| 16 |
|
| 17 |
my $filename="/var/lib/fai/known-mac-addresses"; |
| 18 |
my $dhcpdconf="/etc/dhcp/dhcpd.conf"; |
| 19 |
my %mac; |
| 20 |
$|=1; |
| 21 |
|
| 22 |
our($opt_a,$opt_d,$opt_p,$opt_t,$opt_i); |
| 23 |
|
| 24 |
sub read_known_macs { |
| 25 |
|
| 26 |
-f $filename || return; |
| 27 |
open (IN,"$filename") or die "Can't read file with known MAC addresses\n"; |
| 28 |
while (<IN>) { |
| 29 |
chomp; |
| 30 |
$mac{$_}=1; |
| 31 |
} |
| 32 |
close IN; |
| 33 |
} |
| 34 |
|
| 35 |
sub read_arp { |
| 36 |
|
| 37 |
open (ARP,"ip neigh list|") || die "Can't read arp list. $!\n"; |
| 38 |
while (<ARP>) { |
| 39 |
append_new_mac($1,"MAC found in ARP list") if /laddr (([0-9a-f]{2}:){6}) /i |
| 40 |
} |
| 41 |
close ARP; |
| 42 |
} |
| 43 |
|
| 44 |
sub read_dhcpd { |
| 45 |
|
| 46 |
-f $dhcpdconf || return; |
| 47 |
open(DHCP,"$dhcpdconf") || die "Can't read $dhcpdconf. $!\n"; |
| 48 |
while (<DHCP>) { |
| 49 |
append_new_mac($1,"mac found in dhcpd.conf") if /hardware ethernet\s+(([0-9a-f]{1,2}:){5}[0-9a-f]{1,2})/i; |
| 50 |
} |
| 51 |
close DHCP; |
| 52 |
} |
| 53 |
|
| 54 |
sub append_new_mac { |
| 55 |
|
| 56 |
my ($newmac,$msg) = @_; |
| 57 |
|
| 58 |
return if defined $mac{$newmac}; |
| 59 |
$mac{$newmac}=1; |
| 60 |
if ($opt_p) { |
| 61 |
print "$msg $newmac\n" if $newmac =~ /$opt_p/i; |
| 62 |
} else { |
| 63 |
print "$msg $newmac\n"; |
| 64 |
} |
| 65 |
open (OUT,">>$filename") or die "Can't append to file with old MAC addresses\n"; |
| 66 |
print OUT "$newmac\n"; |
| 67 |
close OUT; |
| 68 |
} |
| 69 |
|
| 70 |
sub read_from_tcpdump { |
| 71 |
|
| 72 |
my $newmac; |
| 73 |
if ($opt_t) { |
| 74 |
open (TCPDUMP,"tcpdump $opt_i -pnlqte udp and src port bootpc and broadcast|") || die "Can't read from tcpdump. $!\n"; |
| 75 |
} else { |
| 76 |
open (TCPDUMP,"-") || die "$!\n"; |
| 77 |
} |
| 78 |
|
| 79 |
while (<TCPDUMP>) { |
| 80 |
next if /^tcpdump:/; |
| 81 |
next if /^listening /; |
| 82 |
$newmac=(split)[0]; |
| 83 |
append_new_mac($newmac,"NEW"); |
| 84 |
} |
| 85 |
close TCPDUMP; |
| 86 |
} |
| 87 |
|
| 88 |
sub usage {exit;} |
| 89 |
|
| 90 |
getopts('atdp:i:') || usage(); |
| 91 |
|
| 92 |
$opt_i and $opt_i="-i $opt_i"; |
| 93 |
read_known_macs(); |
| 94 |
$opt_d && read_dhcpd(); |
| 95 |
$opt_a && read_arp(); |
| 96 |
read_from_tcpdump(); |