用于检测服务器是否停机的Python脚本
这是我的代码:用于检测服务器是否停机的Python脚本,python,Python,这是我的代码: from os import system from datetime import datetime import time import os import subprocess import sys def status(ip_addr): return os.system('ping ' + ip_addr + '> nul') == 0 statut[] print("##################################
from os import system
from datetime import datetime
import time
import os
import subprocess
import sys
def status(ip_addr):
return os.system('ping ' + ip_addr + '> nul') == 0
statut[]
print("##################################")
print("Current time: ", str(datetime.now()))
print(" ")
with open('data.txt', 'r+') as adds:
add = [addrs.strip() for addrs in adds.readlines()]
for website in add:
stat = status(website)
if stat == 1:
stats = " is up!"
statut[website] = 1
else:
stats = " is down!"
statut[website] = 0
print(website, stats)
print("##################################")
while True:
print("Current time: ", str(datetime.now()))
print(" ")
with open('data.txt', 'r+') as adds:
add = [addrs.strip() for addrs in adds.readlines()]
for website in add:
stat = status(website)
if stat != statut[website]:
stats = " is up!"
statut[website] = stat
print(website, stats)
print("##################################")
time.sleep(240)
我想从中了解的是,首先要了解服务器是否正常工作,然后每隔240秒检查一次服务器是否正常工作——但我不能像预期的那样使用布尔数组“statut”。我真的非常感谢您能为我提供一些帮助。如果您只是想改变状态,您可以这样做:
from os import system
from datetime import datetime
import time
def server_status(ip_addr):
if system('ping ' + ip_addr + '> nul') == 0:
return 'up'
else:
return 'down'
status_history = {}
print("##################################")
print("Current time: ", str(datetime.now()))
print(" ")
with open('data.txt', 'r+') as adds:
ipaddress = [addrs.strip() for addrs in adds.readlines()]
# Set inital state
for server in ipaddress:
status_history[server] = server_status(server)
print(f"{server} is {status_history[server]}")
print("##################################")
while True:
print("Current time: ", str(datetime.now()))
print(" ")
for server in ipaddress:
if server_status(server) != status_history[server]:
status_history[server] = server_status(server)
print(f"{server} has switched state to {status_history[server]}")
else:
print(f"{server} is still {status_history[server]}")
print("##################################")
time.sleep(10)
我会在while循环上设置一个超时,以防万一,并可能使某些部分更易于配置,例如睡眠。欢迎使用堆栈溢出。请阅读。具体来说,“我不能像我预期的那样使用布尔数组”statut“是什么意思?你打算做什么?你想做什么?你是说
statut=[]
?或者基于statut[website]=1
,可能是statut={}
?为什么它是缩进的?这将导致缩进错误
。虽然与您的问题不完全相关,但您可以crontab
来安排事情。例如,我使用它在工作日每小时向我发送关于股票价格的桌面通知。(我假设您使用的是基于linux的服务器,但windows可能也有类似的功能。)