pihole.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. query_type_point = Point("query_types").time(timestamp).tag("hostname", self.host)
  126. for key, value in query_types.items():
  127. query_type_point.field(key, float(value))
  128. yield query_type_point
  129. forward_destinations = self.request_forward_destinations()
  130. forward_destinations_point = Point("forward_destinations").time(timestamp).tag("hostname", self.host)
  131. for key, value in forward_destinations.items():
  132. forward_destinations_point.field(key.split('|')[0], value)
  133. yield forward_destinations_point
  134. def get_queries_for_influxdb(self, query_date: datetime, sample_period: int):
  135. # Get all queries since last sample
  136. end_time = query_date.timestamp()
  137. start_time = end_time - sample_period + 1
  138. queries = self.request_all_queries(start_time, end_time)
  139. timestamp = datetime.now().astimezone()
  140. df = DataFrame(queries, columns=['time', 'query_type', 'domain', 'client', 'status', 'destination', 'reply_type', 'reply_time', 'dnssec'])
  141. # we still need some stats from the summary
  142. summary = self.request_summary()
  143. yield Point("domains") \
  144. .time(timestamp) \
  145. .tag("hostname", self.host) \
  146. .field("domain_count", summary['domains_being_blocked']) \
  147. .field("unique_domains", len(df.groupby('domain'))) \
  148. .field("forwarded", len(df[df['status'] == QueryStati.Forwarded.value])) \
  149. .field("cached", len(df[df['status'] == QueryStati.Cached.value]))
  150. blocked_count = len(df[(df['status'] == QueryStati.Blocked.value) | (df['status'] == QueryStati.Wildcard.value)])
  151. queries_point = Point("queries") \
  152. .time(timestamp) \
  153. .tag("hostname", self.host) \
  154. .field("queries", len(df)) \
  155. .field("blocked", blocked_count) \
  156. .field("ads_percentage", blocked_count * 100.0 / max(1, len(df)))
  157. yield queries_point
  158. for key, client_df in df.groupby('client'):
  159. blocked_count = len(client_df[(client_df['status'] == QueryStati.Blocked.value) | (client_df['status'] == QueryStati.Wildcard.value)])
  160. clients_point = Point("clients") \
  161. .time(timestamp) \
  162. .tag("hostname", self.host) \
  163. .tag("client", key) \
  164. .field("queries", len(client_df)) \
  165. .field("blocked", blocked_count) \
  166. .field("ads_percentage", blocked_count * 100.0 / max(1, len(client_df)))
  167. yield clients_point
  168. yield Point("other") \
  169. .time(timestamp) \
  170. .tag("hostname", self.host) \
  171. .field("status", summary['status'] == 'enabled') \
  172. .field("gravity_last_update", summary['gravity_last_updated']['absolute'])
  173. query_type_point = Point("query_types").time(timestamp).tag("hostname", self.host)
  174. for key, group_df in df.groupby('query_type'):
  175. query_type_point.field(key, len(group_df))
  176. yield query_type_point
  177. forward_destinations_point = Point("forward_destinations").time(timestamp).tag("hostname", self.host)
  178. for key, group_df in df.groupby('destination'):
  179. forward_destinations_point.field(key.split('|')[0], len(group_df))
  180. yield forward_destinations_point
  181. def get_logs_for_influxdb(self, query_date: datetime, sample_period: int):
  182. end_time = query_date.timestamp()
  183. start_time = end_time - sample_period + 1
  184. for data in self.request_all_queries(start_time, end_time):
  185. timestamp, query_type, domain, client, status, destination, reply_type, reply_time, dnssec = data
  186. p = Point("logs") \
  187. .time(datetime.fromtimestamp(timestamp)) \
  188. .tag("hostname", self.host) \
  189. .tag("query_type", query_type) \
  190. .field("domain", domain) \
  191. .tag("client", client) \
  192. .tag("status", QueryStati(status)) \
  193. .tag("dnssec", dnssec != 0) \
  194. .field("reply_time", reply_time)
  195. if destination:
  196. p.tag("destination", destination)
  197. yield p
  198. if __name__ == "__main__":
  199. import argparse
  200. parser = argparse.ArgumentParser(description='Export Pi-Hole statistics')
  201. parser.add_argument('--host', required=True, type=str, help='Pi-Hole host')
  202. parser.add_argument('--token', '-t', required=True, type=str, help='Pi-Hole API token')
  203. args = parser.parse_args()
  204. pihole = PiHole(host=args.host, token=args.token)
  205. points = list(pihole.get_queries_for_influxdb(datetime.now(), 600))
  206. for p in points:
  207. print(p._time, p._name, p._tags, p._fields)