在 Python 中 Ping 服务器 [英] Pinging servers in Python

查看:37
本文介绍了在 Python 中 Ping 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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()返回平台名称.前任.'Darwin' 在 macOS 上.
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆