Created
April 17, 2019 21:13
-
-
Save lazymutt/ca7dc5a4de6ba16df8a296f00e34ecde to your computer and use it in GitHub Desktop.
Converts the output of an "ipconfig /all" command to a nested dictionary.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
# ipconfig_to_dict.py ***************** | |
# | |
# converts the output of an "ipconfig /all" command | |
# to a nested dictionary. | |
# | |
# ************************************* | |
from __future__ import print_function | |
import subprocess | |
def ipconfig_to_dict(raw_command): | |
""" | |
Converts the return of a ipconfig command into a dictionary and returns results. | |
""" | |
dict_command = {} | |
raw_command = raw_command.decode("utf-8") | |
split_command = raw_command.split("\r\n") | |
split_command = [x for x in split_command if x] | |
for item in split_command: | |
split_item = item.split(" : ") | |
# print("%r" % split_item) | |
if len(split_item) == 1: | |
current_superkey = split_item[0] | |
if current_superkey.endswith(":"): | |
current_superkey = current_superkey.replace(':', '') | |
dict_command[current_superkey] = {} | |
try: | |
split_key = split_item[0].rstrip() | |
split_value = split_item[1].rstrip() | |
if ' .' in split_key: | |
temp_key = split_key.replace('.', '') | |
temp_key = temp_key.rstrip() | |
temp_key = temp_key.lstrip() | |
split_key = temp_key | |
if '","' in split_value: | |
temp_value = split_value.replace('"', '') | |
temp_value = temp_value.rsplit() | |
split_value = temp_value | |
try: | |
if dict_command[current_superkey][split_key] is not None: | |
if isinstance(dict_command[current_superkey][split_key], list): | |
dict_command[current_superkey][split_key].append(split_value) | |
else: | |
temp_value = dict_command[current_superkey][split_key] | |
dict_command[current_superkey][split_key] = [temp_value] | |
dict_command[current_superkey][split_key].append(split_value) | |
except KeyError: | |
dict_command[current_superkey][split_key] = split_value | |
except: | |
pass | |
return dict_command | |
def main(): | |
ipconfig_raw = subprocess.check_output(["ipconfig", "/all"]) | |
ipconfig_dict = ipconfig_to_dict(ipconfig_raw) | |
for key, value in ipconfig_dict.items(): | |
print(key) | |
for subkey, subitem in value.items(): | |
print("\t%s: %s" % (subkey, subitem)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment