Skip to content

Instantly share code, notes, and snippets.

@ageis
Created February 12, 2018 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ageis/bb45fe818e9fbce95c4f23ce31a7b0dc to your computer and use it in GitHub Desktop.
Save ageis/bb45fe818e9fbce95c4f23ce31a7b0dc to your computer and use it in GitHub Desktop.
Simple Prometheus exporter in Python for traffic metrics from a running Tor daemon.
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Simple Prometheus exporter for traffic metrics
from a running Tor daemon. """
import re
import time
import sys
from prometheus_client import start_http_server, Gauge
import stem
from stem.control import Controller
TOR_CONTROL_PORT = 9051
TOR_SOCKET_PATH = '/var/run/tor/control'
TOR_AUTH_COOKIE_PATH = '/var/run/tor/control.authcookie'
TOR_TRAFFIC_READ = Gauge('tor_traffic_read', 'Bytes read by Tor')
TOR_TRAFFIC_WRITTEN = Gauge('tor_traffic_written', 'Bytes written by Tor')
def main():
try:
controller = Controller.from_port(port=TOR_CONTROL_PORT)
except stem.SocketError as exc:
print("Unable to connect to Tor on port 9051: %s" % exc)
try:
controller = Controller.from_socket_file(path=TOR_SOCKET_PATH)
except stem.SocketError as exc:
print("Unable to connect to Tor via control socket: %s" % exc)
sys.exit(1)
sys.exit(1)
with open(TOR_AUTH_COOKIE_PATH, "rb") as auth_cookie_file:
tor_auth_cookie = auth_cookie_file.read()
try:
controller.authenticate()
except stem.connection.AuthenticationFailure as exc:
print("Unable to authenticate to Tor: %s" % exc)
sys.exit(1)
version_str = str(controller.get_version())
regex = re.compile(r"(\d+\.\d+\.\d+.\d+)")
version = str(re.findall(regex, version_str))
print("Tor is running version %s" % version)
start_http_server(9052)
while True:
bytes_read = controller.get_info("traffic/read")
bytes_written = controller.get_info("traffic/written")
TOR_TRAFFIC_READ.set(bytes_read)
TOR_TRAFFIC_WRITTEN.set(bytes_written)
time.sleep(300)
controller.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment