216

Python では、ICMP を介してサーバーに ping を実行し、サーバーが応答する場合は TRUE を返し、応答がない場合は FALSE を返す方法はありますか?

4

29 に答える 29

190

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 タイムアウト (秒単位) を変更することもできます。これにより、テキストがコンソールに出力されることに注意してください。

于 2012-05-01T18:29:04.973 に答える
32
import subprocess
ping_response = subprocess.Popen(["/bin/ping", "-c1", "-w100", "192.168.0.1"], stdout=subprocess.PIPE).stdout.read()
于 2010-06-01T21:34:26.920 に答える
27

python3 には、非常にシンプルで便利な python モジュールping3があります: (にはroot権限pip install ping3が必要です)。

from ping3 import ping, verbose_ping
ping('example.com')  # Returns delay in seconds.
>>> 0.215697261510079666

このモジュールでは、一部のパラメーターをカスタマイズすることもできます。

于 2017-12-21T13:50:43.157 に答える
18

Python プログラムをバージョン 2.7 と 3.x、およびプラットフォーム Linux、Mac OS、Windows でユニバーサルにしたいので、既存の例を変更する必要がありました。

# 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"))
于 2016-02-25T10:47:12.273 に答える
7

pyping がインストールされていることを確認するか、インストールしてくださいpip install pyping

#!/usr/bin/python
import pyping

response = pyping.ping('Your IP')

if response.ret_code == 0:
    print("reachable")
else:
    print("unreachable")
于 2015-12-16T06:17:46.233 に答える
5
#!/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 !")
于 2014-10-01T15:07:44.550 に答える
5

私はこれを解決します:

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 が正しいかどうかを知る方法です。サルドス

于 2017-09-06T15:30:40.103 に答える
3

このスクリプトは Windows で動作し、他の OS でも動作するはずです: 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
于 2015-02-13T22:00:38.793 に答える
2

十分に単純に思えますが、私には合いました。「icmp オープン ソケット操作が許可されていません」というメッセージが表示され続けるか、サーバーがオフラインの場合にソリューションがハングアップします。ただし、サーバーが稼働中で、そのサーバーで 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
于 2015-02-10T20:18:39.967 に答える
2

同様の要件があったため、以下に示すように実装しました。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)' から情報を抽出することにより、追加の検証を行うことができます。

于 2015-05-21T10:58:50.280 に答える
2

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
于 2015-04-11T17:07:13.527 に答える
2

これは、Python のsubprocessモジュールとping、基盤となる OS によって提供される CLI ツールを使用したソリューションです。Windows と Linux でテスト済み。ネットワーク タイムアウトの設定をサポートします。root 権限は必要ありません (少なくとも Windows と Linux では)。

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
于 2018-02-13T12:45:47.010 に答える
-3
  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"

簡単なものを 1 分で作成しました。icmplib を使用するにはルート権限が必要です。以下はかなりうまく機能します。HTH

于 2014-03-15T12:37:31.460 に答える