Created
October 9, 2012 15:13
-
-
Save fritz0705/3859439 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # coding: utf-8 | |
| class Route: | |
| def __init__(self, network): | |
| self.network = network | |
| class BGPRoute(Route): | |
| def __init__(self, network, origin="IGP", as_path=[], next_hop=None, | |
| community=[], med=0): | |
| Route.__init__(self, network) | |
| self.origin = origin | |
| self.as_path = as_path | |
| self.next_hop = next_hop | |
| self.community = community | |
| self.med = med | |
| def as_path_pairs(self): | |
| pairs = [] | |
| i = 0 | |
| while i < len(self.as_path) - 1: | |
| pair = (self.as_path[i], self.as_path[i + 1]) | |
| if pair not in pairs and pair[0] != pair[1]: | |
| pairs.append(pair) | |
| i += 1 | |
| return pairs | |
| class Parser: | |
| def __init__(self, static_route=Route, bgp_route=BGPRoute): | |
| self.static_route = static_route | |
| self.bgp_route = bgp_route | |
| pass | |
| def parse_route_body(self, network, route_body): | |
| raw_routes = [] | |
| c_route = None | |
| for key, value in map(lambda x: x.split(": "), route_body): | |
| if key == "Type": | |
| if c_route: | |
| raw_routes.append(c_route) | |
| c_route = None | |
| c_route = {} | |
| c_route[key] = value | |
| if c_route: | |
| raw_routes.append(c_route) | |
| routes = [] | |
| for route in raw_routes: | |
| if route["Type"].split(" ")[0] == "BGP": | |
| new_route = self.bgp_route( | |
| network, | |
| origin=route.get("BGP.origin"), | |
| as_path=route.get("BGP.as_path").split(" "), | |
| next_hop=route.get("BGP.next_hop"), | |
| med=route.get("BGP.med"), | |
| ) | |
| if "BGP.community" in route: | |
| new_route.community = list(map(lambda x: (x[0], x[1]), map(lambda x: x[1:-1].split(","), route.get("BGP.community", "").split(" ")))) | |
| else: | |
| new_route = self.static_route(network) | |
| routes.append(new_route) | |
| return routes | |
| def parse_routes(self, routes): | |
| network = None | |
| networks = {} | |
| for line in routes.split("\n"): | |
| if len(line) == 0: | |
| continue | |
| if line[0] == "\t": | |
| networks[network].append(line[1:]) | |
| elif line[0:8] == " " * 8: | |
| networks[network][-1] += "\n" + line.replace(" " * 8, "\t") | |
| else: | |
| network = line.split(" ")[0] | |
| networks[network] = [] | |
| routes = [] | |
| for network, route_body in networks.items(): | |
| routes += self.parse_route_body(network, route_body) | |
| return routes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment