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("##################################")
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 循环上设置一个超时,并可能使某些部分更具可配置性,例如睡眠。
推荐阅读
- javascript - 即使填充了数组,Javascript 长度也会返回 0
- c++ - 尝试构建时缺少 libz.so
- swiftui - SwiftUI - ScrollView 移动内容以使用 KeyboardAwareSwiftUI 可见
- php - PHP - 如何通过流 url 的公共部分匹配来自两个 m3u8 播放列表的流?
- python - 如何在更新期间隐藏或清除 python Dash+Plotly Graph
- php - Laravel API 路由需要 Session
- python - 尝试创建虚拟环境,但我不断收到“IOError:[Errno 2] 没有这样的文件或目录”
- git - 如何使用审阅者对 github 上的拉取请求所做的更改来更新 fork?
- r - Grep 函数:如何组合字符和一系列数字
- c# - 我得到的错误是每个条目必须有一个关联的键?(WPF)