用Python ping服务器 [英] Pinging servers in Python
问题描述
在Python中,是否可以通过ICMP对服务器进行ping操作,如果服务器响应则返回TRUE,如果没有响应则返回FALSE?
In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?
推荐答案
此功能可在任何操作系统(Unix,Linux,macOS和Windows)上使用
Python 2和Python 3
由 @radato os.system
替换为subprocess.call
.这样可以避免在主机名字符串可能未经验证的情况下 shell注入漏洞.
EDITS:
By @radato os.system
was replaced by subprocess.call
. This avoids shell injection vulnerability in cases where your hostname string might not be validated.
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
请注意,根据Windows上的@ikrase,如果出现Destination Host Unreachable
错误,此函数仍将返回True
.
Note that, according to @ikrase on Windows this function will still return True
if you get a Destination Host Unreachable
error.
说明
在Windows和类似Unix的系统中,该命令均为ping
.
选项-n
(Windows)或-c
(Unix)控制在此示例中设置为1的数据包数量.
The command is ping
in both Windows and Unix-like systems.
The option -n
(Windows) or -c
(Unix) controls the number of packets which in this example was set to 1.
platform.system()
返回平台名称.前任.在MacOS上为'Darwin'
.
subprocess.call()
执行系统调用.前任. subprocess.call(['ls','-l'])
.
platform.system()
returns the platform name. Ex. 'Darwin'
on macOS.
subprocess.call()
performs a system call. Ex. subprocess.call(['ls','-l'])
.
这篇关于用Python ping服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!