0

I've tried hard to figure out on how to append items in one list into a new list. The data in the list is actually information from ipconfig/all. Because I wanted to separate the items in sections based on the network titles, I added the titles into another list to be used as reference. Here is my code:

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) 

Output for 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'"]..............]

The above is basically the list I'm extracting the data from.

Output for 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']

Here is the list to use as reference.

Ultimately, I want to have an output like this by separating data in all connections by the titles in leftconnections.

[[["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'"]],[[...],[...],[...],[[...],[...]]]

What I could think of, was to make this for loop (not a working code):

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

The main purpose of the code is just to separate all the details in ipconfig/all by network. So, I'm actually open to other methods because I know, my code is a little messy right now.

Thank you so much if you are willing to help me out.

Sin Han Jinn
  • 574
  • 3
  • 18
  • 1
    Check out my answer to a very similar question [Parsing Command Line Output in Windows with Python](https://stackoverflow.com/questions/58260776/parsing-command-line-output-in-windows-with-python/58264457#58264457) – GordonAitchJay Oct 07 '19 at 07:07

1 Answers1

1

In the code you posted, you're floundering around with the b' which is at the start of the representation of the line from stdout. In your current code, stdout is given to you as bytes. To make it a string, call its decode() method, or get it as a str right from the start, by calling Popen with the text=True parameter.

The main purpose of the code is just to separate all the details in ipconfig/all by network. So, I'm actually open to other methods because I know, my code is a little messy right now.

I would seriously suggest using a module/API which gives you this information directly, instead of gleaning it from ipconfig /alls output. As wjandrea suggested in a comment, try the wmic module Extracting Subnet Mask from my computer python.

Failing that, give this a go. I made some changes to code I gave in an answer to another question so it handles ipconfig /all. Mind you, it's delicate. Don't rely on it for anything serious.

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

Output:

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"
GordonAitchJay
  • 4,640
  • 1
  • 14
  • 16
  • Hey Gordon, thanks for the more detailed explanation. I was in the process of making changes from the answer you gave in the comments. I actually needed this code to store information first hand because I'll be altering the ip addresses & might need to restore them back to previous values. This method you've shown definitely works well for my case. Thank you once again for your help! – Sin Han Jinn Oct 07 '19 at 09:14
  • No worries dude. How many network adapters are you dealing with? So many that you can't just copy the output from `ipconfig /all` to a textfile, and manually restore the different values? – GordonAitchJay Oct 07 '19 at 09:43
  • Not too many, 4-6. That's possible too but I'm making a double click and run exe & would be quick. Don't wanna leave any files hanging around too. – Sin Han Jinn Oct 07 '19 at 23:41