编辑: 被@radatoos.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
请注意,根据Windows上的@ikrase,True
如果遇到Destination Host Unreachable
错误,此函数仍将返回。
该命令ping
在Windows和类似Unix的系统中都可以使用。 选项-n
(Windows)或-c
(Unix)控制在此示例中设置为1的数据包数量。
platform.system()
返回平台名称。例如'Darwin'
在macOS上。subprocess.call()
执行系统调用。例如subprocess.call(['ls','-l'])
。