在 Python 中 Ping 服务器

新手上路,请多包涵

在 Python 中,有没有办法通过 ICMP ping 服务器并在服务器响应时返回 TRUE,或者在没有响应时返回 FALSE?

原文由 Kudu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 603
2 个回答

此功能适用于任何操作系统(Unix、Linux、macOS 和 Windows)

Python 2 和 Python 3

编辑:

@radato os.system 替换为 subprocess.call 。这可以避免在您的主机名字符串可能未被验证的情况下出现 shell 注入 漏洞。

 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 错误。

解释

该命令在 Windows 和类 Unix 系统中都是 ping

选项 -n (Windows) 或 -c (Unix) 控制本例中设置为 1 的数据包数量。

platform.system() 返回平台名称。前任。 'Darwin' 在 macOS 上。

subprocess.call() 执行系统调用。前任。 subprocess.call(['ls','-l'])

原文由 ePi272314 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您不需要支持 Windows,这里有一个非常简洁的方法:

 import os
hostname = "google.com" #example
response = os.system("ping -c 1 " + hostname)

#and then check the response...
if response == 0:
  print hostname, 'is up!'
else:
  print hostname, 'is down!'

这是有效的,因为如果连接失败,ping 将返回一个非零值。 (返回值实际上因网络错误而异。)您还可以使用“-t”选项更改 ping 超时(以秒为单位)。请注意,这会将文本输出到控制台。

原文由 Scott 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题