62 lines
1.8 KiB
Python
62 lines
1.8 KiB
Python
#!/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() |