Skip to content
maraventoPublic

Latest commit

 

History

54 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

status-maintained last commit Stargazers Twitter Follow

isc-dhcp-server reached end of life in 2022, leaving those who administer it on local networks without a direct path to migrate their configurations without reengineering.

The most popular alternatives are Kea (also developed by ISC) and dnsmasq. Both use their own syntax and lease formats that differ from those of ISC DHCP. As a result, they cannot directly reuse existing files: migration requires translating configurations and adapting both the administration workflow and the scripts that depend on those formats.

PyDHCP proposes an intermediate open-source solution for IPv4 local networks: it retains part of the configuration syntax and lease-file format of ISC DHCP to facilitate migration and incorporates local DNS resolution through Unbound, a capability also available in dnsmasq and additionally automates DHCP assignments from access control lists (ACLs) and includes per-client allocation controls and configuration backups.

isc-dhcp-server alcanzó el fin de su ciclo de vida en 2022, dejando a quienes lo administran en redes locales sin una ruta directa para migrar sus configuraciones sin hacer reingeniería.

Las alternativas más populares son Kea (desarrollado también por ISC) y dnsmasq. Ambos utilizan sintaxis propias y formatos de concesiones distintos a los de ISC DHCP. Por ello, no permiten reutilizar directamente los archivos existentes: la migración requiere traducir las configuraciones y adaptar tanto el flujo de administración como los scripts que dependan de esos formatos.

PyDHCP propone una solución intermedia de código abierto para redes locales IPv4: conserva parte de la sintaxis de configuración y del formato de concesiones de ISC DHCP para facilitar la migración e incorpora resolución DNS local mediante Unbound, una capacidad presente también en dnsmasq y, adicionalmente, automatiza las asignaciones DHCP a partir de listas de control de acceso (ACL) e incluye controles de asignación por cliente y respaldos de configuración.

REQUIREMENTS


Compatibility

Only tested on Ubuntu 24.04/26.04 LTS. Other versions or distributions are not tested and are used at your own risk.

Solo probado en Ubuntu 24.04/26.04 LTS. Otras versiones o distribuciones no están probadas y se usan bajo tu responsabilidad.

Network

Installation and update require the following:

  • Required interfaces must have an UP link and configured global IPv4.
  • Internet access is required when installing or updating packages and downloading components.
  • The selected LAN IPv4 must be static and persistent.

The operation continues if the applicable requirements above are met; otherwise, it aborts.

La instalación y actualización requieren lo siguiente:

  • Las interfaces requeridas deben tener enlace UP e IPv4 global configurada.
  • Se requiere Internet para instalar o actualizar paquetes y descargar componentes.
  • La IPv4 LAN seleccionada debe ser estática y persistente.

La operación continúa si se cumplen los requisitos anteriores que correspondan; de lo contrario, aborta.

Software

Component Requirements Requisitos
Daemon Python 3.8+ and systemd Python 3.8+ y systemd
Installer packages python3-yaml, python3, systemd, iproute2, passwd, util-linux, coreutils, grep, sed, iputils-ping, findutils, libc-bin, logrotate, curl, zip, cron, perl, ncurses-bin, unbound, openssl, diffutils. --install and --update install the missing ones --install y --update instalan los paquetes que falten
Awk A POSIX-compatible awk command must be available before installation and tool execution; no implementation is imposed Debe existir un comando awk compatible con POSIX antes de instalar o ejecutar herramientas; no se impone una implementación
Optional WPAD apache2, apache2-bin, apache2-data, apache2-doc, apache2-utils; the installer installs missing packages apache2, apache2-bin, apache2-data, apache2-doc, apache2-utils. El instalador instala los paquetes ausentes
Optional Webmin module Webmin, Perl and ncurses-bin, in addition to the shared command dependencies Webmin, Perl y ncurses-bin, además de las dependencias de comandos compartidas

REPOSITORY STRUCTURE


pydhcp/                           # deployed to: /etc/pydhcp [1770 root:pydhcpd]
├── pydhcp.env                    # generated configuration [0640 root:pydhcpd]
├── acl/                          # PyDHCP-managed ACLs [0700 root:root]
│   └── blockdhcp.txt             # blocked MAC addresses [0600 root:root]
├── conf/
│   ├── forward.conf              # deployed to: /etc/unbound/unbound.conf.d/forward.conf [0644 root:root]
│   └── wpad.conf                 # deployed to: /etc/apache2/sites-available/wpad.conf [0644 root:root]
├── core/                         # DHCP daemon and state [1770 root:pydhcpd]
│   ├── pydhcpd.py                # IPv4 DHCP daemon [0755 root:root]
│   ├── pydns.py                  # essential DHCP/DNS synchronization [0750 root:root]
│   ├── pydhcpd.conf              # daemon configuration [0640 root:pydhcpd]
│   └── pydhcpd.leases            # generated DHCP leases [0640 pydhcpd:pydhcpd]
├── init.d/
│   └── pydhcpd                   # deployed to: /etc/init.d/pydhcpd [0750 root:root]
├── service/
│   ├── pydhcp-dns.service        # DNS publisher, deployed to /etc/systemd/system [0644 root:root]
│   ├── pydhcp-dns.path           # deployed to /etc/systemd/system; change watcher [0644 root:root]
│   ├── pydhcp-dns.timer          # deployed to /etc/systemd/system; reconciliation [0644 root:root]
│   └── pydhcpd.service           # deployed to: /etc/systemd/system/pydhcpd.service [0644 root:root]
├── tools/                        # administrative tools [0755 root:root]
│   ├── pydhcpenv.sh              # shared Bash configuration reader [0644 root:root]
│   ├── pybk.sh                   # configuration backup [0750 root:root]
│   ├── pyleases.sh               # reconciles DHCP leases and ACLs [0750 root:root]
│   └── pywebmin.sh               # optional Webmin installer [0750 root:root]
└── pysetup.sh                    # installer, updater and uninstaller

Additional Installed Paths

etc/
├── acl/                          # administrator-managed MAC lists [0700 root:root]
│   ├── mac-limited.txt           # limited clients [0600 root:root]
│   └── mac-unlimited.txt         # unlimited clients [0600 root:root]
├── apache2/
│   └── sites-enabled/
│       └── wpad.conf             # link to ../sites-available/wpad.conf [0777 root:root]
├── bak/
│   └── pydhcp                    # configuration backups [0700 root:root]
├── cron.d/
│   ├── pydhcp                    # scheduled tasks [0644 root:root]
│   └── pydhcp.lock               # cron writer lock [0600 root:root]
├── default/
│   └── unbound                   # daemon options written by the installer
├── logrotate.d/
│   └── pydhcp                    # log rotation policy [0644 root:root]
├── systemd/system/
│   ├── pydhcpd.service           # DHCP service [0644 root:root]
│   ├── pydhcp-dns.service        # DNS name publication [0644 root:root]
│   ├── pydhcp-dns.path           # lease/config change watcher [0644 root:root]
│   └── pydhcp-dns.timer          # reconciliation after five seconds of inactivity [0644 root:root]
└── unbound/
    └── unbound.conf.d/
        └── forward.conf         # active DNS configuration [0644 root:root]

var/
├── lib/
│   └── pydhcp-dns/               # publication state [0700 root:root]
│       ├── publish.lock          # serializes configuration and name publication
│       └── records.json          # records owned by pydns.py
├── log/
│   └── pydhcp.log                # shared DHCP log [0640 pydhcpd:pydhcpd]
└── www/
    └── wpad/                     # optional WPAD document root [0755 www-data:www-data]
        └── wpad.pac              # generated proxy configuration [0644 www-data:www-data]

HOW TO USE


git clone --depth=1 https://github.com/maravento/pydhcp.git
cd pydhcp

# Install
sudo bash pysetup.sh --install

# Update
sudo bash pysetup.sh --update

# Uninstall
sudo bash pysetup.sh --uninstall

# Status
sudo bash pysetup.sh --status

# Interactive menu
sudo bash pysetup.sh

# Help
sudo bash pysetup.sh --help   # or -h
Action Description Descripción
sudo bash pysetup.sh Opens the interactive menu Abre el menú interactivo
sudo bash pysetup.sh --install Installs pydhcp. Aborts if already installed Instala pydhcp. Aborta si ya está instalado
sudo bash pysetup.sh --update Updates the code and preserves the user configuration Actualiza el código y conserva la configuración del usuario
sudo bash pysetup.sh --uninstall Removes pydhcp, with two confirmations up front Elimina pydhcp, con dos confirmaciones al inicio
sudo bash pysetup.sh --status Shows service state, UDP 67 listeners, the configured interface and recent log lines. Resets the installer log at startup Muestra el estado del servicio, las escuchas UDP 67, la interfaz configurada y las últimas líneas del log. Vacía el log del instalador al comenzar
sudo bash pysetup.sh -h Shows the usage Muestra el uso

pysetup.sh takes one action per run. Without arguments it opens the interactive menu, with the same four actions and an exit option.

pysetup.sh ejecuta una acción por vez. Sin argumentos abre el menú interactivo, con las mismas cuatro acciones y una opción de salida.

SCOPE


SCOPE ALCANCE
  • DHCPv4 address assignment on one LAN interface and one configured IPv4 subnet, with dynamic pools and static MAC/IP reservations.
  • Lease storage, renewal, release and expiration, with optional ICMP address-conflict checks and a limit on new allocations per MAC.
  • Generation of DHCP configuration from ACL lists: static reservations for authorized entries, a dynamic pool for unknown clients and denial of DHCP assignments to blocked MACs.
  • Advertisement of the local domain through DHCP option 15 and of DNS server addresses through option 6.
  • DNS forwarding through Unbound and automatic publication of local A/PTR records from valid static reservation names and active, unexpired DHCP client names. DHCP and DNS run as separate services.
  • On configuration regeneration, synchronization of Unbound listening addresses, permitted LAN subnet and local domain with pydhcp.env.
  • Optional PAC generation and HTTP hosting through Apache during installation, with URL advertisement through DHCP option 252. The installer checks Apache configuration and the PAC URL response.
  • Configuration backups, including Unbound, and an optional tool for installing the PyDHCP module in an existing Webmin installation.
  • Asignación de direcciones DHCPv4 en una interfaz LAN y una subred IPv4 configuradas, con pools dinámicos y reservas estáticas MAC/IP.
  • Almacenamiento, renovación, liberación y vencimiento de concesiones, con comprobación ICMP opcional de conflictos de direcciones y límite de nuevas asignaciones por MAC.
  • Generación de configuración DHCP desde listas ACL: reservas estáticas para las entradas autorizadas, un pool dinámico para clientes desconocidos y denegación de asignaciones DHCP a las MAC bloqueadas.
  • Anuncio del dominio local mediante la opción DHCP 15 y de las direcciones de servidores DNS mediante la opción 6.
  • Reenvío DNS mediante Unbound y publicación automática de registros A/PTR locales a partir de nombres válidos de reservas estáticas y clientes con concesiones activas y no vencidas. DHCP y DNS funcionan como servicios separados.
  • Al regenerar la configuración, sincronización de las direcciones de escucha de Unbound, la subred LAN permitida y el dominio local con pydhcp.env.
  • Generación opcional del PAC y publicación mediante HTTP con Apache durante la instalación, con anuncio de su URL mediante la opción DHCP 252. El instalador comprueba la configuración de Apache y la respuesta de la URL del PAC.
  • Respaldos de configuración, incluida la de Unbound, y una herramienta opcional para instalar el módulo de PyDHCP en una instalación existente de Webmin.
OUT OF SCOPE FUERA DE ALCANCE
  • DHCPv6, BOOTP/PXE and DHCP service for multiple subnets.
  • LDAP integration, RFC 2136 DNS updates and advertisement of search domains through DHCP option 119.
  • Independent DHCP options for each host or class. DNS server addresses, the local domain and the WPAD URL are shared within the configured subnet.
  • Configuration of host network-interface addresses, routing or router failover, and management of firewall rules or proxy access policies. DHCP ACLs govern address assignment, not network traffic.
  • Automatic PAC regeneration during --update, HTTPS deployment for the PAC server and JavaScript syntax validation of the PAC.
  • DHCPv6, BOOTP/PXE y servicio DHCP para varias subredes.
  • Integración con LDAP, actualizaciones DNS mediante RFC 2136 y anuncio de dominios de búsqueda mediante la opción DHCP 119.
  • Opciones DHCP independientes para cada host o clase. Las direcciones de servidores DNS, el dominio local y la URL WPAD son comunes a la subred configurada.
  • Configuración de direcciones de las interfaces de red del servidor, enrutamiento o conmutación entre routers, y gestión de reglas de firewall o políticas de acceso del proxy. Las ACL de DHCP regulan la asignación de direcciones, no el tráfico de red.
  • Regeneración automática del PAC durante --update, despliegue HTTPS del servidor PAC y validación de la sintaxis JavaScript del PAC.

ISC-DHCP-SERVER VS PYDHCP


Legend: ✅ same behaviour · ⚠️ works, with a difference · ⛔ not implemented

Leyenda: ✅ mismo comportamiento · ⚠️ funciona, con una diferencia · ⛔ no implementado

Protocol and architecture

isc-dhcp-server pydhcp Description Descripción
DHCPv4 (RFC 2131) over UDP 67/68 ✅ Python daemon, same protocol Demonio Python, mismo protocolo
DHCPv6 ⛔ IPv4 only Solo IPv4
Multiple interfaces ⛔ Single interface, set in INTERFACESv4 Interfaz única, definida en INTERFACESv4
BOOTP / PXE ⛔ Packets are padded to the BOOTP minimum for protocol compliance, but BOOTP clients are not served PyDHCP completa los paquetes hasta el tamaño mínimo de BOOTP, pero no atiende a clientes BOOTP
DHCP relay agents ⛔ No legitimate use without multi-segment support. giaddr/hops are parsed only to close a spoofing hole PyDHCP no ofrece servicio de relay. Lee giaddr y hops para detectar y descartar paquetes de relay falsificados
Clients whose chaddr differs from the frame source MAC ⛔ Dropped and logged: closes a spoofing hole PyDHCP descarta y registra los paquetes si la MAC de chaddr no coincide con la MAC de origen Ethernet
LDAP backend ⛔ Host reservations live in pydhcpd.conf, or in the mac-*.txt lists that pyleases.sh turns into reservations Las reservas de host viven en pydhcpd.conf, o en las listas mac-*.txt que pyleases.sh convierte en reservas
DDNS ⛔ No RFC 2136 updates; the core/pydns.py component publishes local records in Unbound Sin actualizaciones RFC 2136; el componente core/pydns.py publica registros locales en Unbound
client-updates / deny client-updates ⛔ Depends on DDNS plus the client FQDN option, neither implemented Depende de DDNS y de la opción FQDN del cliente, ninguna implementada

Directives

isc-dhcp-server pydhcp Description Descripción
authoritative; ✅ pydhcpd's default, accepted for compatibility Es el valor por defecto de pydhcpd, se acepta por compatibilidad
not authoritative; ✅ The only way to disable authoritative mode Única forma de desactivar el modo autoritativo
server-identifier IP; ✅ Mandatory: the daemon refuses to start without it Obligatoria: el demonio no arranca sin ella
cleanup-interval N; ✅ Seconds between expired-lease sweeps Segundos entre barridos de concesiones expiradas
abandon-lease-time N; ✅ Seconds an IP is held out of the pool after a DHCPDECLINE Segundos que una IP queda fuera del pool tras un DHCPDECLINE
deny duplicates; ✅ Re-offers the MAC's existing pool lease on DISCOVER while the first pool admitting that MAC contains it Al recibir DISCOVER, vuelve a ofrecer la concesión vigente del pool si pertenece al primer pool que admite esa MAC
deny declines; ✅ Ignores DHCPDECLINE messages Ignora mensajes DHCPDECLINE
ping-check true|false; ✅ Enabled by default in the shipped config, unlike isc Activado por defecto en la configuración que se entrega, al revés que isc
ping-timeout N; ✅ Seconds to wait for the ICMP reply before sending the OFFER Segundos de espera de la respuesta ICMP antes de enviar el OFFER
subnet ... { pool { ... } } ✅ Several pool { } blocks per subnet are accepted Se aceptan varios bloques pool { } por subred
host NAME { hardware ethernet MAC; fixed-address IP; } ✅ fixed-address validated at config load and on SIGHUP fixed-address se valida al cargar la configuración y en cada SIGHUP
class / subclass / deny members of ✅ Any class name is accepted, not just blockdhcp Se acepta cualquier nombre de clase, no solo blockdhcp
allow|deny unknown-clients, known-clients ✅ Pool-level admission rules Reglas de admisión a nivel de pool
min-lease-time, default-lease-time, max-lease-time ✅ Validated together (0 < min <= default <= max), at subnet and pool level Se validan en conjunto (0 < min <= default <= max), a nivel de subred y de pool
option routers ⚠️ Accepts a comma-separated list but uses only the first address; the rest are ignored with a notice. No failover between routers Acepta varias direcciones separadas por comas, pero entrega solo la primera e informa que ignora las demás. No cambia automáticamente a otro router si el primero falla
option broadcast-address ✅ Served as option 28 Se entrega como opción 28
option domain-name-servers ✅ Comma-separated list, all served Lista separada por comas, se entregan todas
option wpad ...; ✅ Option 252. The daemon serves it whenever the directive is present in pydhcpd.conf; WPAD_ENABLED in pydhcp.env decides whether tools/pyleases.sh writes it when it regenerates the config Opción 252. El demonio la entrega siempre que la directiva esté en pydhcpd.conf; WPAD_ENABLED en pydhcp.env decide si tools/pyleases.sh la escribe al regenerar la configuración
one-lease-per-client ⚠️ Always enforced; one MAC can hold only one pool lease at a time Se aplica siempre: cada MAC puede tener una sola concesión del pool a la vez
option domain-name ✅ Quoted local domain, sent through option 15 Dominio local entre comillas, enviado mediante la opción 15
option domain-search ⛔ Option 119 is not implemented La opción 119 no está implementada
option subnet-mask override ⛔ The netmask sent always matches the subnet ... netmask ... declaration La máscara enviada siempre coincide con la declaración subnet ... netmask ...
Per-host / per-class option scoping ⛔ Options declared at subnet level apply to every client uniformly Las opciones declaradas a nivel subnet aplican a todos los clientes por igual

Files and paths

isc-dhcp-server pydhcp Description Descripción
/etc/dhcp/dhcpd.conf /etc/pydhcp/core/pydhcpd.conf Similar syntax for the supported directives listed above Sintaxis similar para las directivas admitidas indicadas arriba
/var/lib/dhcp/dhcpd.leases /etc/pydhcp/core/pydhcpd.leases Same format Mismo formato
/etc/default/isc-dhcp-server /etc/pydhcp/pydhcp.env Bootstrap values, plus pydhcp's own extras Valores iniciales de configuración, junto con otras variables propias de PyDHCP
/run/dhcp-server/dhcpd.pid /run/pydhcp/pydhcpd.pid Fixed path, not configurable Ruta fija, no configurable
/etc/systemd/system/isc-dhcp-server.service /etc/systemd/system/pydhcpd.service The PyDHCP unit starts the daemon as pydhcpd with its two network capabilities La unidad de PyDHCP inicia el demonio como pydhcpd con sus dos capacidades de red
/etc/init.d/isc-dhcp-server /etc/init.d/pydhcpd Compatible wrapper Wrapper compatible
/var/log/syslog /var/log/pydhcp.log Writes directly to file, does not use syslog, so no log-facility directive is needed Escribe directamente al archivo, no usa syslog, así que no hace falta la directiva log-facility
(none) pysetup.log Installer log, written in the directory containing pysetup.sh and rewritten on each run. Kept out of /var/log/pydhcp.log so install, update and remove runs never mix with daily operation Log del instalador, escrito en el directorio que contiene pysetup.sh y reescrito en cada ejecución. Se mantiene fuera de /var/log/pydhcp.log para que las ejecuciones de instalación, actualización y desinstalación no se mezclen con la operación diaria
(none) pywebmin.log Webmin installer log beside pywebmin.sh, cleared after the root check on each run Log del instalador Webmin junto a pywebmin.sh, vaciado tras comprobar root en cada ejecución
/etc/logrotate.d/rsyslog /etc/logrotate.d/pydhcp Weekly, one config for the whole project Semanal, una sola configuración para todo el proyecto
journalctl -u isc-dhcp-server journalctl -u pydhcpd Both also reach journald through systemd Ambos llegan además a journald a través de systemd

Commands

isc-dhcp-server pydhcp Description Descripción
systemctl start|stop|restart|status isc-dhcp-server systemctl start|stop|restart|status pydhcpd Same verbs, same behaviour Mismos verbos, mismo comportamiento
service isc-dhcp-server start|stop|restart|status service pydhcpd start|stop|restart|status Goes through the init.d wrapper, which delegates to systemctl when systemd is the active init Pasa por el wrapper de init.d, que delega en systemctl cuando systemd es el init activo
dhcpd -t -cf /etc/dhcp/dhcpd.conf pydhcpd.py -t -cf /etc/pydhcp/core/pydhcpd.conf Config syntax test Prueba de sintaxis de la configuración

Log output

isc-dhcp-server pydhcp Description Descripción
DHCPREQUEST for 192.168.0.50 (192.168.0.2) from aa:bb:cc:dd:ee:ff via enpXsX
DHCPACK on 192.168.0.50 to aa:bb:cc:dd:ee:ff (FOO) via enpXsX
REQUEST from aa:bb:cc:dd:ee:ff (FOO)
ACK aa:bb:cc:dd:ee:ff → 192.168.0.50 lease 2592000s
Authorized client with static IP (renewal) Cliente autorizado con dirección IP fija (renovación)
DHCPDISCOVER from bb:cc:dd:ee:ff:aa via enpXsX
DHCPOFFER on 192.168.0.230 to bb:cc:dd:ee:ff:aa (BAR) via enpXsX
DHCPREQUEST for 192.168.0.230 (192.168.0.2) from bb:cc:dd:ee:ff:aa (BAR) via enpXsX
DHCPACK on 192.168.0.230 to bb:cc:dd:ee:ff:aa (BAR) via enpXsX
DISCOVER from bb:cc:dd:ee:ff:aa (BAR)
OFFER bb:cc:dd:ee:ff:aa → 192.168.0.230
REQUEST from bb:cc:dd:ee:ff:aa (BAR)
ACK bb:cc:dd:ee:ff:aa → 192.168.0.230 lease 60s
Unknown client entering the block pool Cliente desconocido ingresando al pool de bloqueo
DHCPDISCOVER from bb:cc:dd:ee:ff:aa via enpXsX: network 192.168.0.0/24: no free leases DISCOVER from bb:cc:dd:ee:ff:aa (BAR)
No IP for bb:cc:dd:ee:ff:aa -skip
Pool exhausted Pool agotado
DHCPDISCOVER from bb:cc:dd:ee:ff:aa via enpXsX: network 192.168.0.0/24: no free leases DISCOVER from bb:cc:dd:ee:ff:aa (BAR)
Blocked bb:cc:dd:ee:ff:aa -skip
Blocked client — isc-dhcp-server reports it as a full pool Cliente bloqueado — isc-dhcp-server lo reporta como pool lleno

A pool with deny members of "blockdhcp" becomes invisible to that class, so isc-dhcp-server sees no lease available and logs the same message as a genuinely full pool. pydhcpd logs the real cause: Blocked or No IP.

Un pool con deny members of "blockdhcp" se vuelve invisible para esa clase, así que isc-dhcp-server no ve ninguna concesión disponible y escribe el mismo mensaje que un pool genuinamente lleno. pydhcpd registra la causa real: Blocked o No IP.

Authoritative behaviour

Configuration Description Descripción
authoritative; Enables authoritative behavior; also the PyDHCP default when neither directive is present Activa el modo autoritativo. PyDHCP también lo utiliza cuando faltan ambas directivas
not authoritative; Disables authoritative behavior Desactiva el modo autoritativo
REQUEST selecting another server PyDHCP ignores a REQUEST whose server identifier names another server, including in authoritative mode PyDHCP ignora un REQUEST que identifica a otro servidor, incluso en modo autoritativo
REQUEST for an unavailable address PyDHCP can send NAK in authoritative mode. In non-authoritative mode it stays silent PyDHCP puede responder NAK en modo autoritativo. En modo no autoritativo guarda silencio
When migrating, explicitly use not authoritative; if this server must remain non-authoritative. PyDHCP handles the requests addressed to this server. Durante la migración, añada not authoritative; si necesita conservar el modo no autoritativo. PyDHCP atiende las solicitudes dirigidas a este servidor.

Pool leases per client

PyDHCP keeps at most one active pool lease per MAC. When it grants a new pool address, it removes any different pool lease held by that MAC. This behavior is always enabled. PyDHCP conserva como máximo una concesión activa del pool por MAC. Al conceder otra dirección del pool, elimina la concesión anterior de esa MAC. Este comportamiento está siempre activo.

WPAD/PAC option scoping

PyDHCP stores one WPAD URL for the configured subnet. It sends that URL to every client receiving an OFFER or ACK, including an ACK for INFORM. WPAD_ENABLED controls the configuration generator; the daemon reads the resulting option wpad directive. PyDHCP conserva una URL WPAD para la subred configurada. La entrega a todos los clientes que reciben OFFER o ACK, incluido el ACK de INFORM. WPAD_ENABLED controla el generador. El demonio lee la directiva option wpad resultante.

External filtering

A firewall can restrict access to the PAC server, but PyDHCP will still advertise the same URL. A client that cannot download the PAC cannot execute its DIRECT fallback. Its behavior then depends on its own proxy settings. Configure these rules in the firewall. Un firewall puede restringir el acceso al servidor PAC, pero PyDHCP seguirá anunciando la misma URL. Un cliente que no pueda descargar el PAC tampoco podrá ejecutar su alternativa DIRECT. Su comportamiento dependerá de su configuración de proxy. Configure esas reglas en el firewall.

Improvements over isc-dhcp-server

isc-dhcp-server pydhcp Description Descripción
⛔ ✅ Per-MAC allocation rate limit: 5 allocations per minute per MAC Límite de asignación por MAC: 5 asignaciones por minuto y por MAC
⛔ ✅ DISCOVER reservations: a DISCOVER earns a 30s in-memory reservation, rather than a full lease; many different MACs can still exhaust the pool Reservas por DISCOVER: un DISCOVER obtiene una reserva en memoria de 30s, en lugar de una concesión completa; muchas MAC distintas todavía pueden agotar el pool
⛔ ✅ Lease cleanup at startup: malformed entries and already-expired leases are removed from the leases file, and the cleaned file is written back to disk Limpieza de concesiones al arrancar: las entradas malformadas y las concesiones ya vencidas se eliminan del archivo, y el archivo limpio se vuelve a escribir en disco
⛔ ✅ ACL automation: pyleases.sh rebuilds pydhcpd.conf from MAC lists Automatización de ACL: pyleases.sh reconstruye pydhcpd.conf desde listas de MAC

HOW IT WORKS


Rate limiting

By default, each MAC can obtain five new allocations within a sliding 60-second window. Renewing the same IP does not consume this limit. Once reached, further new allocations are rejected until earlier entries leave the window. Configure RATE_LIMIT_MAX and RATE_LIMIT_WINDOW_SECONDS in pydhcp.env. Restart the daemon after changing them. Por defecto, cada MAC puede obtener cinco asignaciones nuevas durante una ventana móvil de 60 segundos. Renovar la misma IP no consume este límite. Al alcanzarlo, se rechazan nuevas asignaciones hasta que venzan las entradas anteriores. Configure RATE_LIMIT_MAX y RATE_LIMIT_WINDOW_SECONDS en pydhcp.env. Reinicie el demonio después de modificarlas.

Known limitation

The allocation limit applies separately to each MAC. Different MACs have independent counters. A client using changing MAC addresses can still exhaust the available addresses. DISCOVER reservations expire after 30 seconds by default; that limits their duration, not the number of different clients. El límite de asignación se aplica por separado a cada MAC. Cada MAC tiene un contador independiente. Un cliente que cambie su MAC todavía puede agotar las direcciones disponibles. Las reservas DISCOVER vencen a los 30 segundos por defecto. Esto limita su duración, no la cantidad de clientes distintos.

Update checks

Updates project code, the systemd unit, administrative tools, log rotation and cron. Checks source files and destinations, creates a backup and pauses affected processes before replacing files. Actualiza el código, la unidad systemd, las herramientas, la rotación de registros y cron. Comprueba los archivos y destinos, crea un respaldo y pausa los procesos afectados antes del reemplazo.
Step Description Descripción
Before copying The installer checks all required source files and destinations, write access, available space, immutable attributes and relevant locks. El instalador comprueba todos los orígenes y destinos, escritura, espacio disponible, atributos inmutables y bloqueos relevantes.
Backup The installer invokes pybk.sh. If pybk.sh fails, the installer aborts before pausing consumers or replacing files, and reports the error. El instalador invoca pybk.sh. Si pybk.sh falla, el instalador aborta antes de pausar procesos o reemplazar archivos, y registra el error.
Pause The installer pauses its cron file and stops affected services and daemons. It verifies they have stopped and waits for running jobs before replacing files. If a pause fails before any replacement, the installer attempts to resume the previous consumers and schedule. El instalador pausa su archivo cron y detiene los servicios y demonios afectados. Comprueba su detención y espera que terminen las tareas en ejecución antes de reemplazar archivos. Si falla una pausa antes de reemplazar archivos, el instalador intenta reanudar los procesos y la programación anteriores.
Copy The installer repeats the checks immediately before copying. It verifies every replacement and its file contents. If a replacement fails, it aborts and leaves consumers paused. The backup remains available for manual recovery. The paused schedule remains at /etc/cron.d/pydhcp.update-disabled. El instalador repite las comprobaciones inmediatamente antes de copiar. Comprueba cada reemplazo y el contenido copiado. Si falla un reemplazo, aborta y deja los procesos pausados. El respaldo queda disponible para recuperación manual. La programación pausada permanece en /etc/cron.d/pydhcp.update-disabled.
Finish The installer regenerates its complete cron file and resumes the consumers that were active. It writes done only after successful completion. El instalador regenera su archivo cron completo y reanuda los procesos que estaban activos. Escribe done únicamente si termina correctamente.

Installer file handling

File --update --uninstall
pydhcpd.py ✅ overwritten ✅ removed
pydns.py ✅ overwritten ✅ removed
pydhcp-dns.service ✅ overwritten ✅ removed
pydhcp-dns.path ✅ overwritten ✅ removed
pydhcp-dns.timer ✅ overwritten ✅ removed
pydhcpd.service ✅ overwritten ✅ removed
init.d/pydhcpd ✅ overwritten ✅ removed
tools/pybk.sh ✅ overwritten ✅ removed (its cron entry is deregistered first)
tools/pyleases.sh ✅ overwritten ✅ removed
tools/pydhcpenv.sh ✅ overwritten ✅ removed
tools/pywebmin.sh ✅ overwritten ✅ removed (also uninstalls the Webmin module, if installed)
pydhcpd.conf ⛔ preserved ✅ removed
pydhcpd.leases ⛔ preserved ✅ removed
pydhcp.env ⛔ preserved ✅ removed
/var/log/pydhcp.log (shared by the daemon, tools/pyleases.sh and tools/pybk.sh; pysetup.sh only creates it) ⛔ preserved ✅ removed
/etc/logrotate.d/pydhcp ✅ policy refreshed ✅ removed
system user/group pydhcpd ⛔ preserved ✅ removed
/etc/pydhcp/acl/blockdhcp.txt (pydhcp's own block list) ⛔ preserved; owner and mode repaired ⛔ preserved
core/pydhcpd.conf.webmin.bak (Webmin rollback copy) ⛔ preserved ✅ removed
/etc/bak/ (project backups written by tools/pybk.sh) ⛔ preserved ⛔ preserved
/etc/acl/ (administrator's own ACL lists) ⛔ preserved; owner and mode of the folder and mac-*.txt repaired ⛔ preserved
/var/www/wpad/wpad.pac ⛔ preserved ✅ removed
wpad.conf (Apache site) and its Listen line in ports.conf ⛔ preserved ✅ removed
APT packages (installer packages and Apache) ✅ missing ones installed ⛔ preserved

/etc/acl is never touched by --uninstall. It holds the administrator's own mac-*.txt lists, edited by hand, which pydhcp may or may not use depending on whether the optional tools/pyleases.sh tool is ever run — pysetup.sh creates the directory regardless, so uninstalling the daemon does not assume that data is safe to discard.

/etc/acl permanece intacto al ejecutar --uninstall. Allí se guardan las listas mac-*.txt del administrador. pydhcp solo las utiliza si se ejecuta la herramienta opcional tools/pyleases.sh. Como pysetup.sh crea ese directorio, la desinstalación no elimina esos datos.

--uninstall removes the project only. It never uninstalls APT packages: other projects and the system may share them.

--uninstall elimina solo el proyecto. Nunca desinstala paquetes APT, porque otros proyectos y el sistema pueden compartirlos.

blockdhcp.txt is a different case: it is pydhcp's own list, written only by pyleases.sh and not edited manually. It is stored under /etc/pydhcp/acl/, separate from the administrator's lists in /etc/acl/. No installer ever removes /etc/acl, because access control lists outlive the project that reads them, so --uninstall leaves it in place.

blockdhcp.txt es un caso distinto: es la lista propia de pydhcp, escrita solo por pyleases.sh y no se edita manualmente. Se guarda en /etc/pydhcp/acl/, separada de las listas del administrador en /etc/acl/. Ningún instalador elimina /etc/acl, porque las listas de control de acceso sobreviven al proyecto que las lee, así que --uninstall la conserva.

Daily operation

# Edit the daemon configuration | Editar la configuración del demonio
sudo nano /etc/pydhcp/core/pydhcpd.conf

# Check the configuration | Comprobar la configuración
sudo /etc/pydhcp/core/pydhcpd.py -t -cf /etc/pydhcp/core/pydhcpd.conf

# Reload configuration | Recargar la configuración
sudo systemctl reload pydhcpd

# Restart after changing daemon bootstrap or performance settings in pydhcp.env
# Reiniciar tras cambiar valores de arranque o rendimiento en pydhcp.env
sudo systemctl restart pydhcpd

# Check service and leases | Consultar el servicio y las concesiones
sudo systemctl status pydhcpd
sudo cat /etc/pydhcp/core/pydhcpd.leases

# Follow logs | Consultar los registros en tiempo real
sudo journalctl -u pydhcpd -f
sudo tail -f /var/log/pydhcp.log

Configuration reload

Action Description Descripción
reload Reads and applies pydhcpd.conf again Vuelve a leer y aplica pydhcpd.conf
restart Loads daemon startup and performance settings from pydhcp.env Carga los ajustes de arranque y rendimiento del demonio desde pydhcp.env
Changed ranges Removes lease records whose addresses fall outside the configured pools and static reservations Elimina los registros de concesiones cuyas direcciones quedan fuera de los pools y reservas estáticas configurados

Config

Before selecting the LAN, the installer aborts if bind9, pdns-recursor, isc-dhcp-server, kea-dhcp4-server or udhcpd is installed, or if UDP 67 is in use. It warns if dnsmasq is installed. It also warns, without aborting, if the WPAD port (TCP 18800) is in use. The installer selects a LAN with an UP link and a global IPv4 address. With one candidate it selects it automatically; with several, it asks which to use and Enter selects the first. If that LAN has several IPv4 addresses, Enter also selects the first. The installer calculates subnet, mask and broadcast from its actual prefix. It then asks for the pool range, DNS1/DNS2 upstream servers, local domain, cleanup interval and optional WPAD deployment. DHCP advertises the selected server IP as DNS. Antes de seleccionar la LAN, el instalador aborta si están instalados bind9, pdns-recursor, isc-dhcp-server, kea-dhcp4-server o udhcpd, o si UDP 67 está en uso. Avisa si dnsmasq está instalado. También avisa, sin abortar, si el puerto de WPAD (TCP 18800) está en uso. El instalador selecciona una LAN con enlace UP e IPv4 global. Si existe una candidata, la selecciona automáticamente. Si existen varias, solicita una y Enter selecciona la primera. Si esa LAN tiene varias IPv4, Enter también selecciona la primera. Calcula subred, máscara y difusión desde su prefijo real. Después solicita el rango del pool, DNS1/DNS2 externos, dominio local, intervalo de limpieza y despliegue opcional de WPAD. DHCP anuncia la IP seleccionada del servidor como DNS.

Another installer may supply PYDHCP_LAN_IFACE and PYDHCP_SERVER_IP for an existing, eligible LAN interface and IPv4 address. It may also supply PYDHCP_SQUID_PORT to select the port used in the PAC.

Otro instalador puede proporcionar PYDHCP_LAN_IFACE y PYDHCP_SERVER_IP para una interfaz LAN y una IPv4 existentes y válidas. También puede proporcionar PYDHCP_SQUID_PORT para seleccionar el puerto utilizado en el PAC.

Configuration files

File Description Descripción
/etc/pydhcp/core/pydhcpd.conf Main configuration file Archivo de configuración principal
/etc/pydhcp/core/pydhcpd.leases Active leases database Base de datos de concesiones activas
/etc/pydhcp/pydhcp.env Shared settings: daemon paths, interface, user/group, network values, ACL paths, lease timers and WPAD/ping-check flags. pysetup.sh creates the file during installation; tools/pyleases.sh reads its required keys and stops if one is missing or invalid (see Key check) Configuración compartida: rutas del demonio, interfaz, usuario/grupo, valores de red, rutas ACL, duración de las concesiones y opciones de WPAD/ping-check. pysetup.sh crea el archivo durante la instalación; tools/pyleases.sh lee las claves que necesita y se detiene si falta alguna o no es válida (ver Key check)
/etc/systemd/system/pydhcpd.service systemd unit Unidad systemd
/etc/init.d/pydhcpd Legacy compatibility script for the service command; delegates to systemd when active Script heredado compatible con service; delega en systemd cuando está activo

Daemon startup settings

The daemon reads these settings from pydhcp.env at startup. It reads DHCP options, lease durations and host reservations from pydhcpd.conf. Reloading the service rereads only that configuration file. El demonio lee estos valores de pydhcp.env al arrancar. Obtiene las opciones DHCP, las duraciones de concesión y las reservas desde pydhcpd.conf. La recarga del servicio vuelve a leer únicamente ese archivo de configuración.
Variable Description Descripción
INTERFACESv4 Interface pydhcpd.py listens on Interfaz en la que escucha pydhcpd.py
DAEMON_USER, DAEMON_GROUP Owner requested when the daemon rewrites its leases file. The systemd unit starts the process as pydhcpd; changing these keys does not change the unit’s user Propietario solicitado al reescribir las concesiones. La unidad systemd inicia el proceso como pydhcpd. Cambiar estas claves no modifica el usuario de la unidad
DHCPDv4_CONF Path to pydhcpd.conf, read at startup and on SIGHUP/reload Ruta a pydhcpd.conf, leída al arrancar y en SIGHUP/reload
DHCPDv4_BIN, DHCPDv4_SCRIPT Interpreter and script used by the init.d fallback. Webmin invokes DHCPDv4_SCRIPT directly for configuration checks. The systemd unit has its own fixed ExecStart Intérprete y script utilizados por la alternativa de init.d. Webmin ejecuta directamente DHCPDv4_SCRIPT para comprobar la configuración. La unidad systemd tiene su propio ExecStart fijo
PYDHCPD_LEASES Leases database path Ruta de la base de datos de concesiones

Performance settings

The daemon reads these four values directly from pydhcp.env at startup. Their values are loaded from that file. Restart the daemon after changing them. El demonio lee estos cuatro valores directamente de pydhcp.env al arrancar. Sus valores se cargan desde ese archivo. Reinicie el demonio después de modificarlos.
Variable Description Descripción
PING_CACHE_TTL_SECONDS Seconds a ping-check result (alive/dead) is cached before re-checking the same IP; default 120 Segundos durante los que se conserva en caché el resultado de ping-check (activa/inactiva) antes de volver a comprobar la IP; valor predeterminado: 120
RATE_LIMIT_WINDOW_SECONDS, RATE_LIMIT_MAX Maximum new allocations per MAC within the configured window; defaults 60 seconds and 5 allocations. Different MACs have independent counters Máximo de asignaciones nuevas por MAC durante el intervalo configurado. Valores predeterminados: 60 segundos y 5 asignaciones. Cada MAC tiene su propio contador
RESERVATION_TTL_SECONDS Seconds a DISCOVER-only provisional reservation holds an IP before expiring, if no matching REQUEST follows; default 30 Segundos durante los que una solicitud DISCOVER puede reservar provisionalmente una IP si no llega el REQUEST correspondiente; valor predeterminado: 30

All four values above must be at least 1. A value below 1 (for example RATE_LIMIT_MAX=0, which does not mean "unlimited") is rejected with a WARNING in the log and the default is used instead.

Los cuatro valores anteriores deben ser como mínimo 1. Un valor menor que 1 (por ejemplo, RATE_LIMIT_MAX=0, que no significa «sin límite») se rechaza con una advertencia (WARNING) en el registro y se usa el valor predeterminado.

Configuration generator settings

The installer writes these values to pydhcp.env. Each pyleases.sh run uses them to generate pydhcpd.conf. The daemon reads the generated directives, not these keys. The generator checks its required keys without adding or changing them. El instalador escribe estos valores en pydhcp.env. Cada ejecución de pyleases.sh los utiliza para generar pydhcpd.conf. El demonio lee las directivas generadas, no estas claves. El generador comprueba las claves requeridas sin añadirlas ni modificarlas.
Variable pydhcpd.conf directive it becomes Description Descripción
CLEANUP_INTERVAL cleanup-interval and pool lease timers Cleanup interval and all three pool lease durations, in seconds; default 60 Intervalo de limpieza y duración de los tres tiempos del pool, en segundos. Valor predeterminado: 60
AUTHORIZED_LEASE_TIME subnet min/default/max-lease-time Lease duration for authorized/static clients in seconds; default 2592000 (30 days) Duración de la concesión para clientes autorizados o estáticos, en segundos. Valor predeterminado: 2592000 (30 días)
QUARANTINE_DURATION abandon-lease-time Address quarantine duration; default 60 seconds Duración de la cuarentena de una IP. Valor predeterminado: 60 segundos
WPAD_ENABLED option wpad ...; Enables the generated WPAD option when true and the URL probe succeeds Activa la opción WPAD generada si vale true y la consulta de la URL termina correctamente
WPAD_PORT Port in the option wpad URL Advertised PAC port. Installation uses 18800; changing this key does not reconfigure Apache Puerto anunciado para el PAC. La instalación utiliza 18800. Cambiar esta clave no reconfigura Apache
PING_CHECK_ENABLED ping-check Enables ICMP conflict checks; default true Activa la comprobación ICMP de conflictos. Valor predeterminado: true
PING_TIMEOUT_SECONDS ping-timeout ICMP reply timeout; default 1 second Tiempo de espera de la respuesta ICMP. Valor predeterminado: 1 segundo
SERVER_IP server-identifier, option routers Server's own IPv4 on the LAN interface IPv4 del servidor en la interfaz LAN
SERV_SUBNET, SERV_MASK subnet ... netmask ... Network address and netmask of the LAN subnet Dirección de red y máscara de la subred LAN
SERV_BROADCAST option broadcast-address Broadcast address of the LAN subnet Dirección de broadcast de la subred LAN
SERV_DNS option domain-name-servers DNS servers handed to clients; accepts a comma-separated list Servidores DNS que se entregan a los clientes; admite una lista separada por comas
SERV_DOMAIN option domain-name Required local domain; installation defaults to home.arpa Dominio local obligatorio; la instalación propone home.arpa
SERV_INI_RANGE_BLOCK, SERV_END_RANGE_BLOCK range of the block pool First and last IPv4 of the pool reserved for clients that are not on a MAC list Primera y última IPv4 del pool reservado para los clientes que no están en una lista MAC
ACL_PATH, ACL_MAC_LIMITED, ACL_MAC_UNLIMITED host entries Directory and files holding the administrator's MAC lists. pyleases.sh reads every mac-*.txt in that directory, not only those two files Directorio y archivos con las listas MAC del administrador. pyleases.sh lee todos los mac-*.txt del directorio, no solo esos dos archivos
ACL_DHCP_PATH, ACL_BLOCK_FILE class blockdhcp members Directory and file holding pydhcp's own blocked-MAC list, written by pyleases.sh Directorio y archivo con la lista de MAC bloqueadas propia de pydhcp, escrita por pyleases.sh

Every key in this table is verified by pyleases.sh before it rewrites pydhcpd.conf. SERVER_IP, SERV_SUBNET, SERV_BROADCAST, SERV_INI_RANGE_BLOCK and SERV_END_RANGE_BLOCK must parse as an IPv4 address, SERV_MASK as a netmask and SERV_DNS as an IPv4 list. See Key check.

Todas las claves de esta tabla las verifica pyleases.sh antes de reescribir pydhcpd.conf. SERVER_IP, SERV_SUBNET, SERV_BROADCAST, SERV_INI_RANGE_BLOCK y SERV_END_RANGE_BLOCK deben ser direcciones IPv4 válidas, SERV_MASK una máscara y SERV_DNS una lista de IPv4. Ver «Key check».

ACL base directory

ACL_PATH points to /etc/acl, and ACL_DHCP_PATH points to /etc/pydhcp/acl. The installer writes these paths in pydhcp.env. ACL_PATH apunta a /etc/acl y ACL_DHCP_PATH apunta a /etc/pydhcp/acl. El instalador escribe estas rutas en pydhcp.env.

Fixed values

These limits are constants defined in the daemon code. Estos límites son constantes definidas en el código del demonio.
Value Why it's fixed Por qué es fijo
Maximum addresses per range (65,536) Fixed limit imposed by PyDHCP to bound memory and CPU use; not an IPv4 limit. Each range exceeding the limit is rejected at config load or reload Tope impuesto por PyDHCP para limitar el uso de memoria y CPU; no es un límite de IPv4. El demonio rechaza cada rango que supere el límite al cargar o recargar la configuración
Max DHCP option length (255 bytes -- WPAD URL and other option values) Each option written by this daemon has a one-byte length field. Longer WPAD URLs are rejected Cada opción que escribe este demonio tiene un campo de longitud de un byte. Rechaza las URL WPAD mayores
Allocation round-robin counter wraparound (2**16) Internal counter used when selecting among free addresses Contador interno que participa en la selección de direcciones; su valor no se configura en los archivos de PyDHCP
Main-loop shutdown poll timeout (5s socket timeout) Controls how fast a systemctl stop is noticed, not DHCP behavior (leases, OFFERs, etc.) Determina cada cuánto el demonio comprueba si debe detenerse; no cambia la asignación de direcciones ni la duración de las concesiones

File ownership and permissions

The systemd unit runs the daemon as pydhcpd. It grants CAP_NET_RAW for raw sockets and ICMP, and CAP_NET_BIND_SERVICE for UDP 67. The following table describes the runtime directory created by systemd. La unidad systemd ejecuta el demonio como pydhcpd. Le concede CAP_NET_RAW para sockets raw e ICMP, y CAP_NET_BIND_SERVICE para UDP 67. La tabla describe el directorio de ejecución que crea systemd.
Path Owner Mode Description Descripción
/run/pydhcp pydhcpd:pydhcpd 755 Runtime directory created by systemd, separate from the installation directory; contains the PID file Directorio de ejecución creado por systemd, separado del directorio de instalación. Contiene el archivo PID
sudo ls -ld /etc/pydhcp /etc/pydhcp/core /etc/pydhcp/tools /run/pydhcp
sudo ls -l /etc/pydhcp/core/ /etc/pydhcp/pydhcp.env /var/log/pydhcp.log

Both --install and --update restore the defined ownership and modes. Existing configurations and leases retain their contents. Repairs are logged with INFO: ... -fixed. Unbound certificates and private keys retain their own permissions.

Tanto --install como --update restauran los propietarios y permisos definidos. Las configuraciones y concesiones existentes conservan su contenido. Las reparaciones se registran con INFO: ... -fixed. Los certificados y claves privadas de Unbound conservan sus permisos propios.

Path Owner Mode
/etc/pydhcp, /etc/pydhcp/core root:pydhcpd 1770
/etc/pydhcp/tools, /etc/unbound/unbound.conf.d root:root 755
/etc/pydhcp/pydhcp.env, /etc/pydhcp/core/pydhcpd.conf root:pydhcpd 640
/etc/pydhcp/core/pydhcpd.leases pydhcpd:pydhcpd 640
/etc/unbound/unbound.conf.d/forward.conf, /etc/default/unbound root:root 644
/var/lib/pydhcp-dns root:root 700
/var/lib/pydhcp-dns/records.json, /var/lib/pydhcp-dns/publish.lock root:root 600

Operational details

Topic Description Descripción
Service control Use systemctl. On systemd hosts, the init.d script delegates to it. Finish one administrative operation before starting another Utilice systemctl. En equipos con systemd, el script init.d delega en ese comando. Termine una operación administrativa antes de iniciar otra
UDP 67 The daemon reserves UDP 67 without socket reuse. If occupied, startup fails. UDP 68 is the client port El demonio reserva UDP 67 sin reutilizar el socket. Si está ocupado, no arranca. UDP 68 corresponde al cliente
Restart after failure The unit uses Restart=on-failure and a five-second delay. Its start limit is ten attempts within 120 seconds La unidad usa Restart=on-failure y espera cinco segundos entre intentos. Limita los arranques a diez intentos en 120 segundos
ping-check Enabled in the supplied configuration. Before an OFFER, it checks new dynamic addresses with ICMP. It skips static reservations and the client’s current address. Four workers handle at most 64 pending checks; saturation sends the OFFER without a check Está activo en la configuración incluida. Antes de un OFFER, comprueba por ICMP las direcciones dinámicas nuevas. Omite reservas estáticas y la dirección actual del cliente. Cuatro hilos atienden hasta 64 comprobaciones pendientes. Si se saturan, envía el OFFER sin comprobar
Ping timeout and cache Default timeout: one second. Default cache: 120 seconds. If raw ICMP is denied, the daemon tries the system ping command Tiempo de espera predeterminado: un segundo. Caché predeterminada: 120 segundos. Si se deniega ICMP raw, el demonio intenta utilizar el comando ping
BPF filter The daemon attempts to filter DHCP frames in the kernel. If attachment fails, it logs BPF attach failed and retains its userspace protocol and port checks El demonio intenta filtrar las tramas DHCP en el kernel. Si falla, registra BPF attach failed y conserva las comprobaciones de protocolo y puerto en su bucle de recepción
Cleanup cleanup-interval schedules removal of expired records. Default: 60 seconds; values below five are raised to five. Address selection already excludes expired leases when checking whether an address is occupied cleanup-interval programa la eliminación de registros vencidos. Su valor predeterminado es 60 segundos. Los valores inferiores a cinco se ajustan a cinco. La selección de direcciones ya ignora las concesiones vencidas al comprobar si una IP está ocupada
Pool lease duration The supplied pool uses 60 seconds. The installer asks for CLEANUP_INTERVAL and uses it for cleanup and all three pool lease timers. The generator does the same. Manually managed configurations can set these directives separately El pool incluido utiliza 60 segundos. El instalador solicita CLEANUP_INTERVAL. Lo utiliza para la limpieza y los tres tiempos del pool. El generador hace lo mismo. Una configuración manual permite ajustar esas directivas por separado
Quarantine abandon-lease-time defaults to 60 seconds. It excludes an address after a positive ping check or an accepted DECLINE. DECLINE is ignored in the supplied configuration because deny declines; is set abandon-lease-time utiliza 60 segundos por defecto. Excluye una dirección tras una respuesta ICMP positiva o un DECLINE aceptado. La configuración incluida ignora DECLINE porque contiene deny declines;
Range limit Each individual range is limited to 65,536 addresses. The daemon checks each range separately Cada rango individual admite hasta 65 536 direcciones. El demonio comprueba cada rango por separado

WPAD/PAC

WPAD advertises the URL of a PAC file through DHCP option 252. The client downloads that file and uses its JavaScript function to choose a proxy or a direct connection. PyDHCP sends the URL in its DHCP responses. Client support and proxy settings determine whether the PAC is used. WPAD anuncia la URL de un archivo PAC mediante la opción DHCP 252. El cliente descarga ese archivo. Su función JavaScript elige entre un proxy y una conexión directa. PyDHCP entrega la URL en sus respuestas DHCP. Su uso depende del soporte y la configuración del cliente.
Operation Description Descripción
Installation Optional; Yes is the default. Uses TCP 18800. If WPAD is chosen, the installer aborts before deployment if nginx, lighttpd or caddy is installed, or if the port is in use Es opcional. La respuesta predeterminada es Sí. Utiliza TCP 18800. Si se elige WPAD, el instalador aborta antes del despliegue si están instalados nginx, lighttpd o caddy, o si el puerto está en uso
Apache preparation Installs missing apache2, apache2-bin, apache2-data, apache2-doc and apache2-utils. Then always reinstalls apache2-doc. Enables alias, mime and the Apache service Instala apache2, apache2-bin, apache2-data, apache2-doc y apache2-utils si faltan. Después siempre reinstala apache2-doc. Habilita alias, mime y el servicio Apache
Files Writes /var/www/wpad/wpad.pac; installs and enables /etc/apache2/sites-available/wpad.conf; adds Listen SERVER_IP:18800 when needed Escribe /var/www/wpad/wpad.pac. Instala y habilita /etc/apache2/sites-available/wpad.conf. Añade Listen SERVER_IP:18800 si hace falta
Startup Tests Apache configuration, reloads Apache if active or starts it otherwise, then probes the PAC URL. A deployment failure aborts installation Comprueba la configuración de Apache. Lo recarga si está activo o lo inicia si está detenido. Después consulta la URL PAC. Un fallo del despliegue detiene la instalación
PAC routing With a successful Squid detection, plain host names, addresses matching 127.* and the LAN use DIRECT. Other destinations use PROXY SERVER_IP:PORT; DIRECT. When Squid detection returns unavailable, the PAC returns DIRECT Si la detección de Squid termina correctamente, los nombres simples, las direcciones 127.* y la LAN utilizan DIRECT. Los demás destinos utilizan PROXY SERVER_IP:PUERTO; DIRECT. Si la detección indica que Squid está ausente o inaccesible, el PAC devuelve DIRECT
Squid port Checks for squid, squid-openssl or squid3, the active squid service and a TCP listener on the LAN address or a wildcard address. The port comes from PYDHCP_SQUID_PORT, the first explicit http_port in squid.conf, or default 3128. Intercept and tproxy entries are skipped Comprueba un paquete squid, squid-openssl o squid3, el servicio squid activo y una escucha TCP en la dirección LAN o una dirección comodín. Obtiene el puerto de PYDHCP_SQUID_PORT, del primer http_port explícito de squid.conf o del valor predeterminado 3128. Descarta las entradas intercept y tproxy
Proxy-port validation When a Squid package is installed, an explicit PYDHCP_SQUID_PORT must be an integer from 1 to 65535. The installer checks it before preparing Apache or creating the PAC directory Si hay un paquete Squid instalado, PYDHCP_SQUID_PORT debe ser un entero entre 1 y 65535. El instalador lo comprueba antes de preparar Apache o crear el directorio PAC
Failure cleanup If WPAD setup fails, the installer attempts to remove the PAC directory, the WPAD site and matching Listen lines before aborting Si falla la configuración de WPAD, el instalador intenta retirar el directorio PAC, el sitio WPAD y las líneas Listen correspondientes antes de terminar
Configuration generator With WPAD_ENABLED=true, each pyleases.sh run probes http://SERVER_IP:WPAD_PORT/wpad.pac. A complete download with HTTP 200 enables the generated option. A failed probe leaves it commented and records a warning Con WPAD_ENABLED=true, cada ejecución de pyleases.sh consulta http://SERVER_IP:WPAD_PORT/wpad.pac. Si la descarga termina correctamente con HTTP 200, activa la opción generada. Si falla, deja la opción comentada y registra una advertencia
Probe validation Requires a successful curl exit and HTTP 200. HTTP 204 and 302 leave the generated option commented Exige que curl termine correctamente y HTTP 200. HTTP 204 y 302 dejan la opción generada comentada
Daemon Reads option wpad from pydhcpd.conf and includes the same URL in its OFFER and ACK responses. The generator converts WPAD_ENABLED into the directive read by the daemon Lee option wpad desde pydhcpd.conf. Incluye la misma URL en sus respuestas OFFER y ACK. El generador convierte WPAD_ENABLED en la directiva que lee el demonio
Update --update preserves the PAC and Apache configuration created during installation --update conserva el PAC y la configuración de Apache creados durante la instalación
Uninstall Removes WPAD files and attempts to reload Apache. The current cleanup removes all matching Listen lines for port 18800, regardless of address or WPAD_ENABLED Elimina los archivos WPAD e intenta recargar Apache. La limpieza actual elimina todas las líneas Listen del puerto 18800, sin distinguir la dirección ni WPAD_ENABLED

Changing WPAD settings

Setting Description Descripción
WPAD_ENABLED If pyleases.sh manages the configuration, set the key to false in pydhcp.env and run that tool. It rebuilds the DHCP configuration and restarts the daemon. Apache continues serving the existing PAC Si pyleases.sh administra la configuración, asigne false a la clave en pydhcp.env y ejecute esa herramienta. Reconstruye la configuración DHCP y reinicia el demonio. Apache continúa sirviendo el PAC existente
Manually managed configuration Comment out the option wpad URL in pydhcpd.conf, then reload the daemon Comente la URL option wpad en pydhcpd.conf y recargue el demonio
WPAD_PORT Sets the port in the generated PAC URL. Configure that same port in Apache’s listener and VirtualHost. Installation uses port 18800 over HTTP Define el puerto de la URL PAC generada. Configure ese mismo puerto en la escucha y el VirtualHost de Apache. La instalación utiliza el puerto 18800 mediante HTTP

Checking the PAC

Replace SERVER_IP and WPAD_PORT with the values in pydhcp.env. The default port is 18800. The curl command shows the HTTP status; cat displays the PAC content. Also check the URL from a LAN client. Sustituya SERVER_IP y WPAD_PORT por sus valores en pydhcp.env. El puerto predeterminado es 18800. El comando curl muestra el estado HTTP. El comando cat muestra el contenido PAC. Compruebe también la URL desde un cliente LAN.
curl -fsS --noproxy '*' --max-time 5 -o /dev/null \
  --write-out 'HTTP %{http_code}\n' 'http://SERVER_IP:WPAD_PORT/wpad.pac'
sudo cat /var/www/wpad/wpad.pac

Tools

pydhcpenv.sh

Shared Bash reader installed at /etc/pydhcp/tools/pydhcpenv.sh. Administrative tools load it with source. It reads pydhcp.env as literal key-value data. Write full paths such as ACL_PATH=/etc/acl. Load it from a consumer script. Lector Bash compartido instalado en /etc/pydhcp/tools/pydhcpenv.sh. Las herramientas administrativas lo cargan mediante source. Lee pydhcp.env como datos literales. Escriba rutas completas, como ACL_PATH=/etc/acl. Cárguelo desde un script consumidor.

pyleases

pyleases.sh reads the leases database and ACL lists, removes unapproved leases from that database, rebuilds pydhcpd.conf and restarts the daemon. Immediately before replacing the configuration, it saves the previous file as pydhcpd.conf.bak for rollback. The updater preserves this copy and uninstall removes it. Run this optional tool manually to rebuild DHCP assignments. pyleases.sh lee las concesiones y las listas ACL. Elimina de esa base las concesiones no autorizadas, reconstruye pydhcpd.conf y reinicia el demonio. Justo antes de reemplazar la configuración, guarda el archivo anterior como pydhcpd.conf.bak para poder restaurarlo. La actualización conserva esa copia y la desinstalación la elimina. Ejecute esta herramienta opcional manualmente para reconstruir las asignaciones DHCP.
Input Description Descripción
Administrator lists Reads every mac-*.txt in ACL_PATH. Entry format: a;MAC;IP;HOSTNAME;. Comment the entire line as #a;MAC;IP;HOSTNAME; to disable it Lee todos los archivos mac-*.txt de ACL_PATH. Formato: a;MAC;IP;HOSTNAME;. Para desactivar una entrada, comente la línea completa: #a;MAC;IP;HOSTNAME;
Blocked list ACL_BLOCK_FILE, normally /etc/pydhcp/acl/blockdhcp.txt. It accepts active entries only; comments are discarded as malformed ACL_BLOCK_FILE, normalmente /etc/pydhcp/acl/blockdhcp.txt. Solo admite entradas activas. Los comentarios se descartan por tener un formato inválido
List order Before any processing, every mac-*.txt is sorted by IP and blockdhcp.txt by line, and lines repeated exactly are removed, logged as INFO: <list>: N duplicate(s) removed -fixed. A list already in order is not rewritten Antes de cualquier procesamiento, cada mac-*.txt se ordena por IP y blockdhcp.txt por línea, y se eliminan las líneas repetidas de forma exacta, con el registro INFO: <lista>: N duplicate(s) removed -fixed. Una lista ya ordenada no se reescribe
Validation Checks line format, duplicate values and active reservation addresses before stopping the daemon. Commented entries still count in duplicate detection Comprueba el formato, los valores duplicados y las direcciones de reservas activas antes de detener el demonio. Las entradas comentadas también cuentan al buscar duplicados
Overlapping runs Uses /var/lock/pyleases.lock. Waits up to ten seconds. If another run still holds the lock, it skips the work and exits with status 75 Utiliza /var/lock/pyleases.lock. Espera hasta diez segundos. Si otra ejecución conserva el bloqueo, omite el trabajo y termina con código 75
sudo bash tools/pyleases.sh
ACL processing
ACL Description Descripción
mac-unlimited.txt, mac-limited.txt Administrator-maintained fixed reservations, processed like every mac-*.txt file. A malformed reservation or duplicate MAC, IP or hostname in these lists aborts the script Reservas fijas mantenidas por el administrador, procesadas como cualquier archivo mac-*.txt. Una reserva mal formada o una MAC, IP o nombre duplicado en estas listas detiene el script
#a;MAC;IP;HOSTNAME; A commented reservation is disabled. Its MAC is included in the generated blocked class Una reserva comentada queda desactivada. Su MAC se incluye en la clase de bloqueo generada
blockdhcp.txt pyleases.sh adds unapproved clients to this list and removes their lease records from the server’s database. After the rebuild, these MACs are denied new pool leases. Clients keep their configured addresses until their DHCP state changes. Invalid list entries are removed pyleases.sh añade los clientes no autorizados a esta lista y elimina sus concesiones de la base del servidor. Tras reconstruir la configuración, esas MAC quedan bloqueadas para nuevas concesiones del pool. Cada cliente conserva su dirección hasta que cambie su estado DHCP. Las entradas inválidas se eliminan de la lista
2026-11-13 12:00:00 INFO: blockdhcp.txt: malformed line 1; removed -fixed
Configuration rebuilding and updates
pysetup.sh --update replaces project code and preserves pydhcpd.conf and pydhcp.env. It first calls pybk.sh. Local edits to scripts are replaced during an update. pysetup.sh --update reemplaza el código del proyecto. Conserva pydhcpd.conf y pydhcp.env. Antes ejecuta pybk.sh. La actualización reemplaza las ediciones locales de los scripts.
Each pyleases.sh run generates one pool, the blocked class and fixed reservations from its configured inputs. The generated file replaces the previous configuration, including manually added pools, classes and directives. Cada ejecución de pyleases.sh genera un pool, la clase bloqueada y las reservas fijas desde sus entradas configuradas. El archivo generado reemplaza la configuración anterior, incluidos los pools, clases y directivas añadidos manualmente.

⚠️ WARNING -- Generated DHCP configuration: If you manage pydhcpd.conf manually, or another project manages it, such as uhm with uhmleases.sh, do not run pyleases.sh: it replaces the complete file and discards the other entries.

⚠️ WARNING -- Configuración DHCP generada: Si administra pydhcpd.conf manualmente, o lo gestiona otro proyecto, como uhm con uhmleases.sh, no ejecute pyleases.sh: reemplaza el archivo completo y descarta las demás entradas.

pybk

Creates pybk_<TIMESTAMP>.zip in BACKUP_DIR, which must be /etc/bak/pydhcp. It includes the installation tree, administrator MAC lists, pydhcp's blocked-MAC list, systemd units (pydhcpd, pydhcp-dns), Unbound configuration (/etc/unbound, /etc/default/unbound), DNS state (/var/lib/pydhcp-dns), init.d script, logrotate configuration, cron file and Webmin module. It also includes existing WPAD files and Apache’s ports.conf. Missing paths are skipped. The archive uses paths relative to /. It reads BACKUP_DIR from pydhcp.env. Any other value aborts before anything is created, written or deleted. The directory is exclusive to pybk.sh. After publishing the archive, the script deletes entries whose names do not match pybk_*.zip and keeps the three most recent archives. Crea pybk_<TIMESTAMP>.zip en BACKUP_DIR, que debe ser /etc/bak/pydhcp. Incluye la instalación, las listas MAC del administrador, la lista de MAC bloqueadas de pydhcp, la unidades systemd (pydhcpd, pydhcp-dns), la configuración de Unbound (/etc/unbound, /etc/default/unbound), el estado DNS (/var/lib/pydhcp-dns), el script init.d, logrotate, cron y el módulo Webmin. También incluye los archivos WPAD existentes y ports.conf de Apache. Omite las rutas ausentes. El comprimido utiliza rutas relativas a /. Lee BACKUP_DIR de pydhcp.env. Cualquier otro valor aborta antes de crear, escribir o borrar nada. El directorio es exclusivo de pybk.sh. Tras publicar el comprimido, el script elimina las entradas cuyo nombre no coincida con pybk_*.zip y conserva los tres comprimidos más recientes.
Command Description Descripción
sudo bash tools/pybk.sh Create a backup now Crear una copia ahora
sudo bash tools/pybk.sh --install Register the @monthly cron entry Registrar la entrada mensual en cron
sudo bash tools/pybk.sh --uninstall Remove the cron entry, keeping the archives Quitar la entrada de cron, conservando los comprimidos

BACKUP_DIR must be /etc/bak/pydhcp. Do not store other files there, because pybk.sh deletes them. Inspect the archive before restoring it manually.

BACKUP_DIR debe ser /etc/bak/pydhcp. No guarde otros archivos ahí, porque pybk.sh los elimina. Revise el comprimido antes de restaurarlo manualmente.

Backup Contents
This project uses two kinds of backup, distinguished by what is copied and its purpose. Este proyecto crea dos tipos de copia de seguridad, según qué se copia y su propósito.
Description Descripción
Project backup. It is a copy of the installation paths listed by pybk.sh, intended for the administrator. It is stored in BACKUP_DIR, which must be /etc/bak/pydhcp; its name carries a timestamp and up to 3 copies are kept. Only pybk.sh creates one. When present, it also includes /var/www/wpad, the available and enabled wpad.conf site paths, and Apache's ports.conf. Symbolic links are stored as links. The archive includes the mac-*.txt lists of ACL_PATH (/etc/acl by default) and /etc/pydhcp/acl. Copia de seguridad del proyecto. Es una copia de las rutas de instalación que enumera pybk.sh, destinada al administrador. Se guarda en BACKUP_DIR, que debe ser /etc/bak/pydhcp. Incluye la fecha y hora en el nombre y conserva hasta tres archivos. Solo pybk.sh crea esta copia. También incluye, cuando existen, /var/www/wpad, las rutas de wpad.conf en sitios disponibles y habilitados, y ports.conf de Apache. Los enlaces simbólicos se guardan como enlaces. El comprimido incluye las listas mac-*.txt de ACL_PATH (/etc/acl por defecto) y /etc/pydhcp/acl.
Routine-operation backup. It is the copy a script takes of one specific file right before modifying it, so the change can be undone. It is stored next to the original file, as <file>.bak, and only one copy is kept, overwritten on every run. Copia previa a una modificación. Antes de modificar un archivo, algunos scripts guardan una copia junto al original, con la extensión .bak. Se conserva una sola copia y cada ejecución reemplaza la anterior.

pywebmin

pywebmin

pywebmin.sh — Optional installer for a PyDHCP module for Webmin. Provides a web interface to manage the pydhcpd daemon: service control (start/stop/restart/reload), active leases table, and configuration file editor. Requires Webmin to be installed on the system. pywebmin.sh — Instalador opcional de un módulo PyDHCP para Webmin. Ofrece una interfaz web para administrar el servicio pydhcpd: iniciarlo, detenerlo, reiniciarlo o recargar su configuración; consultar las concesiones activas y editar el archivo de configuración. Requiere que Webmin esté instalado.
Features
Feature Description Descripción
Installer messages The installer prints its messages to the terminal. El instalador muestra sus mensajes en la terminal.
Service control Buttons to start, stop, restart or reload the pydhcpd service. Botones para iniciar, detener, reiniciar o recargar el servicio pydhcpd.
Active leases table Shows each active lease's IP address, MAC address, hostname, expiry and binding state. Muestra la IP, la dirección MAC, el nombre de host, la fecha de expiración y el estado de cada concesión activa.
Config editor Edits pydhcpd.conf in the browser and validates it with pydhcpd.py -t -cf before saving. Changes with syntax errors are rejected. Before replacing the file, it attempts a backup as pydhcpd.conf.webmin.bak. The save proceeds after the backup attempt. Reload the daemon after saving. Permite editar pydhcpd.conf desde el navegador y valida la sintaxis con pydhcpd.py -t -cf antes de guardar. Rechaza los cambios si hay errores. Antes de reemplazar el archivo, intenta crear pydhcpd.conf.webmin.bak. El guardado continúa después del intento de respaldo. Recargue el demonio después de guardar.
State indicators Color-coded states: Active (#d4edda/#155724), Inactive (#f8d7da/#721c24), Unknown (#e2e3e5/#383d41), Warning (#fff3cd/#856404). Estados con colores: Activo (#d4edda/#155724), Inactivo (#f8d7da/#721c24), Desconocido (#e2e3e5/#383d41), Advertencia (#fff3cd/#856404).
# Install | Instalar
sudo bash tools/pywebmin.sh --install

# Uninstall | Desinstalar
sudo bash tools/pywebmin.sh --uninstall

Requires a local user with sudo access; install aborts if none is found. Access is granted to the Webmin root account and to that user. For any other Webmin user, grant it from Webmin → Webmin Users.

Requiere un usuario local con sudo; la instalación aborta si no se encuentra ninguno. El acceso se concede a la cuenta root de Webmin y a ese usuario. Para cualquier otro usuario de Webmin, concederlo desde Webmin → Webmin Users.

Rogue DHCP defense

Description Descripción
Authoritative mode. Can reject a request for an address this daemon cannot grant. PyDHCP discards a REQUEST that selects another server Modo autoritativo. Puede rechazar una dirección que este demonio no pueda conceder. PyDHCP descarta un REQUEST que selecciona otro servidor
DHCP Snooping. Filters unauthorized DHCP responses at the switch DHCP Snooping. Filtra las respuestas DHCP no autorizadas en el switch

Configure DHCP Snooping on the switch.

Configure DHCP Snooping en el switch.

DHCP Iptables Rules

PyDHCP requires only LAN. The LAN rules below allow it to assign addresses to clients. The optional WAN rules apply only when the host also obtains its own address from an upstream DHCP server. Replace $lan and, if applicable, $wan before running these manual examples; they are not keys created by pydhcp. PyDHCP solo requiere LAN. Las reglas LAN siguientes permiten asignar direcciones a los clientes. Las reglas WAN opcionales aplican únicamente cuando el equipo también obtiene su dirección de un servidor DHCP ascendente. Sustituye $lan y, si corresponde, $wan antes de ejecutar estos ejemplos manuales; no son claves creadas por pydhcp.
# WAN — DHCP client (server requests an IP from an upstream DHCP server)
iptables -A OUTPUT -o $wan -p udp --sport 68 --dport 67 -j ACCEPT
iptables -A INPUT  -i $wan -p udp --sport 67 --dport 68 -j ACCEPT

# LAN — DHCP server (server assigns IPs to local clients)
iptables -A INPUT  -i $lan -p udp --sport 68 --dport 67 -j ACCEPT
iptables -A OUTPUT -o $lan -p udp --sport 67 --dport 68 -j ACCEPT

Logs

pydhcpd writes logs directly to /var/log/pydhcp.log. The daemon, tools/pyleases.sh and tools/pybk.sh append to this file, under one weekly rotation (/etc/logrotate.d/pydhcp). The path is fixed. Before each start, the service recreates the file if missing and restores its owner and mode. The installer writes to pysetup.log in its own directory and clears it at startup. The Webmin installer similarly writes to pywebmin.log beside its script. pydhcpd escribe directamente en /var/log/pydhcp.log. El demonio, tools/pyleases.sh y tools/pybk.sh escriben en ese mismo archivo. logrotate lo rota cada semana según /etc/logrotate.d/pydhcp. La ruta es fija. Antes de cada arranque, el servicio crea el archivo si falta y restaura su dueño y permisos. El instalador escribe en pysetup.log, junto al script, y lo vacía al inicio. El instalador Webmin escribe también su propio pywebmin.log junto al script.

Project log: /var/log/pydhcp.log. Installation and update configure weekly rotation in /etc/logrotate.d/pydhcp, keeping seven previous files plus the active log. Compression starts on the next rotation. Empty logs are not rotated; missing logs are tolerated. Squid and Apache keep their own policies.

Log del proyecto: /var/log/pydhcp.log. La instalación y la actualización configuran rotación semanal en /etc/logrotate.d/pydhcp. Se conservan siete archivos anteriores y el activo. La compresión comienza en la siguiente rotación. Los logs vacíos no se rotan; los ausentes se toleran. Squid y Apache conservan sus propias políticas.

Log format

Element Description Descripción
ERROR: Failures that abort a script, prevent the daemon from starting or stop it Fallos que detienen un script, impiden arrancar el demonio o lo detienen
WARNING: Conditions requiring review while an operation continues or uses a fallback Situaciones que requieren revisión mientras una operación continúa o utiliza una alternativa
INFO: Service activity, lease operations, skipped packets, automatic repairs and start and end markers Actividad del servicio, operaciones de concesiones, paquetes descartados, reparaciones automáticas y marcas de inicio y cierre

Key check

After reading pydhcp.env, pyleases.sh checks its 24 required keys. It reports a missing line as missing line, an empty value as not set, and a malformed value as invalid <type>. It collects key errors, writes one warning per key, then aborts with one error summary. The installer and administrator maintain those keys. Después de leer pydhcp.env, pyleases.sh comprueba sus 24 claves requeridas. Informa una línea ausente como missing line, un valor vacío como not set y un formato incorrecto como invalid <type>. Reúne los errores de claves. Registra una advertencia por clave y termina con un resumen de error. El instalador y el administrador mantienen esas claves.
2026-11-01 10:00:00 WARNING: DAEMON_USER not set -alert
2026-11-01 10:00:00 WARNING: SERVER_IP invalid IPv4 -alert
2026-11-01 10:00:00 ERROR: 2 key(s) invalid in pydhcp.env -abort

Lease request diagnostics

Log example Meaning Significado
INFO: REQUEST 02:00:00:00:00:01 ignored: not authoritative The requested IP differs from the static reservation. The non-authoritative server stays silent. The MAC identifies the client. La IP solicitada difiere de la reserva fija. El servidor no autoritativo guarda silencio. La MAC identifica al cliente.
INFO: NAK 02:00:00:00:00:01 Requested IP differs from offer The server rejects an IP different from its offer. El servidor rechaza una IP diferente de la ofrecida.
INFO: NAK 02:00:00:00:00:01 Not authorized for this IP The authoritative server rejects an IP different from the static reservation. El servidor autoritativo rechaza una IP diferente de la reserva fija.

Daemon errors

Log Cause Causa
ERROR: pydhcpd already running -abort Another pydhcpd instance holds the PID lock Otra instancia de pydhcpd tiene el bloqueo del PID
ERROR: No interface defined (INTERFACESv4) -abort INTERFACESv4 is empty in pydhcp.env INTERFACESv4 está vacía en pydhcp.env
ERROR: Interface <IFACE> missing -abort The interface in INTERFACESv4 does not exist on this host La interfaz de INTERFACESv4 no existe en este equipo
ERROR: absent.conf file not found -abort The configured file is missing. Startup aborts. El archivo configurado no existe. El arranque se detiene.
ERROR: [1/2] host 02:00:00:00:00:01
ERROR: [2/2] invalid IP 999.999.999.999 -abort
A static reservation contains an invalid IPv4 address. The first line identifies the MAC; the second gives the cause and aborts startup. Una reserva fija contiene una dirección IPv4 inválida. La primera línea identifica la MAC; la segunda muestra la causa y detiene el arranque.
ERROR: DNS servers: 64 configured, max 63 -abort More than 63 DNS servers are configured. Startup aborts. Hay más de 63 servidores DNS configurados. El arranque se detiene.
ERROR: [1/2] pool lease 61/60/60
ERROR: [2/2] require 0<min<=default<=max<2^32 -abort
Pool lease times violate the minimum, default and maximum bounds. Startup aborts. Los tiempos del pool incumplen los límites mínimo, predeterminado y máximo. El arranque se detiene.
ERROR: server-identifier missing in config -abort pydhcpd.conf has no server-identifier pydhcpd.conf no tiene server-identifier
ERROR: pydhcpd.leases: No space left on device -abort Disk full. Without saving leases no client gets an IP, so the daemon stops. Checked at startup and on every cleanup cycle Disco lleno. Sin guardar concesiones ningún cliente recibe IP, así que el demonio se detiene. Se comprueba al arrancar y en cada ciclo de limpieza
ERROR: pydhcpd.leases: Read-only file system -abort Disk mounted read-only. Same check and same stop Disco montado como solo lectura. Misma comprobación y misma parada
ERROR: pydhcpd.leases: Permission denied -abort The daemon cannot write in /etc/pydhcp/core. Same check and same stop El demonio no puede escribir en /etc/pydhcp/core. Misma comprobación y misma parada
ERROR: No interface configured -abort The server has no interface when it starts listening El servidor no tiene interfaz al empezar a escuchar
ERROR: UDP port 67 occupied -abort Another DHCP server is using UDP 67 Otro servidor DHCP está usando UDP 67
ERROR: Cannot bind UDP port 67 -abort UDP 67 cannot be opened for another reason UDP 67 no se puede abrir por otro motivo
ERROR: Raw socket failed on <IFACE> -abort The daemon cannot open the interface to read packets El demonio no puede abrir la interfaz para leer paquetes
WARNING: [1/2] cannot open /var/log/pydhcp.log
WARNING: [2/2] logging to stdout only -alert
The log file cannot be opened. Messages go only to the journal No se puede abrir el log. Los mensajes van solo al journal
WARNING: pydhcp.env missing -fallback pydhcp.env does not exist. Default values are used pydhcp.env no existe. Se usan los valores por defecto
WARNING: <KEY> invalid -fallback
WARNING: <KEY> low -fallback
A numeric key in pydhcp.env is not a number, or is below 1. Its default is used Una clave numérica de pydhcp.env no es un número, o es menor que 1. Se usa su valor por defecto
WARNING: cleanup-interval <N> < 5 -fallback cleanup-interval is below 5. It is raised to 5 cleanup-interval es menor que 5. Se sube a 5
WARNING: cleanup-interval <N> > pool min <M> -alert Expired leases are swept less often than the shortest pool lease lasts Las concesiones expiradas se barren con menos frecuencia de lo que dura la concesión más corta
WARNING: netmask not configured -alert pydhcpd.conf has no netmask. No reply can be built pydhcpd.conf no tiene máscara. No se puede construir ninguna respuesta
WARNING: Rate-limit hit: <MAC> -alert A client asked for new IPs too often Un cliente pidió IP nuevas con demasiada frecuencia
WARNING: Worker backlog full, <N> dropped -alert Too many requests at once. Logged once every 100 dropped packets Demasiadas peticiones a la vez. Se registra una vez cada 100 paquetes descartados
WARNING: Cannot save the lease cleanup -alert Expired leases were removed in memory but could not be saved Las concesiones expiradas se quitaron en memoria pero no se pudieron guardar
WARNING: Spoofed chaddr from <MAC> -alert The MAC inside the packet differs from the sender's MAC La MAC dentro del paquete no coincide con la MAC del emisor
WARNING: Spoofed relay from <IP> -alert A relayed packet does not come from a valid relay Un paquete reenviado no viene de un relay válido
WARNING: Reload failed, no server-id -fallback
WARNING: Reload failed -fallback
A reload found an invalid pydhcpd.conf. The previous configuration stays Una recarga encontró un pydhcpd.conf inválido. Se mantiene la configuración anterior

Discarded requests: a client request that the daemon cannot process is discarded. Only that client gets no answer; the other clients are not affected. The reason is one of missing field, invalid value, truncated packet or unexpected data. If the lines repeat, check that device.

Peticiones descartadas: una petición que el demonio no puede procesar se descarta. Solo ese cliente queda sin respuesta; los demás no se ven afectados. El motivo es uno de missing field, invalid value, truncated packet o unexpected data. Si las líneas se repiten, revise ese dispositivo.

2026-11-12 10:05:00 INFO: request from 11:22:33:44:55:66 discarded -skip
2026-11-12 10:05:00 INFO: request discarded: missing field

Client name limits

Lease records store a sanitized name of at most 64 characters; ACL generation accepts at most 63. Las concesiones guardan un nombre depurado de hasta 64 caracteres. El generador ACL admite hasta 63.

Runtime files

Files generated at runtime (not included in the repository): Archivos creados durante la ejecución, no incluidos en el repositorio:
/etc/pydhcp/core/pydhcpd.leases                  # Active leases database
/var/lib/pydhcp-dns/records.json                 # Managed local DNS records
/var/lib/pydhcp-dns/publish.lock                 # DNS synchronization lock
/etc/unbound/unbound.conf.d/forward.conf.bak     # Previous DNS configuration when --configure changes it
/run/pydhcp/pydhcpd.pid                          # PID file, written by the daemon
                                                 # (systemd creates the directory)
/etc/bak/pydhcp/pybk_<TIMESTAMP>.zip             # Selected paths archived by tools/pybk.sh, up to 3 kept
/etc/pydhcp/core/pydhcpd.conf.webmin.bak         # Rollback copy written by the Webmin module (pywebmin.sh) on each save, 1 kept
/etc/webmin/pydhcp/.csrf_token                   # CSRF secret for the Webmin module (pywebmin.sh), mode 0600

DNS Unbound

PyDHCP combines its Python DHCP daemon with Unbound as a separate DNS service. DHCP announces the server LAN IP through option 6 and the local domain through option 15. Unbound answers local names and forwards external queries to its configured upstream servers. core/pydns.py connects both services by publishing names from static reservations and active leases. PyDHCP combina su demonio DHCP Python con Unbound como servicio DNS separado. DHCP anuncia la IP LAN del servidor mediante la opción 6. Anuncia el dominio local mediante la opción 15. Unbound responde nombres locales y reenvía consultas externas a los servidores configurados. core/pydns.py integra ambos servicios publicando nombres de reservas fijas y concesiones activas.

Components

Component Description Descripción
pysetup.sh Selects LAN/IP, calculates the subnet, asks for DNS1/DNS2 and local domain, and deploys Unbound and publication units Selecciona LAN/IP, calcula la subred, pregunta DNS1/DNS2 y dominio local, e instala Unbound y las unidades de publicación
pydhcp.env SERVER_IP, SERV_SUBNET, SERV_MASK and SERV_DOMAIN define the local DNS environment. SERV_DNS contains the DNS addresses announced to clients SERVER_IP, SERV_SUBNET, SERV_MASK y SERV_DOMAIN definen el entorno DNS local. SERV_DNS contiene las direcciones DNS anunciadas a los clientes
core/pydhcpd.py Serves DHCP options 6 and 15; persists client hostnames in core/pydhcpd.leases Entrega las opciones DHCP 6 y 15; guarda los nombres de clientes en core/pydhcpd.leases
core/pydhcpd.conf Defines the DHCP domain, client DNS addresses and named static reservations Define el dominio DHCP, los DNS de clientes y las reservas fijas con nombre
core/pydhcpd.leases Supplies dynamic client names, addresses, binding states and expiry times Proporciona nombres dinámicos, direcciones, estados y vencimientos de las concesiones
conf/forward.conf Installer template. Installation generates /etc/unbound/unbound.conf.d/forward.conf directly; it defines listeners, access-control, local zone and upstream DNS servers Plantilla del instalador. La instalación genera directamente /etc/unbound/unbound.conf.d/forward.conf; define escucha, access-control, zona local y servidores DNS externos
unbound.service Runs DNS independently from the DHCP daemon; serves local records and forwards external queries Ejecuta DNS independientemente del demonio DHCP; responde registros locales y reenvía consultas externas
core/pydns.py Essential synchronization component. Publishes A/PTR records using authenticated local unbound-control, preserving unrelated records Componente esencial de sincronización. Publica registros A/PTR mediante unbound-control local autenticado y conserva registros ajenos
core/pydns.py --configure Synchronizes interface, access-control and local domain, then publishes names in the same invocation and lock Sincroniza interfaz, access-control y dominio local; después publica nombres en la misma ejecución y bloqueo
tools/pyleases.sh / UHM core/uhmleases.sh Rebuild DHCP configuration, start DHCP, then invoke pydns.py --configure once Reconstruyen la configuración DHCP, arrancan DHCP y ejecutan pydns.py --configure una vez
pydhcp-dns.service Runs the publisher as a root oneshot service with a private state directory Ejecuta el publicador como servicio oneshot de root con un directorio de estado privado
pydhcp-dns.path Launches publication when leases, DHCP configuration or pydhcp.env change Activa la publicación cuando cambian las concesiones, la configuración DHCP o pydhcp.env
pydhcp-dns.timer Reconciles five seconds after the publication service becomes inactive; handles expirations and missing records after Unbound restarts Reconcilia cinco segundos después de quedar inactivo el publicador; gestiona vencimientos y registros ausentes tras reiniciar Unbound
/var/lib/pydhcp-dns/records.json Tracks managed records so obsolete names can be removed without deleting unrelated records Registra los datos administrados para eliminar nombres obsoletos sin borrar registros ajenos
/var/lib/pydhcp-dns/publish.lock Serializes direct reloads and automatic name publication Evita ejecuciones simultáneas entre recargas directas y publicación automática

Resolution flow

Query or event Description Descripción
DHCP assignment The client receives its address, server LAN IP as DNS, and SERV_DOMAIN as local domain El cliente recibe su dirección, la IP LAN del servidor como DNS y SERV_DOMAIN como dominio local
Local forward lookup portatil-ana.home.arpa resolves to its published IPv4 address through an A record portatil-ana.home.arpa resuelve su dirección IPv4 publicada mediante un registro A
Local reverse lookup A PTR record maps the published IPv4 address to the full local hostname Un registro PTR relaciona la dirección IPv4 publicada con el nombre local completo
External lookup Client → Unbound → configured upstream DNS. The installed configuration uses forwarding, not direct recursion from root servers Cliente → Unbound → DNS externo configurado. La instalación utiliza reenvío, no recursión directa desde servidores raíz
Name changes The publisher updates local records through unbound-control without restarting Unbound El publicador actualiza los registros locales mediante unbound-control sin reiniciar Unbound
Network/domain changes A DHCP rebuild invokes --configure; changed Unbound configuration is validated and replaced before restarting the DNS service La reconstrucción DHCP ejecuta --configure; valida y reemplaza la configuración Unbound modificada antes de reiniciar DNS
DNS failure during rebuild The reload reports ERROR; DHCP has already started and remains running La recarga informa ERROR; DHCP ya está iniciado y continúa funcionando

Operation

Component Description Descripción
Unbound Installed as a forwarding resolver. DHCP option 6 announces the server LAN IP Instalado como resolutor de reenvío. La opción DHCP 6 anuncia la IP LAN del servidor
Conflict checks Installation aborts for installed bind9 or pdns-recursor, even when stopped. An existing PyDHCP installation aborts before checking Unbound La instalación aborta con bind9 o pdns-recursor instalados, aunque estén detenidos. Si PyDHCP ya está instalado, aborta antes de comprobar Unbound
Existing Unbound Reuses the installed package after confirmation, before package installation or configuration changes. The prompt identifies forward.conf, /etc/default/unbound, local control setup and enabling/restarting Unbound. No or Enter cancels installation; Yes continues. Existing versions of both configuration files are copied to adjacent .bak files before replacement Reutiliza el paquete instalado después de confirmar, antes de instalar paquetes o modificar configuraciones. La pregunta identifica forward.conf, /etc/default/unbound, el control local y la habilitación/reinicio de Unbound. No o Enter cancela la instalación; Sí continúa. Copia ambos archivos existentes a archivos .bak junto a los originales antes de reemplazarlos
DNS prompts DNS1 defaults to 1.1.1.2; DNS2 defaults to 1.0.0.2. The template retains 9.9.9.9 as a third upstream DNS1 propone 1.1.1.2; DNS2 propone 1.0.0.2. La plantilla conserva 9.9.9.9 como tercer servidor externo
Configuration /etc/unbound/unbound.conf.d/forward.conf: loopback/LAN listeners, LAN access, local zone and authenticated loopback control /etc/unbound/unbound.conf.d/forward.conf: escucha local/LAN, acceso LAN, zona local y control autenticado por loopback
Domain SERV_DOMAIN generates DHCP option 15. Option 119 is excluded SERV_DOMAIN genera la opción DHCP 15. La opción 119 queda excluida
Publication core/pydns.py reads current reservations and unexpired active leases; publishes A/PTR through unbound-control core/pydns.py lee reservas actuales y concesiones activas vigentes; publica A/PTR mediante unbound-control
Names Accepts valid single-label hostnames or the same hostname under SERV_DOMAIN. Invalid names are excluded Acepta nombres válidos de una etiqueta o ese nombre dentro de SERV_DOMAIN. Excluye nombres inválidos
Duplicates Reservations win; dynamic ties prefer latest expiry, then name/IP. Reserved MACs/IPs cannot publish dynamic alternatives Prioriza reservas; entre concesiones, prioriza vencimiento posterior y después nombre/IP. Las MAC/IP reservadas no publican alternativas dinámicas
Triggers File changes and DHCP rebuilds trigger publication. A five-second timer removes expired records and restores records after Unbound restarts Los cambios de archivos y reconstrucciones DHCP activan la publicación. Un temporizador de cinco segundos elimina registros vencidos y repone registros después de reiniciar Unbound
TTL Local records use at most 30 seconds, bounded by dynamic lease expiry Los registros locales utilizan hasta 30 segundos, limitados por el vencimiento de las concesiones dinámicas
Ownership /var/lib/pydhcp-dns is root-only (0700). Publication preserves unrelated records and refuses conflicting records managed elsewhere /var/lib/pydhcp-dns pertenece exclusivamente a root (0700). La publicación conserva registros ajenos y rechaza registros en conflicto administrados externamente
Updates Code updates preserve DNS configuration. Installations without DNS integration require reinstalling Las actualizaciones conservan la configuración DNS. Las instalaciones sin integración DNS requieren reinstalación
Removal Removes publication units/state. If PyDHCP installed Unbound, removes forward.conf and stops and disables Unbound. A reused Unbound gets back its previous files and its enabled/active state; files it did not have before are removed. Package dependencies remain installed Elimina unidades/estado de publicación. Si PyDHCP instaló Unbound, elimina forward.conf y detiene y deshabilita Unbound. Un Unbound reutilizado recupera sus archivos anteriores y su estado habilitado/activo; los archivos que no tenía se eliminan. Conserva los paquetes instalados
Configuration reloads pyleases.sh and uhmleases.sh invoke core/pydns.py --configure. It synchronizes LAN interface, access-control and local zone from pydhcp.env, validates before replacing, and restarts Unbound only when configuration changes. Failed restarts restore the previous file pyleases.sh y uhmleases.sh ejecutan core/pydns.py --configure. Sincroniza interfaz LAN, access-control y zona local desde pydhcp.env, valida antes de reemplazar y reinicia Unbound solamente si cambia la configuración. Restaura el archivo anterior si falla el reinicio
Short names Client suffix handling determines whether portatil-ana expands to the full name; verify Windows and systemd-resolved clients El cliente determina si completa portatil-ana con el dominio; verifique clientes Windows y systemd-resolved

ACKNOWLEDGMENTS


Thanks are due to the Internet Systems Consortium (ISC) and NLnet Labs, and especially to the developers who created ISC-DHCP and Unbound. Without their work, PyDHCP would not have been possible. Se agradece a Internet Systems Consortium (ISC) y a NLnet Labs, y especialmente a los desarrolladores que crearon ISC-DHCP y Unbound. Sin esta base, PyDHCP no habría sido posible.
Project Version Status
ISC-DHCP 4.4.3-P1-4ubuntu2 EOL/EOS 2022
Unbound Distribution package Active

NOTICE


This repository
  • May include third-party components.
  • Does not accept Pull Requests. Changes must be proposed via Issues.
  • This project does not support backward compatibility. New versions may require configuration changes or reinstallation.
  • Adding custom tasks to the project's cron file is not recommended because each installation or update rewrites it.
Este repositorio
  • Puede incluir componentes de terceros.
  • No acepta Pull Requests. Los cambios deben proponerse mediante Issues.
  • Este proyecto no soporta retrocompatibilidad. Las nuevas versiones pueden requerir cambios de configuración o una reinstalación.
  • No se recomienda programar tareas propias en el cron del proyecto, ya que se reescribe en cada instalación o actualización.

LIMITATIONS


  • Follows a non-standard workflow. Published commits may be rewritten or removed without notice as part of the debugging and improvement process.
  • Utiliza un flujo de trabajo no convencional. Los commits publicados pueden ser reescritos o eliminados sin previo aviso como parte del proceso de depuración y mejora.

SPONSOR THIS PROJECT


Image

PROJECT LICENSES


This project uses a dual-licensing model to balance software freedom with content protection: Este proyecto utiliza un modelo de licencia dual para equilibrar la libertad del software con la protección del contenido:
Content Licensed Under
Scripts, Binaries, Infrastructure GPL-3.0
RAG, Workers, Specialized Modules, Docs CC

DISCLAIMER


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Contributors

Languages