您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

用Python ping服务器

用Python ping服务器

编辑: 被@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'])

python 2022/1/1 18:32:31 有208人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶