首页 > 解决方案 > 用于检测服务器是否宕机的 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” . 我真的很想为我如何使它工作提供一些帮助。

标签: python

解决方案


如果您只是在寻找状态更改,您可以执行以下操作:

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 循环上设置一个超时,并可能使某些部分更具可配置性,例如睡眠。


推荐阅读