pihole.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import requests
  4. from datetime import datetime
  5. from enum import Enum
  6. from influxdb_client import Point
  7. from pandas import DataFrame
  8. class QueryStati(Enum):
  9. Blocked = 1
  10. Forwarded = 2
  11. Cached = 3
  12. Wildcard = 4
  13. Unknown = 5
  14. class PiHole:
  15. def __init__(self, host, token):
  16. self.host = host
  17. if host.startswith("http"):
  18. self.url = host
  19. else:
  20. self.url = f"http://{host}"
  21. self.token = token
  22. def query(self, endpoint, params={}):
  23. return requests.get(f"{self.url}/admin/{endpoint}.php", params=params)
  24. def request_all_queries(self, start: float, end: float):
  25. """
  26. keys[]: time, query_type, domain, client, status, destination, reply_type, reply_time, dnssec
  27. """
  28. if not self.token:
  29. raise Exception("Token required")
  30. params = {
  31. "getAllQueries": "",
  32. "from": int(start),
  33. "until": int(end),
  34. "auth": self.token
  35. }
  36. json = self.query("api_db", params=params).json()
  37. if json:
  38. return json['data']
  39. else:
  40. return []
  41. def request_summary(self):
  42. """
  43. keys:
  44. - domains_being_blocked
  45. - dns_queries_today
  46. - ads_blocked_today
  47. - ads_percentage_today
  48. - unique_domains
  49. - queries_forwarded
  50. - queries_cached
  51. - clients_ever_seen
  52. - unique_clients
  53. - dns_queries_all_types
  54. - reply_UNKNOWN
  55. - reply_NODATA
  56. - reply_NXDOMAIN
  57. - reply_CNAME
  58. - reply_IP
  59. - reply_DOMAIN
  60. - reply_RRNAME
  61. - reply_SERVFAIL
  62. - reply_REFUSED
  63. - reply_NOTIMP
  64. - reply_OTHER
  65. - reply_DNSSEC
  66. - reply_NONE
  67. - reply_BLOB
  68. - dns_queries_all_replies
  69. - privacy_level
  70. - status
  71. - gravity_last_update: file_exists, absolute, relative
  72. """
  73. json = self.query("api").json()
  74. return json
  75. def request_forward_destinations(self):
  76. if not self.token:
  77. raise Exception("Token required")
  78. params = {
  79. "getForwardDestinations": "",
  80. "auth": self.token
  81. }
  82. json = self.query("api", params=params).json()
  83. if json:
  84. return json['forward_destinations']
  85. else:
  86. return {}
  87. def request_query_types(self):
  88. if not self.token:
  89. raise Exception("Token required")
  90. params = {
  91. "getQueryTypes": "",
  92. "auth": self.token
  93. }
  94. json = self.query("api", params=params).json()
  95. if json:
  96. return json['querytypes']
  97. else:
  98. return {}
  99. def get_totals_for_influxdb(self):
  100. summary = self.request_summary()
  101. timestamp = datetime.now().astimezone()
  102. yield Point("domains") \
  103. .time(timestamp) \
  104. .tag("hostname", self.host) \
  105. .field("domain_count", summary['domains_being_blocked']) \
  106. .field("unique_domains", summary['unique_domains']) \
  107. .field("forwarded", summary['queries_forwarded']) \
  108. .field("cached", summary['queries_cached'])
  109. yield Point("queries") \
  110. .time(timestamp) \
  111. .tag("hostname", self.host) \
  112. .field("queries", summary['dns_queries_today']) \
  113. .field("blocked", summary['ads_blocked_today']) \
  114. .field("ads_percentage", summary['ads_percentage_today'])
  115. yield Point("clients") \
  116. .time(timestamp) \
  117. .tag("hostname", self.host) \
  118. .field("total_clients", summary['clients_ever_seen']) \
  119. .field("unique_clients", summary['unique_clients']) \
  120. .field("total_queries", summary['dns_queries_all_types'])
  121. yield Point("other") \
  122. .time(timestamp) \
  123. .tag("hostname", self.host) \
  124. .field("status", summary['status'] == 'enabled') \
  125. .field("gravity_last_update", summary['gravity_last_updated']['absolute'])
  126. if self.token:
  127. query_types = self.request_query_types()
  128. for key, value in query_types.items():
  129. yield Point("query_types") \
  130. .time(timestamp) \
  131. .tag("hostname", self.host) \
  132. .tag("query_type", key) \
  133. .field("value", float(value))
  134. forward_destinations = self.request_forward_destinations()
  135. for key, value in forward_destinations.items():
  136. yield Point("forward_destinations") \
  137. .time(timestamp) \
  138. .tag("hostname", self.host) \
  139. .tag("destination", key.split('|')[0]) \
  140. .field("value", float(value))
  141. def get_queries_for_influxdb(self, query_date: datetime, sample_period: int):
  142. # Get all queries since last sample
  143. end_time = query_date.timestamp()
  144. start_time = end_time - sample_period + 1
  145. queries = self.request_all_queries(start_time, end_time)
  146. timestamp = datetime.now().astimezone()
  147. df = DataFrame(queries, columns=['time', 'query_type', 'domain', 'client', 'status', 'destination', 'reply_type', 'reply_time', 'dnssec'])
  148. # we still need some stats from the summary
  149. summary = self.request_summary()
  150. yield Point("domains") \
  151. .time(timestamp) \
  152. .tag("hostname", self.host) \
  153. .field("domain_count", summary['domains_being_blocked']) \
  154. .field("unique_domains", len(df.groupby('domain'))) \
  155. .field("forwarded", len(df[df['status'] == QueryStati.Forwarded.value])) \
  156. .field("cached", len(df[df['status'] == QueryStati.Cached.value]))
  157. blocked_count = len(df[(df['status'] == QueryStati.Blocked.value) | (df['status'] == QueryStati.Wildcard.value)])
  158. queries_point = Point("queries") \
  159. .time(timestamp) \
  160. .tag("hostname", self.host) \
  161. .field("queries", len(df)) \
  162. .field("blocked", blocked_count) \
  163. .field("ads_percentage", blocked_count * 100.0 / max(1, len(df)))
  164. yield queries_point
  165. for key, client_df in df.groupby('client'):
  166. blocked_count = len(client_df[(client_df['status'] == QueryStati.Blocked.value) | (client_df['status'] == QueryStati.Wildcard.value)])
  167. clients_point = Point("clients") \
  168. .time(timestamp) \
  169. .tag("hostname", self.host) \
  170. .tag("client", key) \
  171. .field("queries", len(client_df)) \
  172. .field("blocked", blocked_count) \
  173. .field("ads_percentage", blocked_count * 100.0 / max(1, len(client_df)))
  174. yield clients_point
  175. yield Point("other") \
  176. .time(timestamp) \
  177. .tag("hostname", self.host) \
  178. .field("status", summary['status'] == 'enabled') \
  179. .field("gravity_last_update", summary['gravity_last_updated']['absolute'])
  180. for key, group_df in df.groupby('query_type'):
  181. yield Point("query_types") \
  182. .time(timestamp) \
  183. .tag("hostname", self.host) \
  184. .tag("query_type", key) \
  185. .field("queries", len(group_df))
  186. for key, group_df in df.groupby('destination'):
  187. yield Point("forward_destinations") \
  188. .time(timestamp) \
  189. .tag("hostname", self.host) \
  190. .tag("destination", key.split('|')[0]) \
  191. .field("queries", len(group_df))
  192. def get_query_logs_for_influxdb(self, query_date: datetime, sample_period: int):
  193. end_time = query_date.timestamp()
  194. start_time = end_time - sample_period + 1
  195. for data in self.request_all_queries(start_time, end_time):
  196. timestamp, query_type, domain, client, status, destination, reply_type, reply_time, dnssec = data
  197. p = Point("logs") \
  198. .time(datetime.fromtimestamp(timestamp)) \
  199. .tag("hostname", self.host) \
  200. .tag("query_type", query_type) \
  201. .field("domain", domain) \
  202. .tag("client", client) \
  203. .tag("status", QueryStati(status)) \
  204. .tag("dnssec", dnssec != 0) \
  205. .field("reply_time", reply_time)
  206. if destination:
  207. p.tag("destination", destination)
  208. yield p
  209. if __name__ == "__main__":
  210. import argparse
  211. parser = argparse.ArgumentParser(description='Export Pi-Hole statistics')
  212. parser.add_argument('--host', required=True, type=str, help='Pi-Hole host')
  213. parser.add_argument('--token', '-t', required=True, type=str, help='Pi-Hole API token')
  214. args = parser.parse_args()
  215. pihole = PiHole(host=args.host, token=args.token)
  216. points = list(pihole.get_queries_for_influxdb(datetime.now(), 600))
  217. for p in points:
  218. print(p._time, p._name, p._tags, p._fields)