From 7a14a129c30f96b4cf53c29798765fff9cf5767c Mon Sep 17 00:00:00 2001 From: David Barroso Date: Tue, 28 Apr 2015 16:57:22 +0200 Subject: [PATCH] Adding some utils to parse information from the CLI --- utils/__init__.py | 0 utils/string_parsers.py | 54 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 utils/__init__.py create mode 100644 utils/string_parsers.py diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/utils/string_parsers.py b/utils/string_parsers.py new file mode 100644 index 0000000..5e9b140 --- /dev/null +++ b/utils/string_parsers.py @@ -0,0 +1,54 @@ +def colon_separated_string_to_dict(string): + ''' + Converts a string in the format: + + Name: Et3 + Switchport: Enabled + Administrative Mode: trunk + Operational Mode: trunk + MAC Address Learning: enabled + Access Mode VLAN: 3 (VLAN0003) + Trunking Native Mode VLAN: 1 (default) + Administrative Native VLAN tagging: disabled + Administrative private VLAN mapping: ALL + Trunking VLANs Enabled: 2-3,5-7,20-21,23,100-200 + Trunk Groups: + + into a dictionary + + ''' + dictionary = dict() + + for line in string.splitlines(): + line_data = line.split(':') + + if len(line_data) > 1: + dictionary[line_data[0].strip()] = ''.join(line_data[1:]) + elif len(line_data) == 1: + dictionary[line_data[0].strip()] = None + else: + raise Exception('Something went wrong parsing the colo separated string {}'.format(line)) + + return dictionary + + +def hyphen_range(string): + ''' + Expands a string of numbers separated by commas and hyphens into a list of integers. + For example: 2-3,5-7,20-21,23,100-200 + ''' + list_numbers = list() + temporary_list = string.split(',') + + for element in temporary_list: + sub_element = element.split('-') + + if len(sub_element) == 1: + list_numbers.append(int(sub_element[0])) + elif len(sub_element) == 2: + for x in range(int(sub_element[0]), int(sub_element[1])+1): + list_numbers.append(x) + else: + raise Exception('Something went wrong expanding the range'.format(string)) + + return list_numbers