Adam Tengler | a2f260a | 2018-07-12 17:35:28 +0000 | [diff] [blame^] | 1 | from netaddr import iter_iprange |
| 2 | |
| 3 | __virtualname__ = 'netutils' |
| 4 | |
| 5 | |
| 6 | def __virtual__(): |
| 7 | return __virtualname__ |
| 8 | |
| 9 | |
| 10 | def parse_network_ranges(ranges, needed): |
| 11 | ''' |
| 12 | Takes comma seprated list of IP ranges and returns full list of IP addresses in these ranges. |
| 13 | Second argument is used to check if there is enough IP addresses to cover the required number of nodes. |
| 14 | |
| 15 | >>> parse_network_ranges("192.168.1.101-192.168.1.103,192.168.2.101-192.168.2.103") |
| 16 | ["192.168.1.101", "192.168.1.102", "192.168.1.103", "192.168.2.101", "192.168.2.102", "192.168.2.103"] |
| 17 | ''' |
| 18 | range_list = ranges.split(',') |
| 19 | ip_obj_list = [] |
| 20 | for _range in ranges.split(','): |
| 21 | ip_obj_list += list(iter_iprange(*_range.split('-'))) |
| 22 | ip_list = [str(ip) for ip in ip_obj_list] |
| 23 | if len(ip_list) < needed: |
| 24 | raise ValueError('There is not enough IP addresses in ranges: "{}". {} available, {} required.'.format(ranges, len(ip_list), needed)) |
| 25 | return ip_list |