check_active-leases 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. q#!/usr/bin/python
  2. import datetime, bisect
  3. def parse_timestamp(raw_str):
  4. tokens = raw_str.split()
  5. if len(tokens) == 1:
  6. if tokens[0].lower() == 'never':
  7. return 'never';
  8. else:
  9. raise Exception('Parse error in timestamp')
  10. elif len(tokens) == 3:
  11. return datetime.datetime.strptime(' '.join(tokens[1:]),
  12. '%Y/%m/%d %H:%M:%S')
  13. else:
  14. raise Exception('Parse error in timestamp')
  15. def timestamp_is_ge(t1, t2):
  16. if t1 == 'never':
  17. return True
  18. elif t2 == 'never':
  19. return False
  20. else:
  21. return t1 >= t2
  22. def timestamp_is_lt(t1, t2):
  23. if t1 == 'never':
  24. return False
  25. elif t2 == 'never':
  26. return t1 != 'never'
  27. else:
  28. return t1 < t2
  29. def timestamp_is_between(t, tstart, tend):
  30. return timestamp_is_ge(t, tstart) and timestamp_is_lt(t, tend)
  31. def parse_hardware(raw_str):
  32. tokens = raw_str.split()
  33. if len(tokens) == 2:
  34. return tokens[1]
  35. else:
  36. raise Exception('Parse error in hardware')
  37. def strip_endquotes(raw_str):
  38. return raw_str.strip('"')
  39. def identity(raw_str):
  40. return raw_str
  41. def parse_binding_state(raw_str):
  42. tokens = raw_str.split()
  43. if len(tokens) == 2:
  44. return tokens[1]
  45. else:
  46. raise Exception('Parse error in binding state')
  47. def parse_next_binding_state(raw_str):
  48. tokens = raw_str.split()
  49. if len(tokens) == 3:
  50. return tokens[2]
  51. else:
  52. raise Exception('Parse error in next binding state')
  53. def parse_rewind_binding_state(raw_str):
  54. tokens = raw_str.split()
  55. if len(tokens) == 3:
  56. return tokens[2]
  57. else:
  58. raise Exception('Parse error in next binding state')
  59. def parse_leases_file(leases_file):
  60. valid_keys = {
  61. 'starts': parse_timestamp,
  62. 'ends': parse_timestamp,
  63. 'tstp': parse_timestamp,
  64. 'tsfp': parse_timestamp,
  65. 'atsfp': parse_timestamp,
  66. 'cltt': parse_timestamp,
  67. 'hardware': parse_hardware,
  68. 'binding': parse_binding_state,
  69. 'next': parse_next_binding_state,
  70. 'rewind': parse_rewind_binding_state,
  71. 'uid': strip_endquotes,
  72. 'client-hostname': strip_endquotes,
  73. 'option': identity,
  74. 'set': identity,
  75. 'on': identity,
  76. 'abandoned': None,
  77. 'bootp': None,
  78. 'reserved': None,
  79. }
  80. leases_db = {}
  81. lease_rec = {}
  82. in_lease = False
  83. in_failover = False
  84. for line in leases_file:
  85. if line.lstrip().startswith('#'):
  86. continue
  87. tokens = line.split()
  88. if len(tokens) == 0:
  89. continue
  90. key = tokens[0].lower()
  91. if key == 'lease':
  92. if not in_lease:
  93. ip_address = tokens[1]
  94. lease_rec = {'ip_address' : ip_address}
  95. in_lease = True
  96. else:
  97. raise Exception('Parse error in leases file')
  98. elif key == 'failover':
  99. in_failover = True
  100. elif key == '}':
  101. if in_lease:
  102. for k in valid_keys:
  103. if callable(valid_keys[k]):
  104. lease_rec[k] = lease_rec.get(k, '')
  105. else:
  106. lease_rec[k] = False
  107. ip_address = lease_rec['ip_address']
  108. if ip_address in leases_db:
  109. leases_db[ip_address].insert(0, lease_rec)
  110. else:
  111. leases_db[ip_address] = [lease_rec]
  112. lease_rec = {}
  113. in_lease = False
  114. elif in_failover:
  115. in_failover = False
  116. continue
  117. else:
  118. raise Exception('Parse error in leases file')
  119. elif key in valid_keys:
  120. if in_lease:
  121. value = line[(line.index(key) + len(key)):]
  122. value = value.strip().rstrip(';').rstrip()
  123. if callable(valid_keys[key]):
  124. lease_rec[key] = valid_keys[key](value)
  125. else:
  126. lease_rec[key] = True
  127. else:
  128. raise Exception('Parse error in leases file')
  129. else:
  130. if in_lease:
  131. raise Exception('Parse error in leases file')
  132. if in_lease:
  133. raise Exception('Parse error in leases file')
  134. return leases_db
  135. def round_timedelta(tdelta):
  136. return datetime.timedelta(tdelta.days,
  137. tdelta.seconds + (0 if tdelta.microseconds < 500000 else 1))
  138. def timestamp_now():
  139. n = datetime.datetime.utcnow()
  140. return datetime.datetime(n.year, n.month, n.day, n.hour, n.minute,
  141. n.second + (0 if n.microsecond < 500000 else 1))
  142. def lease_is_active(lease_rec, as_of_ts):
  143. return timestamp_is_between(as_of_ts, lease_rec['starts'],
  144. lease_rec['ends'])
  145. def ipv4_to_int(ipv4_addr):
  146. parts = ipv4_addr.split('.')
  147. return (int(parts[0]) << 24) + (int(parts[1]) << 16) + \
  148. (int(parts[2]) << 8) + int(parts[3])
  149. def select_active_leases(leases_db, as_of_ts):
  150. retarray = []
  151. sortedarray = []
  152. for ip_address in leases_db:
  153. lease_rec = leases_db[ip_address][0]
  154. if lease_is_active(lease_rec, as_of_ts):
  155. ip_as_int = ipv4_to_int(ip_address)
  156. insertpos = bisect.bisect(sortedarray, ip_as_int)
  157. sortedarray.insert(insertpos, ip_as_int)
  158. retarray.insert(insertpos, lease_rec)
  159. return retarray
  160. ##############################################################################
  161. myfile = open('/var/lib/dhcp/dhcpd.leases', 'r')
  162. leases = parse_leases_file(myfile)
  163. myfile.close()
  164. now = timestamp_now()
  165. report_dataset = select_active_leases(leases, now)
  166. print('Active Leases: ' + str(len(report_dataset)))