在Python中,有没有办法通过ICMP ping服务器,如果服务器响应则返回TRUE,如果没有响应则返回FALSE?
答案 0 :(得分:134)
如果您不需要支持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超时(以秒为单位)。注意,这会将文本输出到控制台。
答案 1 :(得分:78)
此功能适用于任何操作系统(Unix,Linux,macOS和Windows)
Python 2和Python 3
编辑:
@radato os.system
被subprocess.call
取代
截至@Boris如果您使用的是Python 3.5 +,则文档建议您使用subprocess.run()
。
import platform # For getting the operating system name
import subprocess # For executing a shell command
def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
"""
# Option for the number of packets as a function of
param = '-n' if platform.system().lower()=='windows' else '-c'
# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', param, '1', host]
return subprocess.call(command) == 0
请注意,根据Windows上的@ikrase,如果您收到True
错误,此功能仍会返回Destination Host Unreachable
。
<强>解释强>
Windows和类Unix系统中的命令均为ping
选项-n
(Windows)或-c
(Unix)控制在此示例中设置为1的数据包数。
platform.system()
返回平台名称。防爆。 macOS上的'Darwin'
subprocess.call()
执行系统调用。防爆。 subprocess.call(['ls','-l'])
。
答案 2 :(得分:27)
import subprocess
ping_response = subprocess.Popen(["/bin/ping", "-c1", "-w100", "192.168.0.1"], stdout=subprocess.PIPE).stdout.read()
答案 3 :(得分:12)
因为我喜欢在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"))
答案 4 :(得分:6)
#!/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()
答案 5 :(得分:6)
确保安装了Pyping或安装 pip install pyping
#!/usr/bin/python
import pyping
response = pyping.ping('Your IP')
if response.ret_code == 0:
print("reachable")
else:
print("unreachable")
答案 6 :(得分:5)
环顾四周之后,我最终编写了自己的ping模块,该模块用于监控大量地址,是异步的,并且不使用大量系统资源。您可以在此处找到它:https://github.com/romana/multi-ping/它获得了Apache许可,因此您可以以您认为合适的任何方式在项目中使用它。
实施我自己的主要原因是其他方法的限制:
答案 7 :(得分:3)
我用以下方法解决了这个问题:
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
答案 8 :(得分:3)
使用多次发送(pip install multiPing
)我创建了这个简单的代码(只是复制并粘贴,如果你愿意的话!):
from multiping import MultiPing
def ping(host,n = 0):
if(n>0):
avg = 0
for i in range (n):
avg += ping(host)
avg = avg/n
# Create a MultiPing object to test hosts / addresses
mp = MultiPing([host])
# Send the pings to those addresses
mp.send()
# With a 1 second timout, wait for responses (may return sooner if all
# results are received).
responses, no_responses = mp.receive(1)
for addr, rtt in responses.items():
RTT = rtt
if no_responses:
# Sending pings once more, but just to those addresses that have not
# responded, yet.
mp.send()
responses, no_responses = mp.receive(1)
RTT = -1
return RTT
<强>用法:强>
#Getting the latency average (in seconds) of host '192.168.0.123' using 10 samples
ping('192.168.0.123',10)
如果你想要一个样本,第二个参数&#34; 10
&#34;可以忽略!
希望它有所帮助!
答案 9 :(得分:2)
由于发送原始ICMP数据包所需的特权提升,编程ICMP ping很复杂,而调用ping
二进制文件很难看。对于服务器监视,您可以使用名为 TCP ping 的技术:
# pip3 install tcping
>>> from tcping import Ping
# Ping(host, port, timeout)
>>> ping = Ping('212.69.63.54', 22, 60)
>>> ping.ping(3)
Connected to 212.69.63.54[:22]: seq=1 time=23.71 ms
Connected to 212.69.63.54[:22]: seq=2 time=24.38 ms
Connected to 212.69.63.54[:22]: seq=3 time=24.00 ms
在内部,这只是建立到目标服务器的TCP连接并立即丢弃它,测量经过的时间。这个特定的实现有点受限制,因为它不处理关闭的端口,但是对于你自己的服务器,它运行得很好。
答案 10 :(得分:2)
我最终在类似情况下找到了这个问题。我尝试了pyping,但Naveen给出的例子在Windows 2.7下的Windows中并不适用。
一个对我有用的例子是:
import pyping
response = pyping.send('Your IP')
if response['ret_code'] == 0:
print("reachable")
else:
print("unreachable")
答案 11 :(得分:2)
#!/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 !")
答案 12 :(得分:2)
我使用这篇文章中的答案中的想法减少了但只使用了新推荐的子进程模块和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)
答案 13 :(得分:1)
我有类似的要求所以我实现它如下所示。它在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()会引发异常。可以通过从输出行'Packets:Sent = 2,Received = 2,Lost = 0(0%loss)'中提取信息来完成额外验证。
答案 14 :(得分:1)
在python3中使用socket包:
import socket
def ping_server(server: str, port: int, timeout=3):
"""ping server"""
try:
socket.setdefaulttimeout(timeout)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server, port))
except OSError as error:
return False
else:
s.close()
return True
答案 15 :(得分:1)
我的ping功能版本:
import platform, subprocess
def ping(host_or_ip, packets=1, timeout=1000):
''' Calls system "ping" command, returns True if ping succeeds.
Required parameter: host_or_ip (str, address of host to ping)
Optional parameters: packets (int, number of retries), timeout (int, ms to wait for response)
Does not show any output, either as popup window or in command line.
Python 3.5+, Windows and Linux compatible (Mac not tested, should work)
'''
# The ping command is the same for Windows and Linux, except for the "number of packets" flag.
if platform.system().lower() == 'windows':
command = ['ping', '-n', str(packets), '-w', str(timeout), host_or_ip]
# run parameters: capture output, discard error messages, do not show window
result = subprocess.run(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, creationflags=0x08000000)
# 0x0800000 is a windows-only Popen flag to specify that a new process will not create a window.
# On Python 3.7+, you can use a subprocess constant:
# result = subprocess.run(command, capture_output=True, creationflags=subprocess.CREATE_NO_WINDOW)
# On windows 7+, ping returns 0 (ok) when host is not reachable; to be sure host is responding,
# we search the text "TTL=" on the command output. If it's there, the ping really had a response.
return result.returncode == 0 and b'TTL=' in result.stdout
else:
command = ['ping', '-c', str(packets), '-w', str(timeout), host_or_ip]
# run parameters: discard output and error messages
result = subprocess.run(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return result.returncode == 0
随时随地使用它。
答案 16 :(得分:1)
这是使用Python的[InvalidOperationException: Sequence contains no elements]
System.Linq.Enumerable.First(IEnumerable`1 source) +301
Linkofy.Controllers.IdentifiersController.CreateBulkUpload(Identifier model) in C:\Users\liam\Documents\Visual Studio 2017\Linkofy4\Linkofy\Controllers\IdentifiersController.cs:229
lambda_method(Closure , ControllerBase , Object[] ) +104
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +228
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9748493
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159
模块和底层操作系统提供的subprocess
CLI工具的解决方案。在Windows和Linux上测试过。支持设置网络超时。不需要root权限(至少在Windows和Linux上)。
ping
答案 17 :(得分:1)
我喜欢ping3 https://github.com/kyan001/ping3 非常简单方便!
from ping3 import ping, verbose_ping
ping('example.com') # Returns delay in seconds.
>>>0.215697261510079666
答案 18 :(得分:1)
此脚本适用于Windows,应该适用于其他操作系统: 它适用于Windows,Debian和macosx,需要对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("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
答案 19 :(得分:0)
看似简单,但给了我适合。我一直在不允许打开套接字操作&#34;如果服务器脱机,解决方案将挂断。但是,如果您想知道的是服务器处于活动状态并且您正在该服务器上运行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
答案 20 :(得分:0)
许多答案遗漏的一件事是(至少在Windows中)ping
命令返回0(表示成功),如果它收到回复&#34;目标主机无法访问。&#34; < / p>
这是我的代码,用于检查响应中是否有b'TTL='
,因为只有在ping到达主机时才会出现。注意:此代码的大部分内容都基于其他答案。
import platform
import subprocess
def ping(ipAddr, timeout=100):
'''
Send a ping packet to the specified host, using the system ping command.
Accepts ipAddr as string for the ping destination.
Accepts timeout in ms for the ping timeout.
Returns True if ping succeeds otherwise Returns False.
Ping succeeds if it returns 0 and the output includes b'TTL='
'''
if platform.system().lower() == 'windows':
numFlag = '-n'
else:
numFlag = '-c'
completedPing = subprocess.run(['ping', numFlag, '1', '-w', str(timeout), ipAddr],
stdout=subprocess.PIPE, # Capture standard out
stderr=subprocess.STDOUT) # Capture standard error
# print(completedPing.stdout)
return (completedPing.returncode == 0) and (b'TTL=' in completedPing.stdout)
print(ping('google.com'))
注意:这会捕获输出而不是打印输出,因此如果您想查看ping
的输出,则在返回之前需要打印completedPing.stdout
。
答案 21 :(得分:0)
仅限WINDOWS - 无法相信没有人破解Win32_PingStatus 使用简单的WMI查询,我们返回一个充满了免费的详细信息的对象
import wmi
# new WMI object
c = wmi.WMI()
# here is where the ping actually is triggered
x = c.Win32_PingStatus(Address='google.com')
# how big is this thing? - 1 element
print 'length x: ' ,len(x)
#lets look at the object 'WMI Object:\n'
print x
#print out the whole returned object
# only x[0] element has values in it
print '\nPrint Whole Object - can directly reference the field names:\n'
for i in x:
print i
#just a single field in the object - Method 1
print 'Method 1 ( i is actually x[0] ) :'
for i in x:
print 'Response:\t', i.ResponseTime, 'ms'
print 'TTL:\t', i.TimeToLive
#or better yet directly access the field you want
print '\npinged ', x[0].ProtocolAddress, ' and got reply in ', x[0].ResponseTime, 'ms'
答案 22 :(得分:0)
我从其他答案中借用。尝试简化和最小化查询。
import platform, os
def ping(host):
result = os.popen(' '.join(("ping", ping.param, host))).read()
return 'TTL=' in result
ping.param = "-n 1" if platform.system().lower() == "windows" else "-c 1"
答案 23 :(得分:0)
您可以使用子进程模块的TimeoutExpired
异常来捕获ping超时(其他答案尚未利用。)请注意,此解决方案仅在Linux上有效。
def ping(host, timeout=3):
"""
Send a ping (ICMP) request to a remote host.
The command is set to ``ping -c 1 -W 1 <host>``, which sends exactly 1 ping
packet, and waits for 1 second before terminating.
Args:
host (str): Hostname or IP address.
timeout (int): Ping command timeout (in seconds).
Returns:
bool: The ping response. ``True`` if the host responds to a ping request
within the specified timeout period. ``False`` otherwise.
Note:
A host may not respond to a ping (ICMP) request even if the host name is
valid because of firewall rules.
"""
# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', host, '-W', '1', '-c', '1']
try:
subprocess.run(command, timeout=timeout, check=True)
return True
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
#log.warning("Failed to ping host: %s with timeout: %d", host, timeout)
return False
答案 24 :(得分:0)
我需要更快的ping扫描,并且我不想使用任何外部库,所以我决定使用内置的asyncio
使用并发。
此代码需要 python 3.7 + ,并且仅在 Linux 上进行制作和测试。它不能在Windows上运行,但我相信您可以轻松地将其更改为在Windows上运行。
我不是asyncio
的专家,但是我使用了这篇很棒的文章Speed Up Your Python Program With Concurrency,然后想到了这些代码行。我试图使它尽可能简单,因此很可能您需要向其添加更多代码以满足您的需求。
它不会返回true或false,我认为将它打印出响应ping请求的IP会更方便。我认为这非常快,可以在 10 秒内ping 255 ips。
#!/usr/bin/python3
import asyncio
async def ping(host):
"""
Prints the hosts that respond to ping request
"""
ping_process = await asyncio.create_subprocess_shell("ping -c 1 " + host + " > /dev/null 2>&1")
await ping_process.wait()
if ping_process.returncode == 0:
print(host)
return
async def ping_all():
tasks = []
for i in range(1,255):
ip = "192.168.1.{}".format(i)
task = asyncio.ensure_future(ping(ip))
tasks.append(task)
await asyncio.gather(*tasks, return_exceptions = True)
asyncio.run(ping_all())
样本输出:
192.168.1.1
192.168.1.3
192.168.1.102
192.168.1.106
192.168.1.6
请注意,IP的顺序不正确,因为IP会在答复时立即打印出来,因此首先响应的IP会先打印出来。
答案 25 :(得分:0)
使用它在python 2.7上测试并正常工作,如果成功则返回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
答案 26 :(得分:0)
在 windows 或 linux 中对它们全部执行 Ping,返回一个排序列表。这是@Ahmed Essam 和@Arno 回复的混合/修复。
import asyncio
import re
import platform
isWindows = platform.system()
async def ping(host):
cmd = 'ping {} {} 1'.format(host, '-n' if isWindows else '-c')
ping_proc = \
await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await ping_proc.communicate()
outstr = stdout.decode()
if ping_proc.returncode == 0:
delay = int(re.search(r'(?:time=)([\d]*)', outstr).group(1)) if 'time=' in outstr else -1
if delay >= 0:
# print('{} {}ms'.format(host, delay))
return [host, delay]
return [host, None]
async def ping_all():
tasks = []
for i in range(1, 256):
ip = "192.168.1.{}".format(i)
task = asyncio.ensure_future(ping(ip))
tasks.append(task)
retList = await asyncio.gather(*tasks, return_exceptions=True)
retList = [x for x in retList if x[1] is not None]
retList.sort(key=lambda x: int(x[0].split('.')[-1]))
return retList
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
pingRet = loop.run_until_complete(ping_all())
for ip, d in pingRet:
print('{:<16s} {}ms'.format(ip, d))
答案 27 :(得分:-2)
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