我使用python的子进程模块,通过ping命令打开cmd窗口来执行python中的ping命令。
例如:
import subprocess
p = subprocess.Popen('ping 127.0.0.1')然后,我检查输出是否包含"Reply from 'ip':",以查看ping是否成功。
这在cmd为英语的所有情况下都有效。
如何在任何cmd语言上检查ping是否成功?
发布于 2018-01-15 23:29:47
在Linux上使用python时,我会使用check_output()
subprocess.check_output(["ping", "-c", "1", "127.0.0.1"])如果ping成功,则返回true
发布于 2016-03-02 22:42:40
我知道这在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发布于 2018-01-02 18:44:11
对于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")https://stackoverflow.com/questions/35750041
复制相似问题