检查在python中使用子进程ping是否成功

2024-04-29 08:23:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中执行ping命令,方法是使用python的subprocess模块打开带有ping命令的cmd窗口。
例如:

import subprocess
p = subprocess.Popen('ping 127.0.0.1')

然后我检查输出是否包含“Reply from‘ip’:”,以查看ping是否成功。
这适用于所有cmd为英语的情况。
如何检查ping在任何cmd语言上是否成功?


Tags: 模块方法fromimport命令ipcmd语言
3条回答

对于windows:

import subprocess
hostname = "10.20.16.30"
output = subprocess.Popen(["ping.exe",hostname],stdout = 
subprocess.PIPE).communicate()[0]
print(output)
if ('unreachable' in output):
     print("Offline")

在Linux上使用python,我将使用check_output()

subprocess.check_output(["ping", "-c", "1", "127.0.0.1"])

如果ping成功,则返回true

我知道这在Linux上有效,我认为它也可以在Windows上工作。

更新:未注释的代码也可以在Windows中工作

import subprocess
p = subprocess.Popen('ping 127.0.0.1')
# Linux Version p = subprocess.Popen(['ping','127.0.0.1','-c','1',"-W","2"])
# The -c means that the ping will stop afer 1 package is replied 
# and the -W 2 is the timelimit
p.wait()
print p.poll()

如果p.poll()为0,则ping成功;如果为1,则无法到达目标。

许多IP地址的版本为:

import subprocess
iplist=["127.0.0.1","8.8.8.8"]
for ip in iplist:
    p = subprocess.Popen('ping '+ip,stdout=subprocess.PIPE)
    # the stdout=subprocess.PIPE will hide the output of the ping command
    p.wait()
    if p.poll():
        print ip+" is down"
    else:
        print ip+" is up"
# You end with a log of all the ip addresses

相关问题 更多 >