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

时间:2016-03-02 14:30:33

标签: python subprocess ping

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

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

然后我检查输出是否包含"来自':"的回复,以查看ping是否成功。
这适用于cmd为英语的所有情况 如何检查ping是否在任何cmd语言上成功?

5 个答案:

答案 0 :(得分:3)

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

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

如果ping成功,则返回true

答案 1 :(得分: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

答案 2 :(得分: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")

答案 3 :(得分: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

答案 4 :(得分:0)

在Windows上工作。

对于Python 2

import ipaddress, subprocess
myIpAddress = raw_input('Enter an IP Address with a CIDR. >>> ') #192.168.0.1/24
myAdd = ipaddress.ip_interface(unicode(myIpAddress))
myNet = ipaddress.ip_network(myAdd, strict = False) # False lets you enter any ip address in the /24 ip address block.
for i in myNet:
    canPing = subprocess.call('ping /n 2 /w 1000 %s' % str(i))
        if canPing == 0:
            print('I can ping %s' % str(i))
        if canPing == 1:
            print('%s is not responding' % str(i))

对于Python 3

import ipaddress, subprocess
myIpAddress = input('Enter an IP Address with a CIDR >>> ') #192.168.0.1/24
myAdd = ipaddress.ip_interface(myIpAddress)
myNet = ipaddress.ip_network(myAdd, strict = False) # False lets you enter any ip address in the /24 ip address block.
for i in myNet:
    canPing = subprocess.call('ping /n 2 /w 1000 %s' % str(i))
        if canPing == 0:
            print('I can ping %s.' % str(i))
        if canPing == 1:
            print('%s is not responding' % str(i))