在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返回一个非零值。 (返回值实际上取决于networking错误。)您也可以使用'-t'选项更改ping超时(以秒为单位)。 请注意,这将输出文本到控制台。

该function适用​​于任何操作系统(Unix,Linux,OS X和Windows)
Python 2和Python 3

编辑:添加一些评论给原来的答案。

 from platform import system as system_name # Returns the system/OS name from os import system as system_call # Execute a shell command def ping(host): """ Returns True if host (str) responds to a ping request. Remember that some hosts may not respond to a ping request even if the host name is valid. """ # Ping parameters as function of OS parameters = "-n 1" if system_name().lower()=="windows" else "-c 1" # Pinging return system_call("ping " + parameters + " " + host) == 0 

该命令在Windows和类Unix系统中均为ping
选项-n(Windows)或-c(Unix)控制本例中设置为1的数据包数量。

platform.system()返回平台名称。 防爆。 OS X中的'Darwin'
os.system()执行系统调用。 防爆。 os.system('ls -al')

有一个叫pyping的模块可以做到这一点。 它可以与点安装

 pip install pyping 

使用这个模块非常简单,但是在使用这个模块的时候,你需要root访问权限,因为它是在原始数据包下创build原始数据包。

 import pyping r = pyping.ping('google.com') if r.ret_code == 0: print("Viagra") else: print("Promescent") 
 import subprocess ping_response = subprocess.Popen(["/bin/ping", "-c1", "-w100", "192.168.0.1"], stdout=subprocess.PIPE).stdout.read() 

纯Python平台服务作为一个类,Linux或Windows,它使用线程:

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

确保安装pyping或安装pip安装pyping

 #!/usr/bin/python import pyping response = pyping.ping('Your IP') if response.ret_code == 0: print("reachable") else: print("unreachable") 
 #!/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() 

因为我喜欢在2.7和3.x版本以及平台Linux,Mac OS和Windows上使用Python程序,所以我不得不修改现有的示例。

 # shebang does not work over all platforms # ping.py 2016-02-25 Rudolf # subprocess.call() is preferred to os.system() # works under Python 2.7 and 3.4 # works under Linux, Mac OS, Windows def ping(host): """ Returns True if host responds to a ping request """ import subprocess, platform # Ping parameters as function of OS ping_str = "-n 1" if platform.system().lower()=="windows" else "-c 1" args = "ping " + " " + ping_str + " " + host need_sh = False if platform.system().lower()=="windows" else True # Ping return subprocess.call(args, shell=need_sh) == 0 # test call print(ping("192.168.17.142")) 
 #!/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 !") 

我最终发现了类似的情况下的这个问题。 我尝试了pyping,但是在Python 2.7下,Naveen给出的例子在Windows中并不适用。

一个适用于我的例子是:

 import pyping response = pyping.send('Your IP') if response['ret_code'] == 0: print("reachable") else: print("unreachable") 

这个脚本可以在Windows上运行,并且可以在其他操作系统上运行:在Windows,Debian和macosx上运行,需要在solaris上testing。

 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("example.com")) #Example domain print(isUp("localhost")) #Your computer print(isUp("invalid.example.com")) #Unresolvable hostname: https://tools.ietf.org/html/rfc6761 print(isUp("192.168.1.1")) #Pings local router print(isUp("192.168.1.135")) #Pings a local computer - will differ for your network 

我减less使用在这篇文章中的答案的想法,但只使用较新推荐的subprocess模块和python3:

 import subprocess import platform operating_sys = platform.system() nas = '192.168.0.10' def ping(ip): ping_command = ['ping', ip, '-n 1'] if operating_sys == 'Windows' else ['ping', ip, '-c 1'] shell_needed = True if operating_sys == 'Windows' else False ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode return True if success == 0 else False out = ping(nas) print(out) 

环顾四周后,我写了自己的ping模块,它被devise用来监视大量的地址,是asynchronous的,并且不占用大量的系统资源。 你可以在这里find它: https : //github.com/romana/multi-ping/它是Apache许可的,所以你可以用你认为合适的方式在你的项目中使用它。

实施我自己的主要原因是其他方法的限制:

  • 这里提到的许多解决scheme需要执行一个命令行工具。 如果您需要监视大量的IP地址,这是相当低效和资源饥饿的。
  • 其他人提到一些较老的python ping模块。 我看了看那些,最后都发现了一些问题(比如没有正确设置数据包ID),也没有处理大量地址的ping操作。

我解决这个问题:

 def ping(self, host): res = False ping_param = "-n 1" if system_name().lower() == "windows" else "-c 1" resultado = os.popen("ping " + ping_param + " " + host).read() if "TTL=" in resultado: res = True return res 

“TTL”是知道ping是否正确的方法。 Saludos

似乎很简单,但给了我适合。 我不断收到“ICMP开放套接字操作不允许”,否则解决scheme将挂断,如果服务器脱机。 但是,如果你想知道服务器是活着的,而且你正在该服务器上运行一个Web服务器,那么curl就可以完成这项工作。 如果你有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 

使用它在Python 2.7上进行testing,工作正常,如果成功返回ping时间(以毫秒为单位),返回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上进行testing。

 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()引发exception。 额外的validation可以通过从输出行'信息包:发送= 2,收到= 2,丢失= 0(0%丢失)'中提取信息来完成。

  1 #!/usr/bin/python 2 3 import os 4 import sys 5 import time 6 7 os.system("clear") 8 home_network = "172.16.23." 9 mine = [] 10 11 for i in range(1, 256): 12 z = home_network + str(i) 13 result = os.system("ping -c 1 "+ str(z)) 14 os.system("clear") 15 if result == 0: 16 mine.append(z) 17 18 for j in mine: 19 print "host ", j ," is up" 

一个简单的我刚刚熟了一分钟..使用icmplib需要root privs下面的作品相当不错! HTH