Python中的ping服务器

2024-04-19 03:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

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

编辑:
@radatoos.system替换为subprocess.call
如果您使用的是Python 3.5+,那么文档建议您使用^{}

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

说明

命令在Windows和类Unix系统中都是ping 选项-n(Windows)或-c(Unix)控制本例中设置为1的数据包数。

^{}返回平台名称。例如,macOS上的'Darwin'
^{}执行系统调用。例如subprocess.call(['ls','-l'])

有一个名为pyping的模块可以做到这一点。可与pip一起安装

pip install pyping

它使用起来非常简单,但是,当使用这个模块时,您需要根访问权限,因为它正在幕后制作原始数据包。

import pyping

r = pyping.ping('google.com')

if r.ret_code == 0:
    print("Success")
else:
    print("Failed with {}".format(r.ret_code))

如果不需要支持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超时(以秒为单位)。注意,这将向控制台输出文本。

相关问题 更多 >