使用 python Ping 本地 IP

Pinging local IPs with python

我正在尝试编写一个函数来 ping 多个通过 LAN 连接到我的 PC 的 IP 地址

我的是:

'''

def ping_ip (ip):

pingResponse = os.system("ping " + ip + " -n 1")

if pingResponse == 0:

    return "Pass"

else:

    return "Fail"

def ping_all_ips ():

global allIPs

for ip in allIPs:

    result = ping_ip(ip)

    print(f"Attempt To Ping {ip} -----> {result}")

'''

但问题是,即使未连接 IP,我也会得到“通过”,因为它将“来自 XXXX 的回复:目标网络无法访问”视为成功

编辑:尝试使用 subprocess 模块如下:

def ping_ip (ip):

    process = subprocess.Popen("ping " + ip + " -n 1" , shell=True stdoutt=subprocess.PIPE)

    for line in process.stdout:

        if b"Destination" in line or b"Request timed out" in line:

            return "Fail"

        else:

            return "Pass"

def ping_all_ips ():

    global allIPs

    for ip in allIPs:

        result = ping_ip(ip)

         print(f"Attempt To Ping {ip} -----> {result}")

if __name__ == '__main__':

    ping_all_ips()

我猜你的问题是你想检查控制台的输出但可以看到如何。解决方案是像这样使用 subprocess 模块。

import subprocess

allIPs = ["192.168.1.1", "192.168.1.203", "192.168.1.23"]
def ping_ip (ip):
     process = subprocess.Popen("ping " + ip , shell=True , stdout=subprocess.PIPE) 
     for line in process.stdout:
        print(line)
        if b"PING" in line:
            continue
        if b"Destination" in line or b"Request timed out" in line: 
            print("failed")
            process.kill()
            return "Fail"
        else:            
            print("passed")
            process.kill()
            return "Pass"
        
def ping_all_ips (): 
    global allIPs
    for ip in allIPs:
        print(f"Attempt To Ping {ip}") 
        result = ping_ip(ip)
        print(f"Attempt To Ping {ip} -----> {result}") 
if __name__ == '__main__': 
    ping_all_ips()

此代码将为 运行 您的命令打开一个新进程,并检查每一行输出,如果它在输出中找到 Destination,这意味着发生了错误,它将打印错误并终止进程.然后,如果一切正常,您可以添加您的逻辑,并记住始终终止进程,因为如果不停止,ping 将永远 运行。