2016-03-02 123 views
3

我使用python的子進程模塊通過ping命令打開cmd窗口,從而在python中執行ping命令。
例如:使用python中的子進程檢查ping是否成功

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

事後我檢查,如果輸出包含「從‘IP’回覆:」看如果ping成功。
這適用於cmd爲英文的所有情況。
我能做些什麼來檢查ping是否在任何cmd語言上成功?

+0

相關:[在Python中Ping一個站點?](http://stackoverflow.com/q/316866/4279) – jfs

回答

3

我知道這可以在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平是succesfull,如果是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 
+0

這將使用簡單的ping我同意,但如果我有一個循環在批處理中ping和返回很多結果? – yuval

+0

@yuval你想要在python或bash中進行循環? –

+0

in bash,「cmd/C for/l%i in(1,1,254)do ping -w 2000 -n 1 195.218.195。%i」 – yuval

0

對於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") 
2

在Linux上使用Python,我會用check_output()

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

這將如果ping成功,則返回true