Files
tailscale-tools/tailscale-api.py
alf 11f01df528 Add tailscale-api.py: HTTP-API für Homepage
- Python-HTTP-Server stellt Tailscale-Traffic als JSON bereit
- Pro Gerät: Upload/Download in Mbit/s, Online-Status
- Gesamtwerte und Peer-Statistik
- systemd-Service-Datei inklusive
- Homepage Widget Beispiel-Konfiguration
- Läuft direkt auf dem Exit-Node (kein Docker nötig)

Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-10-28 13:54:31 +01:00

125 lines
4.2 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# tailscale-api.py – Tailscale Traffic API für Homepage
# Läuft auf dem Exit-Node und stellt JSON über HTTP bereit.
#
# Aufruf: python3 tailscale-api.py
# URL: http://<exit-node-ip>:8080/tailscale
#
# Benötigt: tailscale CLI, Python 3
import json
import subprocess
import time
from http.server import HTTPServer, BaseHTTPRequestHandler
PORT = 8080
MEASURE_INTERVAL = 1 # Sekunden zwischen zwei Messungen für Rate-Berechnung
MAX_DEVICES = 10 # Maximale Anzahl Geräte in der Ausgabe
def get_tailscale_status():
"""Holt den aktuellen Tailscale-Status als dict."""
result = subprocess.run(
['tailscale', 'status', '--json'],
capture_output=True, text=True, check=True
)
return json.loads(result.stdout)
def calculate_rates():
"""Berechnet Upload/Download-Raten pro Gerät in Mbit/s."""
# Zwei Messungen im Abstand von MEASURE_INTERVAL Sekunden
snap1 = get_tailscale_status()
time.sleep(MEASURE_INTERVAL)
snap2 = get_tailscale_status()
devices = []
# Self (lokaler Computer / Exit-Node)
self1 = snap1.get('Self', {})
self2 = snap2.get('Self', {})
if self2.get('HostName'):
tx_diff = max(0, self2.get('TxBytes', 0) - self1.get('TxBytes', 0))
rx_diff = max(0, self2.get('RxBytes', 0) - self1.get('RxBytes', 0))
devices.append({
'name': self2.get('HostName', 'unknown'),
'upload_mbit': round(tx_diff * 8 / MEASURE_INTERVAL / 1e6, 2),
'download_mbit': round(rx_diff * 8 / MEASURE_INTERVAL / 1e6, 2),
'online': self2.get('Online', False),
'type': 'self'
})
# Peers (alle anderen Geräte)
peers1 = snap1.get('Peer', {})
peers2 = snap2.get('Peer', {})
for key, peer2 in peers2.items():
peer1 = peers1.get(key, {})
host_name = peer2.get('HostName')
if not host_name:
continue
tx_diff = max(0, peer2.get('TxBytes', 0) - peer1.get('TxBytes', 0))
rx_diff = max(0, peer2.get('RxBytes', 0) - peer1.get('RxBytes', 0))
devices.append({
'name': host_name,
'upload_mbit': round(tx_diff * 8 / MEASURE_INTERVAL / 1e6, 2),
'download_mbit': round(rx_diff * 8 / MEASURE_INTERVAL / 1e6, 2),
'online': peer2.get('Online', False),
'type': 'peer'
})
# Sortiere nach Gesamttraffic (upload + download), aktivste zuerst
devices.sort(key=lambda d: d['upload_mbit'] + d['download_mbit'], reverse=True)
# Auf MAX_DEVICES begrenzen
devices = devices[:MAX_DEVICES]
# Gesamtwerte
total_upload = sum(d['upload_mbit'] for d in devices)
total_download = sum(d['download_mbit'] for d in devices)
return {
'devices': devices,
'total': {
'upload_mbit': round(total_upload, 2),
'download_mbit': round(total_download, 2)
},
'peers_online': sum(1 for d in devices if d['online'] and d['type'] == 'peer'),
'peers_total': len([d for d in devices if d['type'] == 'peer']),
'self_name': self2.get('HostName', 'unknown')
}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path in ('/tailscale', '/tailscale.json', '/'):
try:
data = calculate_rates()
response = json.dumps(data, indent=2).encode()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(response)
except Exception as e:
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'error': str(e)}).encode())
else:
self.send_response(404)
self.end_headers()
def log_message(self, format, *args):
# Logging reduzieren (nur Fehler)
pass
if __name__ == '__main__':
print(f'Tailscale API läuft auf Port {PORT}')
print(f'URL: http://100.87.87.105:{PORT}/tailscale')
print(f'Zum Testen: curl http://localhost:{PORT}/tailscale')
HTTPServer(('0.0.0.0', PORT), Handler).serve_forever()