【问题标题】:Local network pinging in pythonpython中的本地网络ping
【发布时间】:2011-12-02 11:15:33
【问题描述】:

有谁知道如何使用 python ping 本地主机以查看它是否处于活动状态?我们(我和我的团队)已经尝试过使用

os.system("ping 192.168.1.*") 

但是destination unreachable的响应与host的响应是一样的。

感谢您的帮助。

【问题讨论】:

    标签: networking ping


    【解决方案1】:

    试试这个:

    ret = os.system("ping -o -c 3 -W 3000 192.168.1.10")
    if ret != 0:
        print "Host is not up"
    

    -o 只等待一个数据包

    -W 3000 只给它 3000 毫秒来回复数据包。

    -c 3 让它尝试几次,这样你的 ping 就不会永远运行

    【讨论】:

      【解决方案2】:

      使用它并解析字符串输出

      import subprocess output = subprocess.Popen(["ping.exe","192.168.1.1"],stdout = subprocess.PIPE).communicate()[0]

      【讨论】:

        【解决方案3】:

        使用这个...

        import os
        
        hostname = "localhost" #example
        response = os.system("ping -n 1 " + hostname)
        
        #and then check the response...
        if response == 0:
            print(hostname, 'is up!')
        else:
            print(hostname, 'is down!')
        

        如果在 unix/Linux 上使用此脚本,请将 -n 开关替换为 -c !
        就是这样:)

        【讨论】:

        • 如果我收到回复“目标主机无法访问”。它不工作。
        • 确定问题可能会更好。但正如他在描述中所说,它不适用于“目标主机无法访问”。 - 所以你的答案我一直错。
        【解决方案4】:

        不久前我编写了一个小程序。它可能不是您正在寻找的确切内容,但您始终可以在主机操作系统上运行一个程序,该程序在启动时打开一个套接字。这是 ping 程序本身:

        # Run this on the PC that want to check if other PC is online.
        from socket import *
        
        def pingit():                               # defining function for later use
        
            s = socket(AF_INET, SOCK_STREAM)         # Creates socket
            host = 'localhost' # Enter the IP of the workstation here 
            port = 80                # Select port which should be pinged
        
            try:
                s.connect((host, port))    # tries to connect to the host
            except ConnectionRefusedError: # if failed to connect
                print("Server offline")    # it prints that server is offline
                s.close()                  #closes socket, so it can be re-used
                pingit()                   # restarts whole process    
        
            while True:                    #If connected to host
                print("Connected!")        # prints message 
                s.close()                  # closes socket just in case
                exit()                     # exits program
        
        pingit()                           #Starts off whole process
        

        这里有可以接收 ping 请求的程序:

        # this runs on remote pc that is going to be checked
        from socket import *
        
        HOST = 'localhost'
        PORT = 80
        BUFSIZ = 1024
        ADDR = (HOST, PORT)
        serversock = socket(AF_INET, SOCK_STREAM)
        serversock.bind(ADDR)
        serversock.listen(2)
        
        while 1:
            clientsock, addr = serversock.accept()
            serversock.close()
            exit()
        

        要运行程序而不实际显示它,只需将文件保存为 .pyw 而不是 .py。 在用户检查正在运行的进程之前,它使其不可见。

        希望对你有帮助

        【讨论】:

        • 抱歉 - 但问题是 ping 服务器,这是一个不同的场景。只有当您知道服务器存在并且处于活动状态时,连接才有意义!
        【解决方案5】:

        我发现使用 os.system(...) 会导致误报(正如 OP 所说,'destination host unreachable' == 0)。

        如前所述,使用 subprocess.Popen 有效。为简单起见,我建议先执行此操作,然后再解析结果。您可以轻松地这样做:

        if ('unreachable' in output):
                print("Offline")
        

        只需从 ping 结果中检查您要检查的各种输出。在 'that' 中做一个 'this' 检查。

        例子:

        import subprocess
        
        hostname = "10.20.16.30"
        output = subprocess.Popen(["ping.exe",hostname],stdout = subprocess.PIPE).communicate()[0]
        
        print(output)
        
        if ('unreachable' in output):
            print("Offline")
        

        【讨论】:

        • 注意解析输出取决于主机操作系统语言。
        【解决方案6】:

        为简单起见,我使用基于socket的自制函数。

        def checkHostPort(HOSTNAME, PORT):
            """
                check if host is reachable
            """
            result = False
            try:
                destIp  =  socket.gethostbyname(HOSTNAME)
            except:
                return result
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(15)
            try:
                conn = s.connect((destIp, PORT))
                result = True
                conn.close()
            except:
                pass
            return result
        

        如果 Ip:Port 可达,则返回 True

        如果你想模拟Ping,可以参考ping.py

        【讨论】:

          【解决方案7】:

          如果您不想解析输出,我能找到在 Windows 上执行此操作的最佳方法是像这样使用 Popen:

          num = 1
          host = "192.168.0.2"
          wait = 1000
          
          ping = Popen("ping -n {} -w {} {}".format(num, wait, host),
                       stdout=PIPE, stderr=PIPE)  ## if you don't want it to print it out
          exit_code = ping.wait()
          
          if exit_code != 0:
              print("Host offline.")
          else:
              print("Host online.")  
          

          这按预期工作。退出代码没有给出误报。我已经在 Windows 7 和 Windows 10 上的 Python 2.7 和 3.4 中对其进行了测试。

          【讨论】:

            【解决方案8】:

            请求模块呢?

            import requests
            
            def ping_server(address):
                try:
                    requests.get(address, timeout=1)
                except requests.exceptions.ConnectTimeout:
                    return False
            
            return True
            
            • 无需拆分 url 即可移除端口或测试端口,也无需 localhost 误报。
            • 超时量并不重要,因为它只在没有服务器时才达到超时,这在我的情况下意味着性能不再重要。否则,它会以请求的速度返回,这对我来说已经足够快了。
            • 超时等待第一位,而不是总时间,以防万一。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-12-10
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多