簡體   English   中英

如何在 Python 中從 ping 中獲取 IP 地址

[英]How to Grab IP address from ping in Python

我目前使用的是 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

現在它只返回真或假,但有沒有辦法運行 ping(google.com) 並讓它返回 216.58.217.206。 我有一個服務器和 IP 列表,我需要確保 IP 地址與 FQDN 匹配。

您可以使用套接字來獲取主機的 IP。

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

不確定如何沒有人嘗試過這種方法(無論如何對於 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'

輸出截圖:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM