Python中如何从ping获取IP地址

2024-04-18 23:10:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前使用的是python2.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(谷歌)返回216.58.217.206。我有一个服务器和IP的列表,我需要确保IP地址与FQDN匹配。在


Tags: truehostifwindowsshargsneedping
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'

输出屏幕截图:

enter image description here

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

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

相关问题 更多 >