Analysis of Linux DHCP server IP allocation Python script

Leymus chinensis 2021-07-20 04:42:17
analysis linux dhcp server ip


The customer has one here linux The server , As dhcp Server usage . Every time you need to query dhcp The default address assignment record can only be in cat /var/lib/dhcpd/dhcpd.leases View this file , It's very inconvenient to inquire
Just like this.

Later, I tried to write a script to parse , But it wasn't handled very well . But in githup I found a big man writing python Script , Can complete the analysis of Statistics , Humanized a lot , Just like this.

The script is as follows :

#!/usr/bin/python
import datetime, bisect
def parse_timestamp(raw_str):
tokens = raw_str.split()
if len(tokens) == 1:
if tokens[0].lower() == 'never':
return 'never';
else:
raise Exception('Parse error in timestamp')
elif len(tokens) == 3:
return datetime.datetime.strptime(' '.join(tokens[1:]),
'%Y/%m/%d %H:%M:%S')
else:
raise Exception('Parse error in timestamp')
def timestamp_is_ge(t1, t2):
if t1 == 'never':
return True
elif t2 == 'never':
return False
else:
return t1 >= t2
def timestamp_is_lt(t1, t2):
if t1 == 'never':
return False
elif t2 == 'never':
return t1 != 'never'
else:
return t1 < t2
def timestamp_is_between(t, tstart, tend):
return timestamp_is_ge(t, tstart) and timestamp_is_lt(t, tend)
def parse_hardware(raw_str):
tokens = raw_str.split()
if len(tokens) == 2:
return tokens[1]
else:
raise Exception('Parse error in hardware')
def strip_endquotes(raw_str):
return raw_str.strip('"')
def identity(raw_str):
return raw_str
def parse_binding_state(raw_str):
tokens = raw_str.split()
if len(tokens) == 2:
return tokens[1]
else:
raise Exception('Parse error in binding state')
def parse_next_binding_state(raw_str):
tokens = raw_str.split()
if len(tokens) == 3:
return tokens[2]
else:
raise Exception('Parse error in next binding state')
def parse_rewind_binding_state(raw_str):
tokens = raw_str.split()
if len(tokens) == 3:
return tokens[2]
else:
raise Exception('Parse error in next binding state')
def parse_leases_file(leases_file):
valid_keys = {
'starts': parse_timestamp,
'ends': parse_timestamp,
'tstp': parse_timestamp,
'tsfp': parse_timestamp,
'atsfp': parse_timestamp,
'cltt': parse_timestamp,
'hardware': parse_hardware,
'binding': parse_binding_state,
'next': parse_next_binding_state,
'rewind': parse_rewind_binding_state,
'uid': strip_endquotes,
'client-hostname': strip_endquotes,
'option': identity,
'set': identity,
'on': identity,
'abandoned': None,
'bootp': None,
'reserved': None,
}
leases_db = {}
lease_rec = {}
in_lease = False
in_failover = False
for line in leases_file:
if line.lstrip().startswith('#'):
continue
tokens = line.split()
if len(tokens) == 0:
continue
key = tokens[0].lower()
if key == 'lease':
if not in_lease:
ip_address = tokens[1]
lease_rec = {'ip_address' : ip_address}
in_lease = True
else:
raise Exception('Parse error in leases file')
elif key == 'failover':
in_failover = True
elif key == '}':
if in_lease:
for k in valid_keys:
if callable(valid_keys[k]):
lease_rec[k] = lease_rec.get(k, '')
else:
lease_rec[k] = False
ip_address = lease_rec['ip_address']
if ip_address in leases_db:
leases_db[ip_address].insert(0, lease_rec)
else:
leases_db[ip_address] = [lease_rec]
lease_rec = {}
in_lease = False
elif in_failover:
in_failover = False
continue
else:
raise Exception('Parse error in leases file')
elif key in valid_keys:
if in_lease:
value = line[(line.index(key) + len(key)):]
value = value.strip().rstrip(';').rstrip()
if callable(valid_keys[key]):
lease_rec[key] = valid_keys[key](value)
else:
lease_rec[key] = True
else:
raise Exception('Parse error in leases file')
else:
if in_lease:
raise Exception('Parse error in leases file')
if in_lease:
raise Exception('Parse error in leases file')
return leases_db
def round_timedelta(tdelta):
return datetime.timedelta(tdelta.days,
tdelta.seconds + (0 if tdelta.microseconds < 500000 else 1))
def timestamp_now():
n = datetime.datetime.utcnow()
return datetime.datetime(n.year, n.month, n.day, n.hour, n.minute,
n.second + (0 if n.microsecond < 500000 else 1))
def lease_is_active(lease_rec, as_of_ts):
return timestamp_is_between(as_of_ts, lease_rec['starts'],
lease_rec['ends'])
def ipv4_to_int(ipv4_addr):
parts = ipv4_addr.split('.')
return (int(parts[0]) << 24) + (int(parts[1]) << 16) + \
(int(parts[2]) << 8) + int(parts[3])
def select_active_leases(leases_db, as_of_ts):
retarray = []
sortedarray = []
for ip_address in leases_db:
lease_rec = leases_db[ip_address][0]
if lease_is_active(lease_rec, as_of_ts):
ip_as_int = ipv4_to_int(ip_address)
insertpos = bisect.bisect(sortedarray, ip_as_int)
sortedarray.insert(insertpos, ip_as_int)
retarray.insert(insertpos, lease_rec)
return retarray
##############################################################################
myfile = open('/var/lib/dhcpd/dhcpd.leases', 'r')
leases = parse_leases_file(myfile)
myfile.close()
now = timestamp_now()
report_dataset = select_active_leases(leases, now)
print('+------------------------------------------------------------------------------')
print('| DHCPD ACTIVE LEASES REPORT')
print('+-----------------+-------------------+----------------------+-----------------')
print('| IP Address | MAC Address | Expires (days,H:M:S) | Client Hostname ')
print('+-----------------+-------------------+----------------------+-----------------')
for lease in report_dataset:
print('| ' + format(lease['ip_address'], '<15') + ' | ' + \
format(lease['hardware'], '<17') + ' | ' + \
format(str((lease['ends'] - now) if lease['ends'] != 'never' else 'never'), '>20') + ' | ' + \
lease['client-hostname'])
print('+-----------------+-------------------+----------------------+-----------------')
print('| Total Active Leases: ' + str(len(report_dataset)))
print('| Report generated (UTC): ' + str(now))
print('+------------------------------------------------------------------------------')

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
  • 222.
  • 223.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
  • 233.
  • 234.
  • 235.
  • 236.
  • 237.
  • 238.
  • 239.
  • 240.
  • 241.
  • 242.
  • 243.
  • 244.
  • 245.
  • 246.
  • 247.
  • 248.
  • 249.
  • 250.
  • 251.
  • 252.
  • 253.
  • 254.
  • 255.
  • 256.
  • 257.
  • 258.
  • 259.

I feel like the operation and maintenance work , Easy again ...

My level is very high low, I can't learn. , As the saying goes We don't produce code , Just a porter in the code world .

I've collected a lot of scripts before , Unified in their own code base

https://gitee.com/yashirochaos/yangchao

Not now python Our cloud computing engineers are not good networkers Come on, guys

版权声明
本文为[Leymus chinensis]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/05/20210530165826246n.html

  1. 【推荐】常见的Python数据可视化库
  2. 基于Python3.3+Selenium3.0框架实战Web自动化测试实战(百度网站实测项目)
  3. 【django轻量级框架】用Mysql的各种项目响应速度慢?一招解决!
  4. 【django轻量级框架】Django项目导入css,js,images等静态文件
  5. 【django轻量级框架】HTML上传文件拦截到本地
  6. 【深度学习入门到精通系列】留一交叉验证法Python实现(看不懂你来打我~!)
  7. Python机器学习笔记:sklearn库的学习
  8. python【Opencv计算机视觉库】opencv模块cv2常用函数用法(全)
  9. python基础练习(七)
  10. python基础练习(八)
  11. python基础练习(九)
  12. python基础练习(十)
  13. python新增练习(一)
  14. python新增练习(二)
  15. python新增练习(三)
  16. Python中的排序sorted(d.items(), key=lambda x: x[1])
  17. python 判断字母大小写
  18. python绘制科赫雪花(递归)
  19. 解决cmd命令查看python版本“python不是内部命令或外部命令,也不是可执行程序解决方案”的问题
  20. Python Numpy介绍
  21. python —pandas库常用函数
  22. Python应用matplotlib绘图简介
  23. Python matplotlib高级绘图详解
  24. 入门训练 Fibonacci数列-python实现
  25. Python -二维数组定义
  26. python二进制相加
  27. Python文本处理:解析json格式的数据
  28. 查看python安装路径
  29. Python编程之计算生态
  30. Python-turtle标准库知识小结(python绘图工具)
  31. Python-time标准库知识小结
  32. Python-random标准库知识小结
  33. python安装第三方库的三种方法
  34. python程序的控制结构
  35. Python程序的函数和代码复用
  36. python之组合数据类型
  37. python【力扣LeetCode算法题库】300 最长上升子序列(动态规划)
  38. python【力扣LeetCode算法题库】695- 岛屿的最大面积(深搜)
  39. python【力扣LeetCode算法题库】面试题 01.06-字符串压缩
  40. python【力扣LeetCode算法题库】1160-拼写单词
  41. python【力扣LeetCode算法题库】836- 矩形重叠
  42. python【力扣LeetCode算法题库】409-最长回文串(数学 计数器)
  43. python【力扣LeetCode算法题库】面试题40- 最小的k个数
  44. python【力扣LeetCode算法题库】945- 使数组唯一的最小增量
  45. python【力扣LeetCode算法题库】365- 水壶问题(裴蜀等式)
  46. python【力扣LeetCode算法题库】876- 链表的中间结点
  47. python【力扣LeetCode算法题库】面试题 17.16- 按摩师(DP)
  48. python【力扣LeetCode算法题库】892-三维形体的表面积
  49. python【力扣LeetCode算法题库】999-车的可用捕获量(DFS)
  50. python【力扣LeetCode算法题库】914. 卡牌分组(reduce & collections.Counter)
  51. python【力扣LeetCode算法题库】820- 单词的压缩编码
  52. python【力扣LeetCode算法题库】1162- 地图分析(BFS)
  53. python【力扣LeetCode算法题库】面试题62- 圆圈中最后剩下的数字(约瑟夫环)
  54. python【力扣LeetCode算法题库】912- 排序数组
  55. python【力扣LeetCode算法题库】1111- 有效括号的嵌套深度
  56. python【力扣LeetCode算法题库】289- 生命游戏
  57. python【力扣LeetCode算法题库】12- 整数转罗马数字(打表 模拟)
  58. python【数据结构与算法】内置函数enumerate(枚举) 函数(看不懂你来打我)
  59. python【力扣LeetCode算法题库】13- 罗马数字转整数
  60. python【数据结构与算法】内置函数 zip() 函数(看不懂你来打我)