Python 에서 수 있는 방법이 있으면 핑할 ICMP 를 통한 서버 응답이 없을 경우, 또는 거짓값 복귀하십시오 flashcopy 서버가 응답할?
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!'
이 때문에 접속에 장애가 발생한 경우 넌제로 작동됨 핑할 값을 반환한다. (실제로 반환 값은 네트워크 오류가 따라 다릅니다.) & # 39 핑할 변경하십시오 시간초과를 수도 있습니다 (초) 을 사용하여 # 39 t&; -; 디바이스입니다. 참고, 이렇게 하면 출력입니다 텍스트를 콘솔이군요.
편집: 에서 [@radato] (https://stackoverflow.com/users/797396/radato) '' '' 서브프록스스콜 오스트시스템 대체되었다. 에서 [@Boris] (https://stackoverflow.com/users/3064538/) 를 사용하는 것이 좋습니다 붽뎄 ['서브프록스트런 ()'] [3] # 39 you& 사용하는 경우, re 파이썬 3.5+.
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
참고로 @ikrase 따르면, 이 기능은 Windows 에서 여전히 '대상' True '반품하십시오 나타날 경우 호스트 연결 불가' 오류:.
이 명령은 핑할 '에서' Windows 와 유닉스 계열 운영 체제. ' (Windows)' 또는 '-c' (Unix) -n 옵션이 패킷의 수를 제어됩니다 디스크입니다. 예제에서와 설정되었습니다 1.
['판포마리시스템 ()'] [1] 되돌려줍니다 플랫폼 이름. Ex. # 39, & # 39 Darwin& ',' 를 macOS. ['서브프록스스콜 ()'] [2] 는 시스템 호출. Ex. '서브프록스스콜 ([& # 39, & # 39 ls& # 39;; - l& # 39,])'.
[1]: https://docs.python.org/library/platform.html # 판포마리시스템 [2]: https://docs.python.org/library/subprocess.html # 서브프록스스콜 [3]: https://docs.python.org/library/subprocess.html # 서브프록스트런
왕리핑 이 작업을 수행할 수 있는 모듈인 있습니다. Pip 와 설치할 수 있습니다
pip install pyping
그러나 이 모듈에서는 사용할 때 필요한 것은 비교적 간단합니다 사용할 수 있다는 점을 기초형상 패킷 액세스 루트로부터의 인해 짜고 있는 후드요.
import pyping
r = pyping.ping('google.com')
if r.ret_code == 0:
print("Success")
else:
print("Failed with {}".format(r.ret_code))
왜냐면 난 내 범용 플랫폼 및 3.x 버전 2.7 그런겁니다 파이썬 프로그램에 따라, 기존 윈도, 리눅스, 맥 OS, 내가 수정하십시오 참조용이므로 했다.
# 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
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()
둘러보고, 난 후 나만의 핑할 모듈에서는 모니터링하도록 고안되었습니다 먹어서나 됐지 있는 많은 수의 충족합니다 doesn& # 39, t 는 비동기적입니다 및 시스템 자원을 많이 사용합니다. 여기에서 찾을 수 있습니다. https://github.com/romana/multi-ping/ # 39, 아파치 프로젝트에 사용할 수 있도록 It& 라이센스됨, 그 어떤 식으로든 충족합니다 볼 수 있습니다.
내 자신의 가장 큰 이유는 다른 접근 제한 규정을 구현할 수 있다.
from ping3 import ping, verbose_ping
ping('example.com') # Returns delay in seconds.
>>> 0.215697261510079666
이 모듈을 통해 사용자정의화 대한 일부 매개변수입니다 잘 알려져 있다.
내가 이 문제를 해결할 호스트당:
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" 핑할 다운로드되었는지 방법을 제대로. 건배
Icmp 는 프로그래밍 방식으로 인해 높은 권한을 기초형상 ICMP 패킷을 보내는 데 필요한 복잡한 핑할 호출하십시오 핑할 않았다는거지 binary) 은 '및' 서버 모니터링, 라고 하는 기술을 사용하여 TCP 핑할 동일한 결과를 얻을 수 있습니다.
# 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 연결을 통해 내부적으로 타겟대상 서버 및 떨어트림 바로, 측정 시간이. # 39 는 비트 리미티드, 처리할 수 있다는 점에서 이 특정 구축현 doesn& 단힌 포트+ 위한 것이 아니라 자체 서버를 작동하잖아 거의 없다.
단 이 게시물에 답변을 통해 새로운 아이디어를 내 감소 및 하위 권장됨 사용하여 모듈에서는 python3:
import subprocess
import platform
operating_sys = platform.system()
nas = '192.168.0.10'
def ping(ip):
# ping_command = ['ping', ip, '-n', '1'] instead of ping_command = ['ping', ip, '-n 1'] for Windows
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)
내 버전의 핑할 기능:
데프 핑할 (host_or_ip, 패킷 시간초과했습니다 =, = 1, 1000년): & # 39, & # 39, & # 39. 시스템 호출 " ping"; 명령을 되면 되돌려줍니다 핑할 성공합니다. 필요한 매개변수입니다: host_or_ip (str, 주소를 호스트에서 ping) 선택적 매개 변수. 패킷 (int, number of retries), 시간 초과 (int, ms 기다려야 응답) 표시하지 않고 출력입니다 수도 있고, 팝업 창 또는 명령줄입니다. 파이썬 3.5+, Windows, Linux 호환적 (Mac 필터링되지 테스트됨, 노력해야 합니다) & # 39, & # 39, & # 39.
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
"' 언제든지 정보기술 (it) 을 사용할 수 있습니다.
이 작업을 하고 다른 os 는 Windows 의 스크립트입니다. Windows 에서 작동하잖아 에서라도, 데비안, 그리고 필요한 시험을 solris.
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
이 질문에 대해 됐지 내가 찾는 유사한 상황이. 그러나 노력했다고 아웃해야 왕리핑 예제에서와 didn& # 39 에서 Windows 에서 제공한 나빈, 파이썬 2.7 가져다줄래요 빗나갔다.
보여주는 협력했습니다 가져다줄래요 입니다.
import pyping
response = pyping.send('Your IP')
if response['ret_code'] == 0:
print("reachable")
else:
print("unreachable")
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)
한, 두 번째 매개변수입니다 " 스케쳐내 샘플링합니다 '10' "; 무시할 수 있습니다!
import platform
import subprocess
def ping(host, network_timeout=3):
"""Send a ping packet to the specified host, using the system "ping" command."""
args = [
'ping'
]
platform_os = platform.system().lower()
if platform_os == 'windows':
args.extend(['-n', '1'])
args.extend(['-w', str(network_timeout * 1000)])
elif platform_os in ('linux', 'darwin'):
args.extend(['-c', '1'])
args.extend(['-W', str(network_timeout)])
else:
raise NotImplemented('Unsupported OS: {}'.format(platform_os))
args.append(host)
try:
if platform_os == 'windows':
output = subprocess.run(args, check=True, universal_newlines=True).stdout
if output and 'TTL' not in output:
return False
else:
subprocess.run(args, check=True)
return True
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
return False
그래서 구현됩니까 비슷한 조건을 갖고 있다 (아래 참조). It 테스트됩니다 Windows 의 64 비트 및 리눅스.
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 () 는 한 때 접속할 수 없는 예외적인 경우입니다. & # 39 에서 정보를 추가 확인 할 수 있습니다 추출하여 출력입니다 선, 패킷: (= 0 = 2, 손실됩니다 수신되었습니다 전송됩니까 = 2, 0%, & # 39 패).
하지만 부응합니다 정도로 간단한 내게 준 것 같다. 난 계속 " 가져오는 것은 소켓 작업, icmp 열기을 permitted". 또는 그 외의 경우 솔루션뀉뀉뀉뀉 다시그것들을 끊어 서버가 끄기도구 할말이다 그러나 그리웠댔지 알 수 있는 웹 서버 실행 중인 에로남이네 서버만을 살아 있으며, 서버, 그리고 컬 작업을 할 것이다. 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