MacserverAutoRestartNetwork/main.py

78 lines
2.1 KiB
Python
Raw Normal View History

2024-01-08 10:51:35 +08:00
import os, time ,requests
def network_test():
try:
html = requests.get("https://www.baidu.com",timeout=5)
return True
except:
return False
def network_restart():
2024-01-08 11:11:58 +08:00
try:
os.system("ifconfig en0 down")
except:
return False
time.sleep(1)
try:
os.system("ifconfig en0 up")
except:
return False
2024-01-08 10:51:35 +08:00
return True
2024-01-08 18:55:00 +08:00
def convert_seconds(seconds):
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 3600) % 60
return hours, minutes, seconds
2024-01-08 17:12:53 +08:00
def ascii_tag():
2024-01-08 18:55:00 +08:00
sys_s ,sta_s= None, None
2024-01-08 17:12:53 +08:00
if i > 0:
sys_s = "Down"
2024-01-08 18:55:00 +08:00
sta_s = f"{time.ctime()} network 403 , down"
2024-01-08 17:12:53 +08:00
else:
sys_s = "Up"
2024-01-08 18:55:00 +08:00
sta_s = f"{time.ctime()} network 200 , ok"
t = int(time.time() - k)
t = convert_seconds(t)
2024-01-08 17:12:53 +08:00
os.system("clear")
print(" _ _ _______ ")
print(" / \ / |_ |_ __ \ ")
print(" / _ \ __ _ `| |-' .--. | |__) | .---. ")
print(" / ___ \ [ | | | | | / .'`\ \ | __ / / /__\\ ")
print(" _/ / \ \_ | \_/ |,| |,| \__. |_| | \ \_| \__., ")
print("|____| |____|'.__.'_/\__/ '.__.'|____| |___|'.__.' ")
print("")
2024-01-08 18:55:00 +08:00
print(f"系统架构:{os.name}\n异常次数:{j}\n当前状态:{sys_s}\n运行时间:{t[0]}{t[1]}{t[2]}\n最近记录:{sta_s}")
2024-01-08 17:12:53 +08:00
return True
2024-01-08 10:51:35 +08:00
def main():
2024-01-08 18:55:00 +08:00
global i, j, k
i, j = 0, 0
k = time.time()
2024-01-08 10:51:35 +08:00
while(1):
2024-01-08 17:12:53 +08:00
if not network_test(): #网络异常
i +=1 #异常计数 3次失败重启
2024-01-08 17:29:28 +08:00
ascii_tag()
2024-01-08 10:51:35 +08:00
time.sleep(3)
2024-01-08 17:12:53 +08:00
else: #网络正常
i = 0
2024-01-08 17:29:28 +08:00
ascii_tag()
2024-01-08 10:51:35 +08:00
time.sleep(10)
2024-01-08 17:29:28 +08:00
if (i > 2): #异常3次
2024-01-08 17:12:53 +08:00
if not network_restart(): #接口重启失败
2024-01-08 17:29:28 +08:00
ascii_tag()
print("接口错误,输入回车后退出。")
2024-01-08 17:12:53 +08:00
input()
2024-01-08 17:29:28 +08:00
exit()
2024-01-08 17:12:53 +08:00
else: #接口重启完成
2024-01-08 11:11:58 +08:00
i = 0
2024-01-08 17:29:28 +08:00
j += 1
ascii_tag()
2024-01-08 11:11:58 +08:00
time.sleep(10)
2024-01-08 10:51:35 +08:00
if __name__ == "__main__":
main()