在 Debian 上自定义 DHCP 模板的可维护做法
一、准备与目录结构
sudo apt update && sudo apt install isc-dhcp-server/etc/dhcp/dhcpd.conf(仅保留 include 与全局项)/etc/dhcp/conf.d/(按功能拆分:subnets.conf、hosts.conf、options.conf、classes.conf)/etc/dhcp/dhcpd.conf 中引入片段:
ddns-update-style none;
default-lease-time 600;
max-lease-time 7200;
authoritative;
log-facility local7;
include "/etc/dhcp/conf.d/subnets.conf";
include "/etc/dhcp/conf.d/hosts.conf";
include "/etc/dhcp/conf.d/options.conf";
include "/etc/dhcp/conf.d/classes.conf";
/etc/default/isc-dhcp-server,如:INTERFACESv4="eth0"。二、模板化配置示例
subnet 192.168.1.0 netmask 255.255.255.0 {
range 192.168.1.100 192.168.1.200;
option routers 192.168.1.1;
option subnet-mask 255.255.255.0;
option broadcast-address 192.168.1.255;
option domain-name-servers 8.8.8.8, 8.8.4.4;
}
host workstation {
hardware ethernet 00:1A:2B:3C:4D:5E;
fixed-address 192.168.1.55;
}
# 定义代码为 123 的自定义字符串选项
option custom-option code 123 = string;
option custom-option "This is a custom option";
# 为特定主机覆盖
host client1 {
hardware ethernet 00:11:22:33:44:55;
fixed-address 192.168.1.101;
option custom-option "Client1 Custom Option";
}
class "printers" {
match if substring (option vendor-class-identifier, 0, 9) = "HP-Printer";
}
pool {
allow members of "printers";
range 192.168.1.210 192.168.1.220;
option routers 192.168.1.1;
}
三、生效与验证
sudo dhcpd -t -cf /etc/dhcp/dhcpd.confsudo systemctl restart isc-dhcp-server
sudo systemctl enable isc-dhcp-server
sudo systemctl status isc-dhcp-server
sudo journalctl -u isc-dhcp-server -fgrep dhcpd /var/log/syslog/var/lib/dhcp/dhcpd.leasessudo dhcp-lease-listsudo apt install dhcpingsudo dhcping -c 4 192.168.1.1sudo ufw allow 67/udp(服务器侧 UDP 67)。四、自动化与批量生成
/etc/dhcp/conf.d/hosts.conf 的 host 块,示例 Python 片段:#!/usr/bin/env python3
import sys
def block(mac, name, ip):
return f'host {name} {{\n hardware ethernet {mac};\n fixed-address {ip};\n}}\n'
devices = [
("00:1A:2B:3C:4D:5E", "dev-pc01", "192.168.1.55"),
("00:1A:2B:3C:4D:5F", "printer-01", "192.168.1.60"),
]
with open("/etc/dhcp/conf.d/hosts.conf", "w") as f:
f.write("# Auto-generated\n")
for m, n, i in devices:
f.write(block(m, n, i))
# 生成后重启服务
import os; os.system("systemctl restart isc-dhcp-server")
五、常见问题与排查要点
dhcpd -t 校验。/etc/default/isc-dhcp-server 中的 INTERFACESv4 与实际提供 DHCP 的网卡一致;DHCP 服务器本机应使用静态 IP且与子网匹配。range 之外,避免冲突。dnsmasq 等也会提供 DHCP,需停用或调整以避免端口冲突。journalctl -u isc-dhcp-server 与 /var/log/syslog 中的 dhcpd 日志条目。