首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python中从ping中获取IP地址

问如何在Python中从ping中获取IP地址
EN

Stack Overflow用户
提问于 2017-09-29 20:00:40
回答 2查看 3.5K关注 0票数 0

我目前正在使用python2.7,并将需要平窗口和linux。

我想要创建一个函数,它将从python脚本中的ping返回IP地址。我现在有这个功能

代码语言:javascript
复制
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匹配。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-29 20:21:58

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

代码语言:javascript
复制
import socket
print(socket.gethostbyname('www.example.com'))
票数 3
EN

Stack Overflow用户

发布于 2018-06-08 13:19:35

不知道还没有人尝试过这种方法(不管怎么说)!

使用W32_PingStatus的WMI查询

使用这种方法,我们返回一个充满好东西的对象。

代码语言:javascript
复制
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'

产出截图:

​

​

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46496141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档