import platform # For getting the operating system name
import subprocess # For executing a shell command
def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
"""
# Option for the number of packets as a function of
param = '-n' if platform.system().lower()=='windows' else '-c'
# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', param, '1', host]
return subprocess.call(command) == 0
此功能适用于任何操作系统(Unix、Linux、macOS和Windows)
Python 2和Python 3
编辑:} 。
由@radato
os.system
替换为subprocess.call
。如果您使用的是Python 3.5+,那么文档建议您使用^{
注意,根据Windows上的@ikrase,如果您得到一个
Destination Host Unreachable
错误,这个函数仍然会返回True
。说明
命令在Windows和类Unix系统中都是
ping
选项-n
(Windows)或-c
(Unix)控制本例中设置为1的数据包数。^{} 返回平台名称。例如,macOS上的} 执行系统调用。例如
'Darwin'
。^{
subprocess.call(['ls','-l'])
。有一个名为pyping的模块可以做到这一点。可与pip一起安装
它使用起来非常简单,但是,当使用这个模块时,您需要根访问权限,因为它正在幕后制作原始数据包。
如果不需要支持Windows,这里有一个非常简洁的方法:
这是因为如果连接失败,ping将返回一个非零值。(返回值实际上因网络错误而异。)您还可以使用'-t'选项更改ping超时(以秒为单位)。注意,这将向控制台输出文本。
相关问题 更多 >
编程相关推荐