Files
random-api-calls/wireguard/wg_health.py
2026-03-14 00:19:44 +00:00

47 lines
1.8 KiB
Python

# wg_health.py
from flask import Flask, jsonify
import subprocess
# Name of your WireGuard interface (e.g., wg0, wg-server)
# Find it by running `sudo wg show`
WIREGUARD_INTERFACE = 'wg0'
app = Flask(__name__)
@app.route('/health', methods=['GET'])
def health_check():
try:
# We run `wg show` to check the status of the interface.
# This command will fail (return a non-zero exit code) if the interface doesn't exist or the module isn't loaded.
result = subprocess.run(
['sudo', 'wg', 'show', WIREGUARD_INTERFACE],
capture_output=True,
text=True,
check=True
)
# Simple check: If the command ran successfully, we consider it "ok".
# For a more advanced check, you could parse result.stdout to check for recent handshakes.
return jsonify({
'status': 'ok',
'message': f'WireGuard interface "{WIREGUARD_INTERFACE}" is active.'
}), 200
except FileNotFoundError:
# This happens if the 'wg' command isn't installed or not in the PATH
return jsonify({
'status': 'error',
'message': 'Error: `wg` command not found.'
}), 500
except subprocess.CalledProcessError as e:
# This happens if `wg show <interface>` fails, meaning the interface is down or doesn't exist.
return jsonify({
'status': 'error',
'message': f'WireGuard interface "{WIREGUARD_INTERFACE}" appears to be down.',
'details': e.stderr.strip()
}), 503 # 503 Service Unavailable is a fitting HTTP status code
if __name__ == '__main__':
# Listens on all available network interfaces (0.0.0.0) on port 9876
# You can change the port if you like.
app.run(host='0.0.0.0', port=9876)