summaryrefslogtreecommitdiff
path: root/admin-tools/dhcpremember.pl
blob: 6e9abc8ce171b2cc246406f98989b02a70063872 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env perl
#
# Generates static mapping commands from the DHCP leases op mode command output
#
# On VyOS and Vyatta, invoke like "run show dhcp server leases | /config/scripts/dhcpremember.pl"
# On EdgeOS, invoke like "run show dhcp leases | /config/scripts/dhcpremember.pl"
#
# Copyright (C) 2014 Daniil Baturin
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#

use lib "/opt/vyatta/share/perl5/";

use strict;
use warnings;
use Vyatta::Config;
use NetAddr::IP;

my $config = new Vyatta::Config();

while(<>)
{
    # skip headers
    if( $_ !~ /\d\.?/ )
    {
        next;
    }

    # Lease line format: <IPv4> <MAC> <Lease time> <Pool> <Client name>    
    my @values = split /\s+/, $_;
    my $ip = $values[0];
    my $mac = $values[1];
    my $pool = $values[4];
    my $client = undef;
    
    # Client name may not be present
    if( defined($values[5]) )
    {
        $client = $values[5];
    }
    else
    {
        $client = $ip;
    }
    my $subnet = "CHANGME"; # For the case it isn't detected from the config
   
    # Get subnet for the pool
    my @subnets = $config->listNodes("service dhcp-server shared-network-name $pool subnet");
    my $ip_object = new NetAddr::IP("$ip/32");
    foreach my $subnet_str (@subnets)
    {
        my $subnet_object = new NetAddr::IP($subnet_str);
        if( $ip_object->within($subnet_object) )
        {
            $subnet = $subnet_str;
        }
    }
    
    $client = $ip unless defined($client);
    
    print "set service dhcp-server shared-network-name $pool subnet $subnet static-mapping $client ip-address $ip\n";
    print "set service dhcp-server shared-network-name $pool subnet $subnet static-mapping $client mac-address $mac\n";
}