使用python中的子进程检查ping是否成功
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35750041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if ping was successful using subprocess in python
提问by yuval
I execute the ping command in python by opening a cmd window with the ping command using python's subprocess module.
For example:
我通过使用 python 的子进程模块打开一个带有 ping 命令的 cmd 窗口,在 python 中执行 ping 命令。
例如:
import subprocess
p = subprocess.Popen('ping 127.0.0.1')
Afterwards I check if the output contains "Reply from 'ip':", to see if the ping was successful.
This works in all cases where the cmd is in english.
What can I do to check if a ping was successful on any cmd language?
之后我检查输出是否包含“Reply from 'ip':”,以查看 ping 是否成功。
这适用于 cmd 为英文的所有情况。
我该怎么做才能检查在任何 cmd 语言上 ping 是否成功?
回答by Hadrián
I know this works on Linux, I think it will work also over Windows.
我知道这适用于 Linux,我认为它也适用于 Windows。
Update: The uncommented code works also in 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()
If p.poll() is 0 the ping was succesfull, if it is 1 the destination was unreachable.
如果 p.poll() 为 0,则 ping 成功,如果为 1,则无法到达目的地。
A version for many IP addresses will be:
许多 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
回答by elfosardo
Using python on Linux, I would use check_output()
在 Linux 上使用 python,我会使用 check_output()
subprocess.check_output(["ping", "-c", "1", "127.0.0.1"])
this will return true if the ping is successful
如果 ping 成功,这将返回 true
回答by Spartacus
@elfosardo your solution does not return true if ping is successful. It returns the output of the command or a CalledProcessError exception if the return code was non-zero. Using check_output() as you suggested, here is a possible solution even if not the best one:
@elfosardo 如果 ping 成功,您的解决方案不会返回 true。如果返回代码非零,它会返回命令的输出或 CalledProcessError 异常。按照您的建议使用 check_output() ,即使不是最好的解决方案,这里也是一个可能的解决方案:
import subprocess
def ping():
try:
subprocess.check_output(["ping", "-c", "1", "127.0.1.1"])
return True
except subprocess.CalledProcessError:
return False
回答by M.hosseny
For 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")