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

标签 python networking cmd ping

我想在 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]))

关于Python:如何 ping 一个 IP 地址范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27893032/

相关文章:

python - 使用 Python 正则表达式,如何在结果中不出现空字符串的情况下将该字符串拆分为多个分隔符?

python - 基于与 DataFrame 列数匹配的 Series 对 pandas DataFrame 行应用操作

python - Locust Load Testing 分析后术语的含义

c - 尽管设置了 SOCK_NONBLOCK,accept4 block

networking - 广播

mysql - 查询位于桥接用户定义网络中的 docker mysql

android - 使用 WINDOWS 在多个连接的设备上安装 apk

Python:在矩阵中的两个坐标之间画线

windows - cmd 批量重命名子文件夹/文件

c# - 从 C# 代码启动时隐藏 cmd.exe 窗口