用Python ping服务器
在Python中,有没有办法通过ICMP协议去“ping”一个服务器,如果服务器有回应就返回TRUE(真),如果没有回应就返回FALSE(假)呢?
33 个回答
58
有一个叫做 pyping 的模块可以做到这一点。你可以通过 pip 来安装它。
pip install pyping
使用这个模块其实很简单,不过你需要有管理员权限,因为它在后台会处理一些底层的数据包。
import pyping
r = pyping.ping('google.com')
if r.ret_code == 0:
print("Success")
else:
print("Failed with {}".format(r.ret_code))
223
如果你不需要支持Windows系统,这里有一个非常简洁的方法:
import os
param = '-n' if os.sys.platform().lower()=='win32' else '-c'
hostname = "google.com" #example
response = os.system(f"ping {param} 1 {hostname}")
#and then check the response...
if response == 0:
print(f"{hostname} is up!")
else:
print(f"{hostname} is down!")
这个方法之所以有效,是因为当连接失败时,ping命令会返回一个非零的值。(返回的值实际上会根据网络错误的不同而有所变化。)你还可以通过'-t'选项来改变ping的超时时间(以秒为单位)。请注意,这个命令会在控制台上输出一些文字。
207
这个函数可以在任何操作系统上运行(Unix、Linux、macOS 和 Windows)
适用于 Python 2 和 Python 3
编辑内容:
由 @radato 提到,os.system
被 subprocess.call
替代。这是为了避免在你的主机名字符串没有经过验证的情况下出现命令注入的安全漏洞。
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
需要注意的是,根据 @ikrase 的说法,在 Windows 系统上,如果出现 目标主机不可达
的错误,这个函数仍然会返回 True
。
解释
这个命令在 Windows 和类 Unix 系统中都是 ping
。
选项 -n
(Windows)或 -c
(Unix)用来控制发送的数据包数量,在这个例子中设置为 1。
platform.system()
会返回平台的名称。例如,在 macOS 上返回 'Darwin'
。
subprocess.call()
用于执行系统调用。例如,subprocess.call(['ls','-l'])
。