Ping不适用于python中的模式

时间:2017-09-27 05:39:03

标签: python

我有一系列ips,我需要通过ping检查。 ping包含如下模式:

 ping -c 3 -p abc0000114a 10.65.200.44

在此,'abc'是常量,0000114a10.65.200.44是变量。我使用以下代码:

address = "abc"+str(formatted)+ " " + ''.join(map(str, ip))

res = subprocess.call(['ping','-c', '3', '-p', address])
if res == 0:
     print "ping to", address, "OK"
elif res == 2:
     print "no response from", address
else:
     print "ping to", address, "failed!"

它不起作用,如在子流程,变量'地址'不是ip,事实上,它是一种模式

O / P:

 usage: ping [-AaDdfnoQqRrv] [-c count] [-G sweepmaxsize] [-g sweepminsize]
            [-h sweepincrsize] [-i wait] [-l preload] [-M mask | time] [-m ttl]
            [-P policy] [-p pattern] [-S src_addr] [-s packetsize] [-t timeout]
            [-W waittime] [-z tos] host
       ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]
            [-M mask | time] [-m ttl] [-P policy] [-p pattern] [-S src_addr]
            [-s packetsize] [-T ttl] [-t timeout] [-W waittime]
            [-z tos] mcast-group
ping to abc00001060 10.65.200.44 failed!

然而,它有效: 〜> ping -c 3 -p abc0000114a 10.65.200.44

PATTERN: 0xabc0000114a

PING 10.65.200.44 (10.65.200.44): 56 data bytes
64 bytes from 10.65.200.44: icmp_seq=0 ttl=64 time=12.925 ms
64 bytes from 10.65.200.44: icmp_seq=1 ttl=64 time=0.300 ms
64 bytes from 10.65.200.44: icmp_seq=2 ttl=64 time=0.207 ms

--- 10.65.200.44 ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.207/4.477/12.925/5.974 ms

2 个答案:

答案 0 :(得分:0)

尝试:

cmds = ['ping','-c', '3', '-p'].extend(address.split())
res = subprocess.call(cmds)

答案 1 :(得分:0)

使用shlex:

import shlex

res = subprocess.call(shlex.split('ping -c 3 -p ' + address))