1
0

pihole.py 7.9 KB

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