Получить результат ipconfig с Python в Windows

Я новичок здесь и только учусь Python. Мне нужна помощь, чтобы получить правильный Mac-адрес моей сетевой карты в Windows, используя Python. Я попытался найти, и нашел это:

  1. Python - получить MAC-адрес

  2. Получение MAC-адреса

  3. Разбор выходных команд в Python

  4. Синтаксический анализ окон ipconfig /all

Если я запускаю "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

Мне нужно получить MAC-адрес моей сетевой карты Realtek (32-A5-2C-0B-14-D9), а не адрес, созданный Norton или Windows Tunnel. Python дал мне еще один результат MAC-адрес, если я использую: "uuid.getnode() or "getmac" Я думаю, что лучший способ - это получить результат "ipconfig /all", глядя на "Realtek" на "Beschreibung", а затем получить информацию "Physische Adresse", чтобы получить мой реальный mac-адрес. Как это сделать в Python на Windows? Любая помощь приветствуется. Заранее спасибо.

3 ответа

Вы можете получить информацию об интерфейсе Windows, используя wmic в формате XML, а затем преобразовать xml в 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

Эта функция вернет список диктов, нужная информация может быть возвращена из результирующих диктов:

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

Приведенный ниже скрипт python3 основан на сценарии Стивена Рауха (спасибо за указатель на утилиту wmic, он очень удобен)

он извлекает из компьютера только IP- адреса и активные интерфейсы, обрабатывает поля с несколькими значениями (несколько ips/ масок или шлюзов на одном nic), создает объекты IPv4Iinterface или v6 python из ip/mask и выводит список с одним dict на nic.

#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()

импортируйте его или используйте из командной строки:

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, например, с виртуальной машиной или подделкой, кажется, что wmic возвращает только одну строку, а не массив.

      # Python 3.10.4
from getmac import get_mac_address

mac_address = get_mac_address(ip='192.168.1.20').upper()
Другие вопросы по тегам