Skip to content

Instantly share code, notes, and snippets.

@mortn
Created March 11, 2025 18:40
Show Gist options
  • Save mortn/b0a4cacf37038b728c7a7d8514d55e0e to your computer and use it in GitHub Desktop.
Save mortn/b0a4cacf37038b728c7a7d8514d55e0e to your computer and use it in GitHub Desktop.
Show current DHCP leases for all interfaces when using systemd networkd as DHCP server
#!/usr/bin/env python3
import json
from os import listdir, path
from datetime import datetime
# this is the default path on Debian-based distros
DHCP_DIR = '/var/lib/systemd/network/dhcp-server-lease'
def main():
lfiles = [path.join(DHCP_DIR,lf) for lf in listdir(DHCP_DIR)]
for lfile in lfiles:
print_file(lfile)
def print_file(lfile):
# Read the JSON file
with open(lfile, 'r') as file:
data = json.load(file)
# Extract and print the HardwareAddress in hexadecimal
for lease in data.get('Leases', []):
address = '.'.join(map(str, lease.get('Address', [])))
hostname = lease.get('Hostname', 'N/A')[:18]
expire_usec = lease.get('ExpirationRealtimeUSec', 'N/A') / 1000000
expiration = datetime.fromtimestamp(expire_usec).strftime('%y-%m-%d %H:%M:%S')
hardware_address = lease.get('HardwareAddress', [])[:6]
hex_address = ':'.join(f'{value:02x}' for value in hardware_address)
print(f"{address} {hostname:<15} \t {hex_address:<18} \t {expiration}")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment