在windows中使用python获取ipconfig结果

在windows中使用python获取ipconfig结果,python,windows,adapter,ethernet,mac-address,Python,Windows,Adapter,Ethernet,Mac Address,我是新来的,正在学习python。我需要帮助在windows中使用python获取网卡的正确mac地址。我尝试搜索,发现了以下内容: 如果从命令提示符下运行“ipconfig/all”,则会得到以下结果: Windows-IP-Konfiguration Hostname . . . . . . . . . . . . : DESKTOP-CIRBA63 Primäres DNS-Suffix . . . . . . . : Knotentyp . . . . . . . . . .

我是新来的,正在学习python。我需要帮助在windows中使用python获取网卡的正确mac地址。我尝试搜索,发现了以下内容:

  • 如果从命令提示符下运行“ipconfig/all”,则会得到以下结果:

    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网卡的mac地址(32-A5-2C-0B-14-D9),而不是Norton或windows tunneling创建的mac地址。 Python给了我另一个mac地址结果,如果我使用:
    “uuid.getnode()或“getmac”
    我认为最好的方法是获得
    “ipconfig/all”
    , 查看“Beschreibung”中的“Realtek”,然后获取“Physische Adrese”信息以获取我的真实mac地址。
    如何在windows上用python执行此操作?非常感谢您的帮助。请提前感谢。

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

    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=bool,
            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
    
    此函数将返回DICT列表,所需信息可从结果DICT返回:

    for intf in get_interfaces_with_mac_addresses('Realtek'):
        print intf['Name'], intf['MACAddress']
    

    下面的Python 3脚本基于Stephen Rauch one(感谢wmic实用程序指针,它非常方便)

    它仅从计算机检索IP活动接口, 处理具有多个值的字段(一个nic上有多个ip/掩码或网关),从ip/掩码创建,并输出每个nic一个dict的列表

    #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提示符导入或使用它:

    python.exe getnics.py
    
    将输出如下内容:

    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地址字段有一些疑问,例如,在VM或欺骗情况下,wmic似乎只返回一个字符串,而不是一个数组。

    您是否尝试过建议的netifaces模块?这似乎很简单。尽管您已经在寻找特定的适配器,为什么不直接硬编码mac?如果netiface有您需要的信息,它是最好的。如果您必须使用powershell和wmi,我建议您使用powershell和wmi,而不是cmd和ipconfig。@stephenauch、ipconfig.exe或wmic.exe可以通过
    subprocess.Popen从Python直接运行。不需要cmd shell;应该尽可能避免使用cmd shell,尤其是在命令基于用户输入的情况下。此外,wmic.exe还可以按原样输出可靠的XML,对于不了解PowerShell或希望避免其启动延迟的人来说,这是一个合适的选择(在Windows 10中仍然很明显,IMO——这是一个怪兽般的外壳)@eryksun,谢谢你给我的提示:wmic,我今天学到了一些东西。
    os.popen
    使用cmd shell,并且没有隐藏控制台窗口,这在GUI应用程序中很烦人。你可以改为使用
    DETACHED\u PROCESS=8;
    xml\u text=subprocess。检查输出('wmic.exe nic where“name like'reatek%\”“get-MACAddress/format:rawxml',creationflags=DETACHED\u PROCESS)
    。运行分离意味着当父应用程序是GUI应用程序时,Windows不会为wmic创建新的控制台。我添加了where子句和get字段,作为不检索所有接口的所有信息的示例。@eryksun,再次感谢。我添加了子流程调用和接口名称匹配。我省略了“just get the macAddr”,因为在我的机器上,它为“Intel”返回了多个地址。希望,如果OP返回,他可以从中得到他需要的东西。嗨,我尝试复制并粘贴上面的代码,将其保存在文件“testmac.py”中,并将其放在“testpackage”文件夹下。我创建了一个空的init.py文件并将其放在那里。然后我将整个“testpackage”文件夹复制到python安装目录“…\python\Lib\site packages”。之后,我创建了一个文件“callmodule.py”,其中包含:intfs=get_mac_addresses('Realtek')——然后我打开一个命令提示符,尝试使用:python callmodule.py调用该文件,但收到错误消息:“NameError:未定义名称'get\u mac\u addresses'。怎么了?我使用Python2.7.x。谢谢。使用所描述的文件结构,您需要从testpackage.testmac导入get\u mac\u地址
    。您还需要
    \uuuu init\uuuu.py
    而不是
    init.py
    。但更简单的方法是直接将
    get\u mac\u地址
    代码放入脚本中进行测试。在您满意之后,您可以了解如何进入包或模块。我如何将脚本输出打印到变量以在脚本中使用?感谢函数getNics()实际返回一个dict变量(请参见主体部分下的NIC)。例如,您可以键入NIC[0]['hostname']或NIC[0]['ip']