我使用python的子進程模塊通過ping命令打開cmd窗口,從而在python中執行ping命令。
例如:使用python中的子進程檢查ping是否成功
import subprocess
p = subprocess.Popen('ping 127.0.0.1')
事後我檢查,如果輸出包含「從‘IP’回覆:」看如果ping成功。
這適用於cmd爲英文的所有情況。
我能做些什麼來檢查ping是否在任何cmd語言上成功?
我使用python的子進程模塊通過ping命令打開cmd窗口,從而在python中執行ping命令。
例如:使用python中的子進程檢查ping是否成功
import subprocess
p = subprocess.Popen('ping 127.0.0.1')
事後我檢查,如果輸出包含「從‘IP’回覆:」看如果ping成功。
這適用於cmd爲英文的所有情況。
我能做些什麼來檢查ping是否在任何cmd語言上成功?
我知道這可以在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
對於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")
在Linux上使用Python,我會用check_output()
subprocess.check_output(["ping", "-c", "1", "127.0.0.1"])
這將如果ping成功,則返回true
相關:[在Python中Ping一個站點?](http://stackoverflow.com/q/316866/4279) – jfs