MacserverAutoRestartNetwork/main.py

65 lines
1.7 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 17:12:53 +08:00
def ascii_tag():
sys_s = None
sta_s = None
if i > 0:
sys_s = "Down"
sta_s = "{} network 403 , down".format(time.ctime())
else:
sys_s = "Up"
sta_s = "{} network 200 , ok".format(time.ctime())
os.system("clear")
print(" _ _ _______ ")
print(" / \ / |_ |_ __ \ ")
print(" / _ \ __ _ `| |-' .--. | |__) | .---. ")
print(" / ___ \ [ | | | | | / .'`\ \ | __ / / /__\\ ")
print(" _/ / \ \_ | \_/ |,| |,| \__. |_| | \ \_| \__., ")
print("|____| |____|'.__.'_/\__/ '.__.'|____| |___|'.__.' ")
print("")
print("系统架构:{}\n异常次数:{}\n当前状态:{}\n最近记录:{}".format(os.name,j,sys_s,sta_s))
return True
2024-01-08 10:51:35 +08:00
def main():
2024-01-08 17:12:53 +08:00
global i ,j
2024-01-08 10:51:35 +08:00
i = 0
2024-01-08 17:12:53 +08:00
j = 0
2024-01-08 10:51:35 +08:00
while(1):
2024-01-08 17:12:53 +08:00
ascii_tag()
if not network_test(): #网络异常
i +=1 #异常计数 3次失败重启
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 10:51:35 +08:00
time.sleep(10)
2024-01-08 17:12:53 +08:00
if (i > 2): #异常3次
if not network_restart(): #接口重启失败
input()
else: #接口重启完成
2024-01-08 11:11:58 +08:00
i = 0
time.sleep(10)
2024-01-08 10:51:35 +08:00
if __name__ == "__main__":
main()