AdguardTeam / AdGuardHome

Network-wide ads & trackers blocking DNS server
https://adguard.com/adguard-home.html
GNU General Public License v3.0
25.1k stars 1.8k forks source link

Backup DHCP leases like PiHole #5265

Open thedevstone opened 1 year ago

thedevstone commented 1 year ago

Prerequisites

Description

What problem are you trying to solve?

Now the leases are somehow encrypted into leases.db. Cannot read IP and hostname and don't know if a backup will function

Proposed solution

Save DHCP leases in yaml file

jeeftor commented 1 year ago

https://github.com/AdguardTeam/AdGuardHome/blob/fffa6567585324834eff781a3ddfa4026de3e301/internal/dhcpd/db.go#L175

It looks like they are just converted from strings to binary if i had to guess

thedevstone commented 1 year ago

Backup and restore of DHCP config and leases:

Get DHCP config and leases

import json

import requests
import yaml
from requests import Response

if __name__ == '__main__':
    STATIC_LEASES_FILE = "static-leases.yaml"
    DHCP_CONFIG_FILE = "dhcp-config.yaml"

    url = "http://192.168.1.1:8083/control/dhcp/status"

    headers = {
        'Accept': '*/*',
        'Content-Type': 'application/json',
        'Authorization': 'Basic blablablageneratedbyPostMan'
    }

    response: Response = requests.request("GET", url, headers=headers)
    response: dict = json.loads(response.text)
    static_leases: list = response.pop("static_leases")
    leases: list = response.pop("leases")
    config: dict = response
    with open(STATIC_LEASES_FILE, "w") as static_leases_file:
        yaml.dump(static_leases, static_leases_file)
    with open(DHCP_CONFIG_FILE, "w") as dhcp_config_file:
        yaml.dump(response, dhcp_config_file)

Restoring DCHP config and leases

import requests
import json

import yaml

if __name__ == '__main__':
    STATIC_LEASES_FILE = "static-leases.yaml"
    DHCP_CONFIG_FILE = "dhcp-config.yaml"

    headers = {
        'Accept': '*/*',
        'Content-Type': 'application/json',
        'Authorization': 'Basic blablablageneratedbyPostMan'
    }

    add_static_lease_url = "http://192.168.1.1:8083/control/dhcp/add_static_lease"
    with open(STATIC_LEASES_FILE, "r") as f:
        loaded_leases = yaml.load(f, Loader=yaml.FullLoader)
        for lease in loaded_leases:
            response = requests.request("POST", add_static_lease_url, headers=headers, data=json.dumps(lease))
            if response.status_code == 200:
                print(f"Added lease: {lease}")
    set_config_url = "http://192.168.1.100:8083/control/dhcp/set_config"
    with open(DHCP_CONFIG_FILE, "r") as f:
        dhcp_config = yaml.load(f, Loader=yaml.FullLoader)
        response = requests.request("POST", set_config_url, headers=headers, data=json.dumps(dhcp_config))
        if response.status_code == 200:
            print(f"Configuration updated")

Hope it will help someone

mikeeq commented 1 year ago

Related to: https://github.com/AdguardTeam/AdGuardHome/issues/1700