From 7677e337e3d84e0fe768861e778b9b89e5282c01 Mon Sep 17 00:00:00 2001 From: gru Date: Tue, 17 Jun 2025 00:05:07 +0200 Subject: [PATCH] Add check_cups_working.py --- check_cups_working.py | 62 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 check_cups_working.py diff --git a/check_cups_working.py b/check_cups_working.py new file mode 100644 index 0000000..c891aff --- /dev/null +++ b/check_cups_working.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +""" +This script checks whether the CUPS service is listening on TCP port 631. +If not, it restarts the service and verifies again. + + Example manual usage: + sudo /usr/local/bin/check_cups_working.py --host 127.0.0.1 + + Example crontab entry (run every 5 minutes, silent mode): + */5 * * * * root /usr/local/bin/check_cups_working.py --host 127.0.0.1 --quiet +""" + +import socket +import subprocess +import time +import sys +import argparse + +PORT = 631 +SERVICE = "cups" + +def is_port_listening(host, port): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.settimeout(1) + try: + s.connect((host, port)) + return True + except (ConnectionRefusedError, socket.timeout, OSError): + return False + +def restart_service(service): + subprocess.run(["systemctl", "restart", service], check=False) + time.sleep(3) + +def main(): + parser = argparse.ArgumentParser( + description="Checks if CUPS is listening on TCP port 631 and restarts the service if not." + ) + parser.add_argument("--host", default="127.0.0.1", help="IP address to check (default: 127.0.0.1)") + parser.add_argument("--quiet", action="store_true", help="Suppress all output (for use in cron jobs)") + args = parser.parse_args() + + def log(msg): + if not args.quiet: + print(msg) + + if is_port_listening(args.host, PORT): + log(f"CUPS OK: listening on {args.host}:{PORT}") + sys.exit(0) + else: + log(f"CUPS not listening on {args.host}:{PORT}. Restarting service...") + restart_service(SERVICE) + + if is_port_listening(args.host, PORT): + log("CUPS restarted and is now listening.") + sys.exit(0) + else: + log("ERROR: CUPS still not listening after restart!") + sys.exit(2) + +if __name__ == "__main__": + main() \ No newline at end of file