How to ping IP Address form .txt in Python

问题描述 投票:0回答:1

如何从 D: 中的文本文件 (.txt) 编码 ping 地址
我目前正在使用 python 3.1,需要在文本文件中 ping 多个 ip 地址

*** 欢迎提出编码建议。

import requests
import os

def notifyNetwork(message):
    token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    uri = "https://notify-api.line.me/api/notify"
    header = {"Authorization": "Bearer " + token}
    msg = {"message": "TEST \n" + message}
    resp = requests.post(uri, headers=header, data=msg)

hostname = list([['192.168.1.200','EU (SERVER)', True]])

def checkNetwork(hostname):
    response = os.system("ping "+hostname)
    print(response)
    if (response==1):
        status = False
    else:
        status = True
    return status

while True:
    for index, TEST in enumerate(hostname):
        currentStatus = checkNetwork(TEST[0])
        previusStatus = TEST[2]
        if currentStatus == previusStatus:
            print('-----No Notify-----')
        else:
            hostname[index][2] = currentStatus
            if currentStatus:
                statusNetwork = 'UP'
            else:
                statusNetwork = 'Down'
            message = f"IP : {hostname[index][0]}\nName : {hostname[index][1]}\n{statusNetwork}"
            notifyNetwork(message)
            print('---- Notify ----')
        schedule.run_pending()
        time.sleep(5)
    print(hostname)
python ip
1个回答
0
投票

我假设读取(或写入)文件背后的动机是能够终止进程并稍后重新运行它,保持状态。

让我们首先提出文件的格式。文件中的每一行都代表一个服务器。请记住,服务器名称不能包含分号

;
,因为它用作分隔符。 last-status 是“UP”或“Down”。

<IP-address>;<server-name>;<last-status>

开始时在文件中定义要检查的服务器。 然后逐行读取文件,检查状态并保存到一个新的临时文件中。阅读所有行后,用临时文件替换旧文件,有效地更新其内容。

import requests
import os

def notifyNetwork(message):
    pass  # You can keep this function as is.

# Removed the 'hostname' variable, as those values will be read from a file.

def checkNetwork(hostname):
    pass  # You can keep this function as is.

status_file = "the-file.txt"
tmp_file = "tmp.txt"

while True:
    with open(status_file, "r") as host_states, open(tmp_file, "w") as tmp:
        for line in host_states:  # read the file line by line.
            # rstrip() removes '\n' and whitespaces
            ip, name, previusStatus = line.rstrip().split(";")
            print(f"{ip=}, {name=}, {previousStatus=}")
            assert previousStatus in ["UP", "Down"]

            currentStatus = checkNetwork(ip)
            if currentStatus:
                statusNetwork = 'UP'
            else:
                statusNetwork = 'Down'

            if statusNetwork == previusStatus:
                print('-----No Notify-----')
            else:
                message = f"IP : {ip}\nName : {name}\n{statusNetwork}"
                notifyNetwork(message)
                print('---- Notify ----')

            # Save the current status to temp file.
            tmp.write(f"{ip};{name};{statusNetwork}\n")

        # I don't know what next line was supposed to do. Commenting it out.
        # schedule.run_pending()

    # Now replace the old file with the tmp.txt.
    os.replace(tmp_file, status_file)

    time.sleep(5)
© www.soinside.com 2019 - 2024. All rights reserved.