【发布时间】:2011-12-02 11:15:33
【问题描述】:
有谁知道如何使用 python ping 本地主机以查看它是否处于活动状态?我们(我和我的团队)已经尝试过使用
os.system("ping 192.168.1.*")
但是destination unreachable的响应与host的响应是一样的。
感谢您的帮助。
【问题讨论】:
标签: networking ping
有谁知道如何使用 python ping 本地主机以查看它是否处于活动状态?我们(我和我的团队)已经尝试过使用
os.system("ping 192.168.1.*")
但是destination unreachable的响应与host的响应是一样的。
感谢您的帮助。
【问题讨论】:
标签: networking ping
试试这个:
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 就不会永远运行
【讨论】:
使用它并解析字符串输出
import subprocess
output = subprocess.Popen(["ping.exe","192.168.1.1"],stdout = subprocess.PIPE).communicate()[0]
【讨论】:
使用这个...
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 !
就是这样:)
【讨论】:
不久前我编写了一个小程序。它可能不是您正在寻找的确切内容,但您始终可以在主机操作系统上运行一个程序,该程序在启动时打开一个套接字。这是 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。 在用户检查正在运行的进程之前,它使其不可见。
希望对你有帮助
【讨论】:
我发现使用 os.system(...) 会导致误报(正如 OP 所说,'destination host unreachable' == 0)。
如前所述,使用 subprocess.Popen 有效。为简单起见,我建议先执行此操作,然后再解析结果。您可以轻松地这样做:
if ('unreachable' in output):
print("Offline")
只需从 ping 结果中检查您要检查的各种输出。在 'that' 中做一个 '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")
【讨论】:
为简单起见,我使用基于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
【讨论】:
如果您不想解析输出,我能找到在 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 中对其进行了测试。
【讨论】:
请求模块呢?
import requests
def ping_server(address):
try:
requests.get(address, timeout=1)
except requests.exceptions.ConnectTimeout:
return False
return True
【讨论】: