有谁知道如何使用python ping本地主机来查看它是否活动?我们(我和我的团队)已经使用python中的本地网络pinging
os.system("ping 192.168.1.*")
已经尝试过但对目的地不可达的反应是一样的主机的响应起来。
感谢您的帮助。
有谁知道如何使用python ping本地主机来查看它是否活动?我们(我和我的团队)已经使用python中的本地网络pinging
os.system("ping 192.168.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让它试几次,这样你的平安犯规运行永远
使用此和解析字符串输出
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上使用此脚本,请用-c替换-n开关!
这就是所有:)
我已经编写了一个小程序,而回来。它可能不是您正在寻找的确切的东西,但您始终可以在启动时打开套接字的主机操作系统上运行程序。下面是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说,“目标主机不可达” == 0)。
如前所述,使用subprocess.Popen的作品。为了简单起见,我建议这样做,然后解析结果。你可以很容易地做到这一点,如:
if ('unreachable' in output):
print("Offline")
只需检查您要检查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")
请注意,解析输出取决于主机操作系统语言。 – Hauke
为了简单起见,我使用基于插座自制功能。
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
如果叶:港访问,返回True
如果你想模拟坪,可参照平。py
万一我得到回复'目标主机不可达'。它不工作。 –