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

问题描述 投票:5回答:4

我使用python的子进程模块通过ping命令打开cmd窗口,在python中执行ping命令。 例如:

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

然后我检查输出是否包含“来自'ip':”的回复,以查看ping是否成功。 这适用于cmd为英语的所有情况。 我该怎么做才能检查ping是否在任何cmd语言上成功?

python subprocess ping
4个回答
3
投票

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

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

如果ping成功,这将返回true


2
投票

我知道这适用于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

1
投票

对于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")

0
投票

@elfosardo如果ping成功,您的解决方案不会返回true。如果返回码非零,则返回命令的输出或CalledProcessError异常。使用你建议的check_output(),这是一个可能的解决方案,即使不是最好的解决方案:

import subprocess

def ping():
    try:
        subprocess.check_output(["ping", "-c", "1", "127.0.1.1"])
        return True                      
    except subprocess.CalledProcessError:
        return False
© www.soinside.com 2019 - 2024. All rights reserved.