Skip to content

Instantly share code, notes, and snippets.

@sykesm
Last active April 22, 2022 07:59
Show Gist options
  • Save sykesm/245162bbef3d92895e69566730d6a04a to your computer and use it in GitHub Desktop.
Save sykesm/245162bbef3d92895e69566730d6a04a to your computer and use it in GitHub Desktop.
Transform dnsmasq leases to ISC lease file format.
#!/usr/bin/perl
use NetAddr::IP;
use POSIX qw(strftime);
my $dnsmasq_leases_path = '/var/run/dnsmasq-dhcp.leases';
my $dhcpd_leases_path = '/var/run/dhcpd.leases';
my $network_names_path = '/opt/vyatta/config/active/service/dhcp-server/shared-network-name';
my %networks_by_subnet;
opendir(my $dhcp_networks, $network_names_path) or die;
while (my $net_name = readdir $dhcp_networks) {
next if ($net_name =~ m/^\./);
my $subnets_path = "$network_names_path/$net_name/subnet";
next unless -d $subnets_path;
opendir(my $subnets, $subnets_path) or die;
while (my $subnet = readdir $subnets) {
next if ($subnet =~ m/^\./);
$subnet =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
my $nw = NetAddr::IP->new($subnet);
$networks_by_subnet{$nw} = $net_name;
}
closedir($subnets);
}
closedir($dhcp_networks);
open(my $dnsmasq_leases, '<', $dnsmasq_leases_path) or die;
open(my $dhcpd_leases, '>', $dhcpd_leases_path) or die;
while (my $lease = <$dnsmasq_leases>) {
chomp $lease;
my ($expiry, $mac, $ip, $hostname, $client_id) = split(' ', $lease);
$expiry = strftime("%w %Y/%m/%d %H:%M:%S", gmtime($expiry));
my $nw = undef;
my $ipAddr = NetAddr::IP->new($ip);
while (my ($subnet, $network_name) = each %networks_by_subnet) {
$subnet = NetAddr::IP->new($subnet);
$nw = $network_name if $ipAddr->within($subnet);
}
my $dhcpd_record = <<"END_RECORD";
lease $ip {
ends $expiry;
binding state active;
next binding state free;
hardware ethernet $mac;
client-hostname "$hostname";
#shared-network: $nw
}
END_RECORD
print $dhcpd_leases $dhcpd_record;
}
close $dnsmasq_leases;
close $dhcpd_leases;
@rohoog
Copy link

rohoog commented May 3, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment