Skip to main content
 首页 » 编程设计

Python:如何 ping 一个 IP 地址范围

2025年05月04日11zhujiabin

我想在 Python 中 ping 一系列 IP 地址并打印: “该 IP 可以以 X% 的包丢失率访问”或 “IP 无法访问,丢失 X% 的包”

我想尝试的范围是192.168.0.X,X是0-255的范围

到目前为止,这是我的代码;

import shlex 
import subprocess 
import os 
 
for x in range(0, 256): 
    cmd=shlex.split("ping -cl 192.168.0." + str(x)) 
    try: 
       output = subprocess.check_output(cmd) 
    except subprocess.CalledProcessError,e: 
       #Will print the command failed with its exit status 
       print "The IP {0} isn't reachable".format(cmd[-1]) 
    else: 
       print "The IP {0} is reachable".format(cmd[-1]) 

我的代码有什么问题?我还注意到,当我尝试命令“ping -cl 192.168.0.2”时,它说 -cl 是一个仅限管理员的命令。我是计算机的管理员,我以管理员身份运行 cmd,这有什么问题吗?

我使用的是 Windows 8.1 Python v2.7.9

请您参考如下方法:

如果您使用的是 linux 并且只想查看丢包情况:

import shlex 
from subprocess import PIPE, Popen 
 
 
cmd1 = shlex.split("grep -oP '\d+(?=% packet loss)'") 
for x in range(1, 256): 
    cmd = "ping  -c 4  192.168.43.{}".format(x).split() 
    p1 = Popen(cmd, stdout=PIPE, stderr=PIPE) 
    p2 = Popen(cmd1, stdin=p1.stdout, stdout=PIPE) 
    p1.stdout.close() 
    output = p2.communicate()[0].rstrip() 
    if output == "100": 
        print("{}% percent packet loss from unreachable ip {}".format(output, cmd[-1])) 
    else: 
        print("{}% percent packet loss from reachable ip {}".format(output, cmd[-1])) 

免责声明我不使用 Windows,所以可以更正,但这可能有效:

for x in range(1, 256): 
    cmd = "ping  -c 1  192.168.43.{}".format(x).split() 
    p1 = Popen(cmd, stdout=PIPE, stderr=PIPE) 
    lines = p1.communicate()[0].splitlines() 
    output = (lines[-2]).rsplit(None,5) 
    output = output[-5].rstrip() 
    if output == "100%": 
        print("{} percent packet loss from unreachable ip {}".format(output, cmd[-1])) 
    else: 
        print("{} percent packet loss from reachable ip {}".format(output, cmd[-1]))