python中的本地网络ping

Jus*_*ner 8 networking ping

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

os.system("ping 192.168.1.*") 
Run Code Online (Sandbox Code Playgroud)

但目标无法访问的响应与主机的响应相同.

谢谢你的帮助.

Avi*_*wal 11

用这个 ...

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!')
Run Code Online (Sandbox Code Playgroud)

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

  • 万一我收到“目的地主机无法访问”的回复。它不起作用。 (3认同)

小智 6

我发现使用os.system(...)会导致误报(正如OP所说,'目标主机无法访问'== 0).

如前所述,使用subprocess.Popen工作.为简单起见,我建议这样做,然后解析结果.您可以轻松地执行以下操作:

if ('unreachable' in output):
        print("Offline")
Run Code Online (Sandbox Code Playgroud)

只需检查要从ping结果中检查的各种输出.在"那个"中制作一个'this'来检查它.

例:

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")
Run Code Online (Sandbox Code Playgroud)

  • 请注意,解析输出取决于主机OS语言。 (2认同)

Dan*_* F. 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.")  
Run Code Online (Sandbox Code Playgroud)

这按预期工作。退出代码不会给出误报。我已经在 Windows 7 和 Windows 10 上的 Python 2.7 和 3.4 中对其进行了测试。


Cam*_*Ice 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
Run Code Online (Sandbox Code Playgroud)

在这里,您有可以接收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()
Run Code Online (Sandbox Code Playgroud)

要在不实际显示程序的情况下运行程序,只需将文件另存为.pyw而不是.py.在用户检查运行进程之前,它会使其不可见.

希望它能帮助你


jdi*_*jdi 1

尝试这个:

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

-o 只等待一个数据包

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

-c 3 让它尝试几次,这样你的 ping 就不会永远运行