others - 在 python 中ping服务器

在Python中,是否可以通过ICMP对服务器进行ping操作,如果服务器响应,就返回TRUE,如果没有响应,就返回FALSE?

时间:

如果你不需要支持Windows,这里是一种非常简洁的方法:


import os
hostname ="google.com" #example
response = os.system("ping -c 1" + hostname)

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

因为连接失败,ping会返回一个非零值,(返回值实际上不同于网络错误),也可以使用'-t'选项更改ping超时(以秒为单位),注意,这将输出文本到控制台。


import subprocess
ping_response = subprocess.Popen(["/bin/ping","-c1","-w100","192.168.0.1"], stdout=subprocess.PIPE).stdout.read()

我使用的另一个纯python ping实现:

http://www.g-loaded.eu/2009/10/30/python-ping/

纯python ping服务,使用线程类:

https://github.com/duanev/ping-python


#!/usr/bin/python3

import subprocess as sp

ip ="192.168.122.60"
status,result = sp.getstatusoutput("ping -c1 -w2" + ip)

if status == 0: 
 print("System" + ip +" is UP !")
else:
 print("System" + ip +" is DOWN !")


#!/usr/bin/python3

import subprocess as sp

def ipcheck():
 status,result = sp.getstatusoutput("ping -c1 -w2" + str(pop))
 if status == 0:
 print("System" + str(pop) +" is UP !")
 else:
 print("System" + str(pop) +" is DOWN !")


pop = input("Enter the ip address:")
ipcheck()

如果你拥有ssh和证书,那么ssh和一个简单的命令就足够了,下面是代码:


from easyprocess import EasyProcess # as root: pip install EasyProcess
def ping(ip):
 ping="ssh %s date;exit"%(ip) # test ssh alive or
 ping="curl -IL %s"%(ip) # test if http alive
 response=len(EasyProcess(ping).call(timeout=2).stdout)
 return response #integer 0 if no response in 2 seconds

此脚本适用于Windows,并且应该在其他OS上工作: 它在Windows,debian和平台上工作,在solaris上需要另行测试。


import os
import platform


def isUp(hostname):

 giveFeedback = False

 if platform.system() =="Windows":
 response = os.system("ping"+hostname+" -n 1")
 else:
 response = os.system("ping -c 1" + hostname)

 isUpBool = False
 if response == 0:
 if giveFeedback:
 print hostname, 'is up!'
 isUpBool = True
 else:
 if giveFeedback:
 print hostname, 'is down!'

 return isUpBool

print(isUp("google.com")) #Google
print(isUp("localhost")) #Your computer
print(isUp("examplewebsitethatdoesntexist.com")) #Website that doesn't exist
print(isUp("192.168.1.1")) #Pings local router
print(isUp("192.168.1.135")) #Pings a local computer - will differ for your network

在python 2.7上进行测试过,工作精确,如果成功返回ping时间毫秒,失败则return false。


import platform,subproccess,re
def Ping(hostname,timeout):
 if platform.system() =="Windows":
 command="ping"+hostname+" -n 1 -w"+str(timeout*1000)
 else:
 command="ping -i"+str(timeout)+" -c 1" + hostname
 proccess = subprocess.Popen(command, stdout=subprocess.PIPE)
 matches=re.match('.*time=([0-9]+)ms.*', proccess.stdout.read(),re.DOTALL)
 if matches:
 return matches.group(1)
 else: 
 return False

我有类似的需求,因此我实现了如下所示,它已在Windows 64位和Linux上进行了测试。


import subprocess
def systemCommand(Command):
 Output =""
 Error ="" 
 try:
 Output = subprocess.check_output(Command,stderr = subprocess.STDOUT,shell='True')
 except subprocess.CalledProcessError as e:
 #Invalid command raises this exception
 Error = e.output 

 if Output:
 Stdout = Output.split("n")
 else:
 Stdout = []
 if Error:
 Stderr = Error.split("n")
 else:
 Stderr = []

 return (Stdout,Stderr)

#in main
Host ="ip to ping"
NoOfPackets = 2
Timeout = 5000 #in milliseconds
#Command for windows
Command = 'ping -n {0} -w {1} {2}'.format(NoOfPackets,Timeout,Host)
#Command for linux 
#Command = 'ping -c {0} -w {1} {2}'.format(NoOfPackets,Timeout,Host)
Stdout,Stderr = systemCommand(Command)
if Stdout:
 print("Host [{}] is reachable.".format(Host))
else:
 print("Host [{}] is unreachable.".format(Host))

当IP不可达时subprocess.check_output()引发异常,可以通过从输出行的数据包中提取信息来进行额外的验证: sent = 2 ,received = 2 ,lost = 0 (0% loss)'.

...