【问题标题】:How to Grab IP address from ping in Python如何在 Python 中从 ping 中获取 IP 地址
【发布时间】:2018-03-11 18:58:47
【问题描述】:

我目前使用的是 python 2.7,需要 ping windows 和 linux。

我想创建一个函数,该函数将从 python 脚本中的 ping 返回 IP 地址。我目前有这个功能

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

现在它只返回 true 或 false,但有没有办法我可以运行 ping(google.com) 并让它返回 216.58.217.206。我有一个服务器和 IP 列表,我需要确保 IP 地址与 FQDN 匹配。

【问题讨论】:

标签: python python-2.7 ip ping


【解决方案1】:

您可以使用socket获取主机的IP。

import socket
print(socket.gethostbyname('www.example.com'))

【讨论】:

    【解决方案2】:

    不确定如何没有人尝试过这种方法(无论如何都适用于 Windows)!

    使用 W32_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'
    

    输出截图:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 2014-03-01
      • 2021-01-28
      相关资源
      最近更新 更多