Python 3.6(Windows)中的简单Ping扫描不会';I don’我没有按预期工作

Python 3.6(Windows)中的简单Ping扫描不会';I don’我没有按预期工作,python,python-3.x,Python,Python 3.x,我找到了以下脚本并尝试运行它。因为我在Windows上运行Python3.6,所以我对代码做了一些修改。这是我现在使用的代码 import subprocess import os with open('ip.txt', 'r') as f: for ip in f: result=subprocess.Popen(["ping", "-n", "1", ip],stdout=f, stderr=f).wait() if result:

我找到了以下脚本并尝试运行它。因为我在Windows上运行Python3.6,所以我对代码做了一些修改。这是我现在使用的代码

import subprocess
import os

with open('ip.txt', 'r') as f:
    for ip in f:
        result=subprocess.Popen(["ping", "-n", "1", ip],stdout=f, stderr=f).wait()
        if result:
            print(ip, "inactive")
        else:
            print(ip, "active")
然而,结果似乎并不准确。两个主机实际上都启动了

C:\Python>python ping.py
192.168.0.1
 inactive
192.168.0.2 active

C:\Python>
是否有可能在一行中进行第一次输出。。。例如

192.168.0.1 inactive
192.168.0.2 active
更新

如果有更好更简单的方法用Python编写ping sweeper,将IP列表保存在
IP.txt
文件中,请告诉我

所需输出

192.168.0.1 inactive
192.168.0.2 active
192.168.0.3 active
192.168.0.4 inactive
192.168.0.5 inactive
ip.txt

192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5

我尝试了您的示例,但遇到了相同的问题,但我意识到最后一个IP始终是活动的,因此我认为问题在于,在尝试执行ping时,读取文件时拾取了“\n”

我对代码做了一些更改,使其正常工作:

import subprocess
import os

with open('ip.txt', 'r') as f:
    for ip in f:
        result=subprocess.Popen(["ping", "-n", "1", ip.strip()],stdout=f, stderr=f).wait()
        if result:
            print(ip.strip(), "inactive")
        else:
            print(ip.strip(), "active")
只需在从文件接缝读取的IP中添加一个“strip()”即可

如果您发现任何问题,请告诉我

问候