如何使用Python提取DHCP租约文件中binding state为active的指定字段
实现思路
不需要复杂的多行正则匹配,更简单易维护的方案是先按租约的块结构拆分内容,逐个块处理,逻辑清晰不易出错:
- 第一步:将整个租约文件按
lease关键字拆分,得到每个独立的租约块 - 第二步:遍历每个租约块,先判断是否包含
binding state active;,不满足直接跳过 - 第三步:对符合条件的块,逐行提取需要的字段:租约IP、绑定状态、MAC地址、circuit-id、客户端主机名
- 第四步:按需格式化输出内容即可
完整实现代码
def parse_dhcp_leases(file_path): with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 按租约起始标识拆分所有租约块,跳过空块 lease_blocks = [block.strip() for block in content.split('lease ') if block.strip()] for block in lease_blocks: # 非active状态直接跳过 if 'binding state active;' not in block: continue # 提取租约IP lease_ip = block.split(' {')[0].strip() # 初始化字段变量 binding_state = '' hw_ethernet = '' circuit_id = '' client_hostname = '' # 逐行提取需要的字段 for line in block.split('\n'): line = line.strip() if line.startswith('binding state '): binding_state = line elif line.startswith('hardware ethernet '): # 按输出要求在冒号后补空格 hw_ethernet = line.replace(':', ': ') elif line.startswith('option agent.circuit-id '): # 按输出要求在冒号后补空格 circuit_id = line.replace(':', ': ') elif line.startswith('client-hostname '): client_hostname = line # 按要求格式输出 print(f"lease {lease_ip}") print(binding_state) print(hw_ethernet) print(circuit_id) print(client_hostname) # 租约之间空一行分隔 print() if __name__ == '__main__': # 替换为你的租约文件实际路径 parse_dhcp_leases('/var/lib/dhcp.leases')
方案优势
- 逻辑直观,不需要写复杂的正则规则,后续维护修改成本极低
- 按块处理不会出现不同租约字段匹配串扰的问题,准确率更高
- 性能充足,即使是几万条租约的大文件也能快速处理
- 扩展性强,后续需要提取其他租约字段,只要加对应行判断即可
内容的提问来源于stack exchange,提问作者Domingo Martinez
相关产品推荐
相关产品推荐

