#!/usr/bin/python3 import socket import time import subprocess import os def restart_machine(): print("TCP connection failed continuously for 30 minutes. Restarting the machine...") subprocess.run(['sudo', 'reboot']) counter = 0 while True: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) try: sock.connect(("1.1.1.1", 80)) counter = 0 except Exception: counter += 1 if counter == 180: restart_machine() finally: sock.close() time.sleep(10)