首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在windows中使用python获取ipconfig结果

在windows中使用python获取ipconfig结果
EN

Stack Overflow用户
提问于 2017-01-02 00:15:59
回答 3查看 8K关注 0票数 2

我是新来的,刚开始学习蟒蛇。我需要帮助,以获得正确的mac地址,我的网卡在窗口使用python。我试着搜索,发现了这些:

  1. Python - Get mac地址
  2. 获取MAC地址
  3. Python中的命令输出解析
  4. 解析窗口的ipconfig/all输出

如果我从命令提示符运行"ipconfig /all“,我会得到以下内容:

代码语言:javascript
复制
Windows-IP-Konfiguration
Hostname  . . . . . . . . . . . . : DESKTOP-CIRBA63
Primäres DNS-Suffix . . . . . . . :
Knotentyp . . . . . . . . . . . . : Hybrid
IP-Routing aktiviert  . . . . . . : Nein
WINS-Proxy aktiviert  . . . . . . : Nein

Ethernet-Adapter Ethernet:
Verbindungsspezifisches DNS-Suffix:
Beschreibung. . . . . . . . . . . : Realtek PCIe FE Family Controller
Physische Adresse . . . . . . . . : 32-A5-2C-0B-14-D9
DHCP aktiviert. . . . . . . . . . : Nein
Autokonfiguration aktiviert . . . : Ja
IPv4-Adresse  . . . . . . . . . . : 192.168.142.35(Bevorzugt)
Subnetzmaske  . . . . . . . . . . : 255.255.255.0
Standardgateway . . . . . . . . . : 192.168.142.1
DNS-Server  . . . . . . . . . . . : 8.8.8.8
                                    8.8.4.4
NetBIOS über TCP/IP . . . . . . . : Deaktiviert

Ethernet-Adapter Ethernet 2:
Medienstatus. . . . . . . . . . . : Medium getrennt
Verbindungsspezifisches DNS-Suffix:
Beschreibung. . . . . . . . . . . : Norton Security Data Escort Adapter
Physische Adresse . . . . . . . . : 00-CE-35-1B-77-5A
DHCP aktiviert. . . . . . . . . . : Ja
Autokonfiguration aktiviert . . . : Ja

Tunneladapter isatap.{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}:
Medienstatus. . . . . . . . . . . : Medium getrennt
Verbindungsspezifisches DNS-Suffix:
Beschreibung. . . . . . . . . . . : Microsoft ISATAP Adapter
Physische Adresse . . . . . . . . : 00-00-00-00-00-00-00-A0
DHCP aktiviert. . . . . . . . . . : Nein
Autokonfiguration aktiviert . . . : Ja

我需要我的Realtek网卡(32-A5-2C-0B-14-D9),的mac地址,而不是诺顿或windows隧道创建的那个。如果我使用的话,Python给了我另一个mac地址的结果:"uuid.getnode() or "getmac" --我认为最好的方法是获取"ipconfig /all"的输出,查看"Beschreibung“中的"Realtek”,然后获取"Physische Adresse“信息来获取我的真实mac地址。如何在windows上的python中做到这一点?任何帮助都是非常感谢的。提前谢谢。

EN

回答 3

Stack Overflow用户

发布于 2017-01-02 02:49:24

您可以使用wmic格式检索windows接口信息,然后将XML转换为dict。从生成的dict中,您可以收集任何所需的信息:

代码语言:javascript
复制
def get_interfaces_with_mac_addresses(interface_name_substring=''):
    import subprocess
    import xml.etree.ElementTree

    cmd = 'wmic.exe nic'
    if interface_name_substring:
        cmd += ' where "name like \'%%%s%%\'" ' % interface_name_substring
    cmd += ' get /format:rawxml'

    DETACHED_PROCESS = 8
    xml_text = subprocess.check_output(cmd, creationflags=DETACHED_PROCESS)

    # convert xml text to xml structure
    xml_root = xml.etree.ElementTree.fromstring(xml_text)

    xml_types = dict(
        datetime=str,
        boolean=lambda x: x[0].upper() == 'T',
        uint16=int,
        uint32=int,
        uint64=int,
        string=str,
    )

    def xml_to_dict(xml_node):
        """ Convert the xml returned from wmic to a dict """
        dict_ = {}
        for child in xml_node:
            name = child.attrib['NAME']
            xml_type = xml_types[child.attrib['TYPE']]

            if child.tag == 'PROPERTY':
                if len(child):
                    for value in child:
                        dict_[name] = xml_type(value.text)
            elif child.tag == 'PROPERTY.ARRAY':
                if len(child):
                    assert False, "This case is not dealt with"
            else:
                assert False, "This case is not dealt with"

        return dict_

    # convert the xml into a list of dict for each interface
    interfaces = [xml_to_dict(x)
                  for x in xml_root.findall("./RESULTS/CIM/INSTANCE")]

    # get only the interfaces which have a mac address
    interfaces_with_mac = [
        intf for intf in interfaces if intf.get('MACAddress')]

    return interfaces_with_mac

此函数将返回一个dicts列表,所需的信息可以从生成的dicts返回:

代码语言:javascript
复制
for intf in get_interfaces_with_mac_addresses('Realtek'):
    print intf['Name'], intf['MACAddress']
票数 4
EN

Stack Overflow用户

发布于 2017-08-17 08:02:46

下面的python3脚本是基于编写的(谢谢wmic实用程序指针,它非常方便)

它只从计算机中检索IPactive接口,处理具有多个值的字段(多个ips/掩码或一个nic上的网关),从ip/掩码中创建IPv4Iinterface或v6 python对象,并输出每个nic具有一个dict的列表。

代码语言:javascript
复制
#python3
from subprocess import check_output
from xml.etree.ElementTree import fromstring
from ipaddress import IPv4Interface, IPv6Interface

def getNics() :

    cmd = 'wmic.exe nicconfig where "IPEnabled  = True" get ipaddress,MACAddress,IPSubnet,DNSHostName,Caption,DefaultIPGateway /format:rawxml'
    xml_text = check_output(cmd, creationflags=8)
    xml_root = fromstring(xml_text)

    nics = []
    keyslookup = {
        'DNSHostName' : 'hostname',
        'IPAddress' : 'ip',
        'IPSubnet' : '_mask',
        'Caption' : 'hardware',
        'MACAddress' : 'mac',
        'DefaultIPGateway' : 'gateway',
    }

    for nic in xml_root.findall("./RESULTS/CIM/INSTANCE") :
        # parse and store nic info
        n = {
            'hostname':'',
            'ip':[],
            '_mask':[],
            'hardware':'',
            'mac':'',
            'gateway':[],
        }
        for prop in nic :
            name = keyslookup[prop.attrib['NAME']]
            if prop.tag == 'PROPERTY':
                if len(prop):
                    for v in prop:
                        n[name] = v.text
            elif prop.tag == 'PROPERTY.ARRAY':
                for v in prop.findall("./VALUE.ARRAY/VALUE") :
                    n[name].append(v.text)
        nics.append(n)

        # creates python ipaddress objects from ips and masks
        for i in range(len(n['ip'])) :
            arg = '%s/%s'%(n['ip'][i],n['_mask'][i])
            if ':' in n['ip'][i] : n['ip'][i] = IPv6Interface(arg)
            else : n['ip'][i] = IPv4Interface(arg)
        del n['_mask']

    return nics

if __name__ == '__main__':
    nics = getNics()
    for nic in nics :
        for k,v in nic.items() :
            print('%s : %s'%(k,v))
        print()

从cmd提示符导入或使用它:

代码语言:javascript
复制
python.exe getnics.py

将输出类似以下内容:

代码语言:javascript
复制
hardware : [00000000] Intel(R) Centrino(R) Wireless-N 2230 Driver
gateway : ['192.168.0.254']
ip : [IPv4Interface('192.168.0.40/24'), IPv6Interface('fe80::7403:9e12:f7db:60c/64')]
mac : xx:xx:xx:xx:xx:xx
hostname : mixer

hardware : [00000002] Killer E2200 Gigabit Ethernet Controller
gateway : ['192.168.0.254']
ip : [IPv4Interface('192.168.0.28/24')]
mac : xx:xx:xx:xx:xx:xx
hostname : mixer

用windows10测试。我对mac adress字段有一些疑问,例如,使用VM或欺骗情况,wmic似乎只返回一个字符串,而不是一个数组。

票数 3
EN

Stack Overflow用户

发布于 2022-04-14 21:31:33

代码语言:javascript
复制
# Python 3.10.4
from getmac import get_mac_address

mac_address = get_mac_address(ip='192.168.1.20').upper()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41420165

复制
相关文章

相似问题

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