有人知道如何使用Python来ping本地主机以查看它是否处于活动状态吗?我们(我和我的团队)已经尝试使用
os.system("ping 192.168.1.*")
但对于目标不可达的响应与主机正常响应的响应相同。
感谢您的帮助。
有人知道如何使用Python来ping本地主机以查看它是否处于活动状态吗?我们(我和我的团队)已经尝试使用
os.system("ping 192.168.1.*")
但对于目标不可达的响应与主机正常响应的响应相同。
感谢您的帮助。
使用此功能,可以轻松地将文本转换为另一种语言。
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!
就这些:)
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")
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中进行了测试。
我之前编写了一个小程序。虽然它可能不是你正在寻找的完全符合要求的东西,但你可以在主机操作系统上运行一个程序来启动一个套接字。这是本身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()
为了简单起见,我使用基于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
试试这个:
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 requests
def ping_server(address):
try:
requests.get(address, timeout=1)
except requests.exceptions.ConnectTimeout:
return False
return True
使用这个方法并解析字符串输出
import subprocess
output = subprocess.Popen(["ping.exe","192.168.1.1"],stdout = subprocess.PIPE).communicate()[0]