Lease File Parsing Madness
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.py 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #!/usr/bin/python3
  2. import datetime, bisect
  3. print("Content-type: text/html")
  4. print("")
  5. # Below code copied from a script from a forgotten source on the internet.
  6. def parse_timestamp(raw_str):
  7. tokens = raw_str.split()
  8. if len(tokens) == 1:
  9. if tokens[0].lower() == 'never':
  10. return 'never';
  11. else:
  12. raise Exception('Parse error in timestamp')
  13. elif len(tokens) == 3:
  14. return datetime.datetime.strptime(' '.join(tokens[1:]),
  15. '%Y/%m/%d %H:%M:%S')
  16. else:
  17. raise Exception('Parse error in timestamp')
  18. def timestamp_is_ge(t1, t2):
  19. if type(t2) == type(""):
  20. return False
  21. if t1 == 'never':
  22. return True
  23. elif t2 == 'never':
  24. return False
  25. else:
  26. return t1 >= t2
  27. def timestamp_is_lt(t1, t2):
  28. if type(t2) == type(""):
  29. return t1 != 'never'
  30. if t1 == 'never':
  31. return False
  32. elif t2 == 'never':
  33. return t1 != 'never'
  34. else:
  35. return t1 < t2
  36. def timestamp_is_between(t, tstart, tend):
  37. return timestamp_is_ge(t, tstart) and timestamp_is_lt(t, tend)
  38. def parse_hardware(raw_str):
  39. tokens = raw_str.split()
  40. if len(tokens) == 2:
  41. return tokens[1]
  42. else:
  43. raise Exception('Parse error in hardware')
  44. def strip_endquotes(raw_str):
  45. return raw_str.strip('"')
  46. def identity(raw_str):
  47. return raw_str
  48. def parse_binding_state(raw_str):
  49. tokens = raw_str.split()
  50. if len(tokens) == 2:
  51. return tokens[1]
  52. else:
  53. raise Exception('Parse error in binding state')
  54. def parse_next_binding_state(raw_str):
  55. tokens = raw_str.split()
  56. if len(tokens) == 3:
  57. return tokens[2]
  58. else:
  59. raise Exception('Parse error in next binding state')
  60. def parse_rewind_binding_state(raw_str):
  61. tokens = raw_str.split()
  62. if len(tokens) == 3:
  63. return tokens[2]
  64. else:
  65. raise Exception('Parse error in next binding state')
  66. def parse_leases_file(leases_file):
  67. valid_keys = {
  68. 'starts': parse_timestamp,
  69. 'ends': parse_timestamp,
  70. 'tstp': parse_timestamp,
  71. 'tsfp': parse_timestamp,
  72. 'atsfp': parse_timestamp,
  73. 'cltt': parse_timestamp,
  74. 'hardware': parse_hardware,
  75. 'binding': parse_binding_state,
  76. 'next': parse_next_binding_state,
  77. 'rewind': parse_rewind_binding_state,
  78. 'uid': strip_endquotes,
  79. 'client-hostname': strip_endquotes,
  80. 'option': identity,
  81. 'set': identity,
  82. 'on': identity,
  83. 'abandoned': None,
  84. 'bootp': None,
  85. 'reserved': None,
  86. }
  87. leases_db = {}
  88. lease_rec = {}
  89. in_lease = False
  90. in_failover = False
  91. for line in leases_file:
  92. if line.lstrip().startswith('#'):
  93. continue
  94. tokens = line.split()
  95. if len(tokens) == 0:
  96. continue
  97. key = tokens[0].lower()
  98. if key == 'lease':
  99. if not in_lease:
  100. ip_address = tokens[1]
  101. lease_rec = {'ip_address' : ip_address}
  102. in_lease = True
  103. else:
  104. raise Exception('Parse error in leases file')
  105. elif key == 'failover':
  106. in_failover = True
  107. elif key == '}':
  108. if in_lease:
  109. for k in valid_keys:
  110. if callable(valid_keys[k]):
  111. lease_rec[k] = lease_rec.get(k, '')
  112. else:
  113. lease_rec[k] = False
  114. ip_address = lease_rec['ip_address']
  115. if ip_address in leases_db:
  116. leases_db[ip_address].insert(0, lease_rec)
  117. else:
  118. leases_db[ip_address] = [lease_rec]
  119. lease_rec = {}
  120. in_lease = False
  121. elif in_failover:
  122. in_failover = False
  123. continue
  124. else:
  125. raise Exception('Parse error in leases file')
  126. elif key in valid_keys:
  127. if in_lease:
  128. value = line[(line.index(key) + len(key)):]
  129. value = value.strip().rstrip(';').rstrip()
  130. if callable(valid_keys[key]):
  131. lease_rec[key] = valid_keys[key](value)
  132. else:
  133. lease_rec[key] = True
  134. else:
  135. raise Exception('Parse error in leases file')
  136. else:
  137. if in_lease:
  138. raise Exception('Parse error in leases file')
  139. if in_lease:
  140. raise Exception('Parse error in leases file')
  141. return leases_db
  142. def round_timedelta(tdelta):
  143. return datetime.timedelta(tdelta.days,
  144. tdelta.seconds + (0 if tdelta.microseconds < 500000 else 1))
  145. def timestamp_now():
  146. n = datetime.datetime.utcnow()
  147. return datetime.datetime(n.year, n.month, n.day, n.hour, n.minute,
  148. n.second + (0 if n.microsecond < 500000 else 1))
  149. def lease_is_active(lease_rec, as_of_ts):
  150. return timestamp_is_between(as_of_ts, lease_rec['starts'],
  151. lease_rec['ends'])
  152. def ipv4_to_int(ipv4_addr):
  153. parts = ipv4_addr.split('.')
  154. return (int(parts[0]) << 24) + (int(parts[1]) << 16) + \
  155. (int(parts[2]) << 8) + int(parts[3])
  156. def select_active_leases(leases_db, as_of_ts):
  157. retarray = []
  158. sortedarray = []
  159. for ip_address in leases_db:
  160. lease_rec = leases_db[ip_address][0]
  161. if lease_is_active(lease_rec, as_of_ts):
  162. ip_as_int = ipv4_to_int(ip_address)
  163. insertpos = bisect.bisect(sortedarray, ip_as_int)
  164. sortedarray.insert(insertpos, ip_as_int)
  165. retarray.insert(insertpos, lease_rec)
  166. return retarray
  167. # End of the other code
  168. #############################
  169. # Searches for insert segments in the HTML code, ex: <!-- INSERT X HERE -->
  170. def insert_item(text, search, insert):
  171. parts = text.split(search, 1)
  172. # If this is 2 parts, then we have a split string. Otherwise, bail.
  173. if len(parts) == 1:
  174. return text
  175. else:
  176. before = parts[0].rsplit("<!--", 1)[0]
  177. after = parts[1].split("-->", 1)[1]
  178. return before + insert + after
  179. ###############################
  180. try:
  181. #myfile = open('leases.leases','r')
  182. myfile = open('/var/lib/dhcp/dhcpd.leases', 'r')
  183. leases = parse_leases_file(myfile)
  184. myfile.close()
  185. now = timestamp_now()
  186. report_dataset = select_active_leases(leases, now)
  187. # read in the index file, and place it in idx
  188. idx_file = open("index-src.html")
  189. idx = ""
  190. for line in idx_file:
  191. idx += line + "\n"
  192. # Done reading in the file. Now to parse and replace, and return, if success
  193. repl = ""
  194. for lease in report_dataset:
  195. try:
  196. if lease['ends'] != 'never':
  197. expires = str(lease['ends'] - now)
  198. repl += "<tr><td>"
  199. repl += lease['ip_address']
  200. repl += "</td><td>"
  201. repl += lease['hardware']
  202. repl += "</td><td>"
  203. if lease['ends'] == 'never':
  204. repl += "never"
  205. else:
  206. repl += str(lease['ends'] - now)
  207. repl += "</td><td>"
  208. repl += lease['client-hostname']
  209. repl += "</td></tr>\n"
  210. except:
  211. pass
  212. active = str(len(report_dataset))
  213. report_gen = str(now)
  214. stats = "<h4>Total active leases: {}</h4><h4>Report generated {}</h4>".format(active, report_gen)
  215. idx = insert_item(idx, "INSERT LEASE TABLE", repl)
  216. idx = insert_item(idx, "INSERT STATS", stats)
  217. print (idx)
  218. except Exception as e:
  219. print("<html><body>")
  220. print("There was an error on the server end. We are sorry.")
  221. print("Perhaps try the <a href=\"index-src.html\">static version</a> of this page.")
  222. print("The error encountered is listed below: <br/><br/>{}<br/>".format(str(e).replace("\n", "<br/>")))
  223. print("</body></html>")