MacserverAutoRestartNetwork/main.py

78 lines
2.1 KiB
Python

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