2017-09-27 44 views
0

我有一系列需要通過ping檢查的ips。平包含格式,如:Ping不能用於Python中的模式

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 
+0

你要通過模式和IP作爲單獨的參數'call'。不要加入他們。 –

+0

需要加入它們。我需要這個在腳本中工作 ping -c 3 -p abc0000114a 10.65.200.44 – user7994925

回答

0

嘗試:

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

res = subprocess.call(cmds) 文件「/usr/local/lib/python2.7/subprocess.py」,第493行,in請致電 返回Popen(* popenargs,** kwargs).wait() 文件「/usr/local/lib/python2.7/subprocess.py」,第679行,在__init__中 errread,errwrite) 文件「/ usr /local/lib/python2.7/subprocess.py「,第1122行,在_execute_child中 args = list(args) TypeError:'NoneType'對象不可迭代 – user7994925

+0

@ user7994925看起來變量地址不是字符串。你能解釋一下地圖(str,ip)嗎?格式化和IP的價值是什麼? – hailinzeng

+0

謝謝大家。 res = subprocess.call(shlex.split('ping -c 3 -p'+ address))爲我工作 – user7994925

0

使用shlex:

import shlex 

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

謝謝,它工作 – user7994925