Разделять и добавлять элементы в список, используя другой список в качестве ссылки - PullRequest
0 голосов
/ 07 октября 2019

Я очень старался выяснить, как добавить элементы из одного списка в новый список. Данные в списке на самом деле информация из ipconfig / all. Поскольку я хотел разделить элементы по разделам на основе сетевых заголовков, я добавил заголовки в другой список для использования в качестве справочного материала. Вот мой код:

listofstates = []
allconnections = []
leftconnections = []
mainlist = []
commands = "ipconfig/all"
pipe = Popen(commands, shell=True, stdout=PIPE)
for line in pipe.stdout:
    listofstates.append(line.strip())
for items in listofstates:
    splittedvalues = str(items).split(':')
    if "b''" not in splittedvalues:
        splittedvalues = [s for s in splittedvalues if s]
        element = [splittedvalues[0].replace("b'", "").replace(".", "")] + splittedvalues[1:]
        cleanedelement = (re.split(r'\s{2,}',str(element[0])) + element[1:])
        cleanedelement = [s for s in cleanedelement if s]
        allconnections.append(cleanedelement)
        leftvalues = str(splittedvalues[0])
        if "." not in leftvalues:
            wordcount = len(re.findall(r'\w+', leftvalues))
            if wordcount > 2:
                newvalues = leftvalues.replace("b'", "").replace("'", "")
                leftconnections.append(newvalues)

print (allconnections)
print (leftconnections) 

Вывод для allconnections :

[["Windows IP Configuration'"], ['Host Name', " Bla Bla Bla'"], ['Primary Dns Suffix', " vitrox.local'"], ['Node Type', " Hybrid'"], ['IP Routing Enabled', " No'"], ['WINS Proxy Enabled', " No'"], ['DNS Suffix Search List', " black sheep'"], ['Ethernet adapter Ethernet', "'"], ['Media State', " Media disconnected'"], ['Connection-specific DNS Suffix', "'"], ['Description', " Intel(R) Ethernet Connection I-LM'"], ['Physical Address', " 00-B5-00-1E-F4-5G'"], ['DHCP Enabled', " Yes'"], ['Autoconfiguration Enabled', " Yes'"], ['Ethernet adapter Local Area Network 5', "'"], ['Connection-specific DNS Suffix', "'"], ['Description', " VirtualBox Host-Only Ethernet Adapter'"], ['Physical Address', " 0A-00-50-00-11-0B'"], ['DHCP Enabled', " No'"], ['Autoconfiguration Enabled', " Yes'"], ['Link-local IPv6 Address', ' fe69', 'aa2b', '4b5d', '2345', "5f07%08(Preferred)'"], ['IPv4 Address', " 10.0.0.05(Preferred)'"], ['Subnet Mask', " 255.255.255.0'"], ['Default Gateway', "'"], ['DHCPv6 IAID', " 539312188'"], ['DHCPv6 Client DUID', " 00-04-11-01-25-75-14-A4-54-B1-03-1E-F4-5E'"], ['DNS Servers', ' fec0', '0', '0', 'ffff', "1%1'"], ['fec0', '0', '0', 'ffff', "2%1'"], ['fec0', '0', '0', 'ffff', "3%1'"], ['NetBIOS over Tcpip', " Enabled'"]..............]

Выше приведен список, из которого я извлекаю данные.

Вывод для leftconnections :

['Windows IP Configuration', 'Ethernet adapter Ethernet', 'Ethernet adapter Local Area Network 5', 'Wireless LAN adapter Local Area Connection* 3', 'Wireless LAN adapter Local Area Connection* 12', 'Wireless LAN adapter Wi-Fi', 'Ethernet adapter Bluetooth Network Connection']

Вот список для использования в качестве reference .

Ultimate Я хочу получить такой вывод, разделив данные во всех соединениях по заголовкам в левом соединении.

[[["Windows IP Configuration'"], ['Host Name', " Bla Bla Bla'"], ['Primary Dns Suffix', " vitrox.local'"], ['Node Type', " Hybrid'"], ['IP Routing Enabled', " No'"], ['WINS Proxy Enabled', " No'"], ['DNS Suffix Search List', " black sheep'"]],[['Ethernet adapter Ethernet', "'"], ['Media State', " Media disconnected'"], ['Connection-specific DNS Suffix', "'"], ['Description', " Intel(R) Ethernet Connection I-LM'"], ['Physical Address', " 00-B5-00-1E-F4-5G'"], ['DHCP Enabled', " Yes'"], ['Autoconfiguration Enabled', " Yes'"], ['Ethernet adapter Local Area Network 5', "'"], ['Connection-specific DNS Suffix', "'"], ['Description', " VirtualBox Host-Only Ethernet Adapter'"], ['Physical Address', " 0A-00-50-00-11-0B'"], ['DHCP Enabled', " No'"], ['Autoconfiguration Enabled', " Yes'"], ['Link-local IPv6 Address', ' fe69', 'aa2b', '4b5d', '2345', "5f07%08(Preferred)'"], ['IPv4 Address', " 10.0.0.05(Preferred)'"], ['Subnet Mask', " 255.255.255.0'"], ['Default Gateway', "'"], ['DHCPv6 IAID', " 539312188'"], ['DHCPv6 Client DUID', " 00-04-11-01-25-75-14-A4-54-B1-03-1E-F4-5E'"], ['DNS Servers', ' fec0', '0', '0', 'ffff', "1%1'"], ['fec0', '0', '0', 'ffff', "2%1'"], ['fec0', '0', '0', 'ffff', "3%1'"], ['NetBIOS over Tcpip', " Enabled'"]],[[...],[...],[...],[[...],[...]]]

Что я мог придумать, так это сделать цикл for (не рабочий код):

for connection in leftconnections:
   if (*connection is the first*)
       mainlist.append(leftconnections) *until second connection is found*

Основное назначение кодапросто разделить все детали в ipconfig / all по сети. Итак, я на самом деле открыт для других методов, потому что я знаю, что мой код сейчас немного грязный

Большое спасибо, если вы готовы мне помочь.

1 Ответ

1 голос
/ 07 октября 2019

В коде, который вы разместили, вы барахтаетесь с b', который находится в начале представления строки от stdout. В вашем текущем коде stdout дается вам как bytes. Чтобы сделать его строкой, вызовите его метод decode() или получите его как str с самого начала, вызвав Popen с параметром text=True.

Основная целькода просто для разделения всех деталей в ipconfig / all по сети. Итак, я на самом деле открыт для других методов, потому что я знаю, что мой код сейчас немного грязный

Я бы серьезно предложил использовать модуль / API, который дает вам эту информацию напрямую, а не собирать ее из вывода ipconfig /all s. Как wjandrea , предложенный в комментарии , попробуйте wmic module Извлечение маски подсети из моего компьютерного питона .

В противном случае, дайте этотому назад. Я внес некоторые изменения в код, который я дал в ответе на другой вопрос, чтобы он обрабатывал ipconfig /all. Имейте в виду, это деликатно. Не надейтесь на что-либо серьезное.

import subprocess

adapters = {}
current_adapter = None # Used to ignore the stuff between "Windows IP Configuration" and the first adapter
output = subprocess.check_output("ipconfig /all").decode()


for line in output.splitlines():
    # Determine if there's one of these type of adapters in the line
    for term in ["Ethernet adapter", "PPP adapter", 
                 "Tunnel adapter", "Wireless LAN adapter"]:
        if line.startswith(term) and ":" in line:
            adapter_name = line[len(term):-1]
            adapters[adapter_name] = {}
            current_adapter = adapters[adapter_name]
            break # Goes to the next line in the output
    else: # No break - the current line is not the start of a new adapter
        if current_adapter != None:
            split_at = " : "
            if split_at in line:
                # We assume this line contains a key/value pair
                key, value = line.split(split_at)
                key = key.replace(" .", "").strip()
                current_adapter[key] = value
                continue

            # At this point, the line is either a blank line, or an additional value
            value = line.strip()
            if value != "":
                # It's assumed to be an additional value
                # If it's the first additional value, make a list with the
                # original value, then append the value from this line
                if not isinstance(current_adapter[key], list):
                    current_adapter[key] = [current_adapter[key]]

                current_adapter[key].append(value)


for adapter_name, adapter in adapters.items():
    print(f"{adapter_name}:")
    for key, value in adapter.items():
        print(f'    "{key}" = "{value}"')
    print()

Вывод:

Ethernet:
    "Connection-specific DNS Suffix" = ""
    "Description" = "Realtek PCIe GBE Family Controller"
    "Physical Address." = "1C-1C-1C-1C-1C-1C"
    "DHCP Enabled." = "Yes"
    "Autoconfiguration Enabled" = "Yes"
    "Link-local IPv6 Address" = "fe80::fe80:fe80:fe80:fe80%8(Preferred)"
    "IPv4 Address." = "192.168.255.255(Preferred)"
    "Subnet Mask" = "255.255.255.0"
    "Lease Obtained." = "Wednesday, 10 October 2019 10:10:10 PM"
    "Lease Expires" = "Wednesday, 10 October 2019 10:10:10 PM"
    "Default Gateway" = "192.168.255.255"
    "DHCP Server" = "192.168.255.255"
    "DHCPv6 IAID" = "50505050"
    "DHCPv6 Client DUID." = "00-01-01-01-01-01-01-01-01-01-01-01-01-01"
    "DNS Servers" = "['192.168.255.255', '0.0.0.0']"
    "NetBIOS over Tcpip." = "Enabled"

VMware Network Adapter VMnet1:
    "Connection-specific DNS Suffix" = ""
    "Description" = "VMware Virtual Ethernet Adapter for VMnet1"
    "Physical Address." = "00-00-00-00-00-00"
    "DHCP Enabled." = "Yes"
    "Autoconfiguration Enabled" = "Yes"
    "Link-local IPv6 Address" = "fe80::fe80:fe80:fe80:fe8%19(Preferred)"
    "IPv4 Address." = "192.168.255.255(Preferred)"
    "Subnet Mask" = "255.255.255.255"
    "Lease Obtained." = "Wednesday, 10 October 2019 10:10:10 PM"
    "Lease Expires" = "Wednesday, 10 October 2019 10:10:10 PM"
    "Default Gateway" = ""
    "DHCP Server" = "192.168.255.255"
    "DHCPv6 IAID" = "484848480"
    "DHCPv6 Client DUID." = "00-01-00-01-01-01-01-01-01-01-01-01-01-01"
    "DNS Servers" = "['fec0:0:0:ffff::1%1', 'fec0:0:0:ffff::2%1', 'fec0:0:0:ffff::3%1']"
    "NetBIOS over Tcpip." = "Enabled"

VMware Network Adapter VMnet8:
    "Connection-specific DNS Suffix" = ""
    "Description" = "VMware Virtual Ethernet Adapter for VMnet8"
    "Physical Address." = "00-00-00-00-00-00"
    "DHCP Enabled." = "Yes"
    "Autoconfiguration Enabled" = "Yes"
    "Link-local IPv6 Address" = "fe80::fe80:fe80:fe80:fe8%10(Preferred)"
    "IPv4 Address." = "192.168.255.255(Preferred)"
    "Subnet Mask" = "255.255.255.255"
    "Lease Obtained." = "Wednesday, 10 October 2019 10:10:10 PM"
    "Lease Expires" = "Monday, 10 October 2019 10:10:10 PM"
    "Default Gateway" = ""
    "DHCP Server" = "192.168.255.255"
    "DHCPv6 IAID" = "484848480"
    "DHCPv6 Client DUID." = "00-01-00-01-01-01-01-01-01-01-01-01-01-01"
    "DNS Servers" = "['fec0:0:0:ffff::1%1', 'fec0:0:0:ffff::2%1', 'fec0:0:0:ffff::3%1']"
    "Primary WINS Server" = "192.168.255.255"
    "NetBIOS over Tcpip." = "Enabled"
...