使用Python进行本地网络Ping测试

10

有人知道如何使用Python来ping本地主机以查看它是否处于活动状态吗?我们(我和我的团队)已经尝试使用

os.system("ping 192.168.1.*") 

但对于目标不可达的响应与主机正常响应的响应相同。

感谢您的帮助。

8个回答

12

使用此功能,可以轻松地将文本转换为另一种语言。

import os

hostname = "localhost" #example
response = os.system("ping -n 1 " + hostname)

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

如果在Unix/Linux上使用此脚本,请将-n开关替换为-c!
就这些:)


6
如果我收到“目标主机不可达”的回复,则表示它无法工作。 - Kamesh Jungi
当然,这个问题可能需要更好的描述。但是正如他在描述中所述,它无法处理“目标主机不可达”的情况。因此,你的回答完全是错误的。 - Frankstar

8
我发现使用 os.system(...) 会导致误报(正如提问者所说,'destination host unreachable' == 0)。
如前所述,使用 subprocess.Popen 可行。为了简单起见,建议这样做,然后解析结果。你可以像下面这样轻松实现:
if ('unreachable' in output):
        print("Offline")

只需从ping结果中检查您想要检查的各种输出。在“那”里面制造一个“这”来进行检查。

例如:

import subprocess

hostname = "10.20.16.30"
output = subprocess.Popen(["ping.exe",hostname],stdout = subprocess.PIPE).communicate()[0]

print(output)

if ('unreachable' in output):
    print("Offline")

2
请注意,解析输出取决于主机操作系统的语言。 - Hauke

6
我找到在Windows上实现此操作的最佳方法,如果您不想解析输出,则可以像这样使用Popen:
num = 1
host = "192.168.0.2"
wait = 1000

ping = Popen("ping -n {} -w {} {}".format(num, wait, host),
             stdout=PIPE, stderr=PIPE)  ## if you don't want it to print it out
exit_code = ping.wait()

if exit_code != 0:
    print("Host offline.")
else:
    print("Host online.")  

这个工作按预期进行。退出代码没有误报。我已在Windows 7和Windows 10上的Python 2.7和3.4中进行了测试。


5

我之前编写了一个小程序。虽然它可能不是你正在寻找的完全符合要求的东西,但你可以在主机操作系统上运行一个程序来启动一个套接字。这是本身ping程序:

# Run this on the PC that want to check if other PC is online.
from socket import *

def pingit():                               # defining function for later use

    s = socket(AF_INET, SOCK_STREAM)         # Creates socket
    host = 'localhost' # Enter the IP of the workstation here 
    port = 80                # Select port which should be pinged

    try:
        s.connect((host, port))    # tries to connect to the host
    except ConnectionRefusedError: # if failed to connect
        print("Server offline")    # it prints that server is offline
        s.close()                  #closes socket, so it can be re-used
        pingit()                   # restarts whole process    

    while True:                    #If connected to host
        print("Connected!")        # prints message 
        s.close()                  # closes socket just in case
        exit()                     # exits program

pingit()                           #Starts off whole process

以下是可以接收ping请求的程序:

# this runs on remote pc that is going to be checked
from socket import *

HOST = 'localhost'
PORT = 80
BUFSIZ = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(2)

while 1:
    clientsock, addr = serversock.accept()
    serversock.close()
    exit()

为了让程序不可见,只需将文件保存为.pyw而非.py。这样直到用户检查运行进程之前都是不可见的。
希望对您有所帮助。

抱歉 - 但这个问题是关于ping服务器的,这是一个不同的情况。只有在您知道服务器存在且处于活动状态时,连接才有意义! - cslotty

2

为了简单起见,我使用基于socket的自制函数。

def checkHostPort(HOSTNAME, PORT):
    """
        check if host is reachable
    """
    result = False
    try:
        destIp  =  socket.gethostbyname(HOSTNAME)
    except:
        return result
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(15)
    try:
        conn = s.connect((destIp, PORT))
        result = True
        conn.close()
    except:
        pass
    return result

如果 IP:Port 是可达的,则返回 True。
如果你想模拟 Ping,可以参考 ping.py。

1

试试这个:

ret = os.system("ping -o -c 3 -W 3000 192.168.1.10")
if ret != 0:
    print "Host is not up"

-o 等待仅一个数据包

-W 3000 只给它3000毫秒来回复数据包。

-c 3 让它尝试几次,以免您的ping永远运行下去。


0

请求模块怎么样?

import requests

def ping_server(address):
    try:
        requests.get(address, timeout=1)
    except requests.exceptions.ConnectTimeout:
        return False

return True
  • 不需要拆分URL以去除端口或测试端口,也没有本地主机误报。
  • 超时时间并不重要,因为只有在没有服务器时才会触发超时,这意味着性能不再重要。否则,此方法的速度与请求速度相同,对我来说足够快。
  • 如果有必要的话,超时等待第一个比特而不是总时间。

0

使用这个方法并解析字符串输出


import subprocess
output = subprocess.Popen(["ping.exe","192.168.1.1"],stdout = subprocess.PIPE).communicate()[0]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接