def execute_cli(self): r = [] try: v = self.cli("show lldp remote-device | begin LocalPort") except self.CLISyntaxError: raise self.NotSupportedError() if v: for match in self.rx_lldp.finditer(v): local_port = match.group("local_port") remote_chassis_id = match.group("remote_id") remote_chassis_id_subtype = 4 remote_port = match.group("remote_port") rn = match.group("remote_n") remote_port_subtype = 5 if self.rx_mac.match(remote_port): remote_port = MACAddressParameter().clean(remote_port) remote_port_subtype = 3 elif is_ipv4(remote_port): remote_port_subtype = 4 elif is_int(remote_port): remote_port_subtype = 7 if self.rx_mac.match(remote_chassis_id): remote_chassis_id = remote_chassis_id.replace(" ", "-") remote_chassis_id = MACAddressParameter().clean(remote_chassis_id) remote_chassis_id_subtype = 3 n = { "remote_port": remote_port, "remote_port_subtype": remote_port_subtype, "remote_chassis_id": remote_chassis_id, "remote_chassis_id_subtype": remote_chassis_id_subtype, "remote_system_name": rn, } i = {"local_interface": local_port, "neighbors": [n]} r += [i] return r
def execute_cli(self, interface=None): r = [] if self.is_platform_4626: try: cmd = "show interface status | include line protocol is|alias|address is" buf = self.cli(cmd).replace("\n ", " ") except Exception: cmd = "show interface status" buf = self.cli(cmd, cached=True).replace("\n ", " ") for l in buf.splitlines(): match = self.rx_interface_status.match(l) if match: r += [{ "interface": match.group("interface"), "status": match.group("status") == "up", "mac": MACAddressParameter().clean(match.group("mac")), "snmp_ifindex": match.group("ifindex"), }] mdescr = self.rx_interface_descr.match(l) if mdescr: r[-1]["description"] = mdescr.group("descr") else: cmd = "show interface status" buf = self.cli(cmd, cached=True).lstrip("\n\n") for l in buf.split("\n\n"): match = self.rx_interface_status_3526.search(l + "\n") if match: descr = "" interface = match.group("interface") if interface.startswith("VLAN"): linestatus = "up" else: if match.group("block"): block = match.group("block") submatch = self.rx_interface_intstatus_3526.search( block) if submatch: descr = submatch.group("descr") linestatus = "down" submatch = self.rx_interface_linestatus_3526.search( block) if submatch: linestatus = submatch.group( "linestatus").lower() r += [{ "interface": interface, "mac": MACAddressParameter().clean(match.group("mac")), "status": linestatus.lower() == "up", }] if descr: r[-1]["description"] = descr return r
def execute_cli(self): r = [] try: v = self.cli("show lldp neighbors") # This is strange behavior, but it helps us v = self.blank_line.sub("", v) except self.CLISyntaxError: raise self.NotSupportedError() for i in parse_table( v, allow_wrap=True, line_wrapper=None, row_wrapper=lambda x: x.strip(), footer="\r\n\r\n", ): chassis_id = i[1] if is_ipv4(chassis_id) or is_ipv6(chassis_id): chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_NETWORK_ADDRESS else: try: MACAddressParameter().clean(chassis_id) chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_MAC except ValueError: chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_LOCAL port_id = i[2] if is_ipv4(port_id) or is_ipv6(port_id): port_id_subtype = LLDP_PORT_SUBTYPE_NETWORK_ADDRESS else: try: MACAddressParameter().clean(port_id) port_id_subtype = LLDP_PORT_SUBTYPE_MAC except ValueError: port_id_subtype = LLDP_PORT_SUBTYPE_LOCAL caps = lldp_caps_to_bits( i[4].split(","), { "o": LLDP_CAP_OTHER, "p": LLDP_CAP_REPEATER, "b": LLDP_CAP_BRIDGE, "w": LLDP_CAP_WLAN_ACCESS_POINT, "r": LLDP_CAP_ROUTER, "t": LLDP_CAP_TELEPHONE, "c": LLDP_CAP_DOCSIS_CABLE_DEVICE, "s": LLDP_CAP_STATION_ONLY, }, ) neighbor = { "remote_chassis_id": chassis_id, "remote_chassis_id_subtype": chassis_id_subtype, "remote_port": port_id, "remote_port_subtype": port_id_subtype, "remote_capabilities": caps, } if i[3]: neighbor["remote_system_name"] = i[3] r += [{"local_interface": i[0], "neighbors": [neighbor]}] return r
def execute(self): r = [] data = [] try: v = self.cli("show lldp remote-device all") except self.CLISyntaxError: raise self.NotSupportedError() v = v.replace("\n\n", "\n") for l in parse_table(v, allow_extend=True): if not l[0]: data[-1] = [s[0] + s[1] for s in zip(data[-1], l)] continue data += [l] for d in data: chassis_id = d[2] if is_ipv4(chassis_id) or is_ipv6(chassis_id): chassis_id_subtype = 5 else: try: MACAddressParameter().clean(chassis_id) chassis_id_subtype = 4 except ValueError: chassis_id_subtype = 7 port_id = d[3] if is_ipv4(port_id) or is_ipv6(port_id): port_id_subtype = 4 else: try: MACAddressParameter().clean(port_id) port_id_subtype = 3 except ValueError: port_id_subtype = 7 # caps = sum([self.CAPS[s.strip()] for s in d[4].split(",")]) caps = 0 if not chassis_id: continue neighbor = { "remote_chassis_id": chassis_id, "remote_chassis_id_subtype": chassis_id_subtype, "remote_port": port_id, "remote_port_subtype": port_id_subtype, "remote_capabilities": caps, } """ if match.group("system_name"): neighbor["remote_system_name"] = match.group("system_name") """ neighbor["remote_system_name"] = d[4] r += [{ # "local_interface": match.group("port"), "local_interface": d[0], "neighbors": [neighbor], }] return r
def execute(self): r = [] try: v = self.cli("show lldp neighbors") # This is strange behavior, but it helps us v = self.blank_line.sub("", v) except self.CLISyntaxError: raise self.NotSupportedError() t = parse_table(v, allow_wrap=True, allow_extend=True) for i in t: chassis_id = i[1] if is_ipv4(chassis_id) or is_ipv6(chassis_id): chassis_id_subtype = 5 else: try: MACAddressParameter().clean(chassis_id) chassis_id_subtype = 4 except ValueError: chassis_id_subtype = 7 port_id = i[2] if is_ipv4(port_id) or is_ipv6(port_id): port_id_subtype = 4 else: try: MACAddressParameter().clean(port_id) port_id_subtype = 3 except ValueError: port_id_subtype = 7 caps = 0 for c in i[4].split(","): c = c.strip() if c: caps |= { "O": 1, "P": 2, "B": 4, "W": 8, "R": 16, "T": 32, "C": 64, "S": 128 }[c] neighbor = { "remote_chassis_id": chassis_id, "remote_chassis_id_subtype": chassis_id_subtype, "remote_port": port_id, "remote_port_subtype": port_id_subtype, "remote_capabilities": caps } if i[3]: neighbor["remote_system_name"] = i[3] r += [{ "local_interface": i[0], "neighbors": [neighbor] }] return r
def execute_snmp(self, interface=None): # Get interface status r = [] # IF-MIB::ifName, IF-MIB::ifOperStatus, IF-MIB::ifAdminStatus, IF-MIB::ifPhysAddress for i, n, s, d, m in self.join_four_tables( self.snmp, "1.3.6.1.2.1.2.2.1.2", "1.3.6.1.2.1.2.2.1.8", "1.3.6.1.2.1.2.2.1.7", "1.3.6.1.2.1.2.2.1.6", bulk=True, ): match = self.rx_snmp_name_eth.search(n) if match: n = "Port " + match.group("port") if n.startswith("CpuPort"): continue r += [ { "snmp_ifindex": i, "interface": n, "status": int(s) == 1, "mac": MACAddressParameter().clean(m), } ] # ifOperStatus up(1) return r
def poll_worker(self, community, oid, timeout, version): while True: a = yield self.queue.get() if a: for c in community: t0 = perf_counter() try: r = yield snmp_get( address=a, oids=oid, community=c, version=version, timeout=timeout ) s = "OK" dt = perf_counter() - t0 mc = c break except SNMPError as e: s = "FAIL" r = str(e) dt = perf_counter() - t0 mc = "" except Exception as e: s = "EXCEPTION" r = str(e) dt = perf_counter() - t0 mc = "" break if self.convert: try: r = MACAddressParameter().clean(r) except ValueError: pass self.stdout.write("%s,%s,%s,%s,%r\n" % (a, s, dt, mc, r)) self.queue.task_done() if not a: break
def api_list(self, request): q = dict((str(k), v[0] if len(v) == 1 else v) for k, v in request.GET.lists()) # find mac request select max(ts), managed_object, interface, vlan from mac # where like(MACNumToString(mac), 'A0:AB:1B%') group by managed_object, interface, vlan; query = q.get("__query") start = q.get("__start") limit = q.get("__limit") # page = q.get("__page") out = [] if not query: return self.response(out, status=self.OK) try: mac = int(MAC(MACAddressParameter(accept_bin=False).clean(query))) out = self.api_macdb({"mac": mac}, limit=limit, offset=start) except ValueError: if self.mac_search_re.match(query): out = self.api_macdb({"mac__like": "%s%%" % str(query.upper())}, limit=limit, offset=start) elif self.mac_search_re_inv.match(query): out = self.api_macdb({"mac__like": "%%%s" % str(query.upper())}, limit=limit, offset=start) else: # Try MO search # @todo ManagedObject search self.logger.debug("MACDB ManagedObject search") mo_q = ManagedObject.get_search_Q(query) if not mo_q: mo_q = d_Q(name__contains=query) mos = [mo.bi_id for mo in ManagedObject.objects.filter(mo_q)[:2]] if mos: out = self.api_macdb({"managed_object__in": mos}, limit=limit, offset=start) # out = self.api_get_maclog(request, mac) return self.response(out, status=self.OK)
def execute(self, mac=None): r = [] if self.has_snmp(): try: for v in self.snmp.getnext( "1.3.6.1.4.1.25053.1.4.2.1.1.2.2.1.5", cached=True): cpename = v[1] cpeid = v[0][len("1.3.6.1.4.1.25053.1.2.2.4.1.1.1.1.5") + 1:] s = str( self.snmp.get( "1.3.6.1.4.1.25053.1.4.2.1.1.2.2.1.1.%s" % cpeid, cached=True)) mac = MACAddressParameter().clean(s) # convert mac # print "%s\n" % mac key = ".".join( str(int(x, 16)) for x in mac.split(":")) # convert mac - > bytes # print "%s\n" % key status = self.snmp.get( "1.3.6.1.4.1.25053.1.4.2.1.1.2.2.1.16.6.%s" % key, cached=True) ip = self.snmp.get( "1.3.6.1.4.1.25053.1.4.2.1.1.2.2.1.10.%s" % cpeid, cached=True) location = self.snmp.get( "1.3.6.1.4.1.25053.1.4.2.1.1.2.2.1.19.6.%s" % cpeid, cached=True) description = self.snmp.get( "1.3.6.1.4.1.25053.1.4.2.1.1.2.2.1.22.6.%s" % key, cached=True) sn = self.snmp.get( "1.3.6.1.4.1.25053.1.4.2.1.1.2.2.1.9.6.%s" % key, cached=True) model = self.snmp.get( "1.3.6.1.4.1.25053.1.4.2.1.1.2.2.1.8.6.%s" % key, cached=True) version = self.snmp.get( "1.3.6.1.4.1.25053.1.4.2.1.1.2.2.1.7.6.%s" % key, cached=True) r.append({ "vendor": "Ruckus", "model": model, "version": version, "mac": mac, "status": self.type_map[str(status)], "id": cpeid, "global_id": mac, "type": "ap", "name": cpename, "ip": ip, "serial": sn, "description": description, "location": location }) # print ("%s\n" % r) return r except self.snmp.TimeOutError: pass
def execute(self): interfaces = [] # Try SNMP first if self.has_snmp(): try: for v in self.snmp.getnext("1.3.6.1.2.1.2.2.1.1", cached=True): i = v[1] name = self.snmp.get("1.3.6.1.2.1.2.2.1.2." + str(i)) if name.lower().startswith("line"): continue iftype = self.get_interface_type(name) if not name: self.logger.info( "Ignoring unknown interface type: '%s", iftype) continue s = self.snmp.get("1.3.6.1.2.1.2.2.1.6." + str(i)) if s: mac = MACAddressParameter().clean(s) astat = self.snmp.get("1.3.6.1.2.1.2.2.1.7." + str(i)) if astat == 1: a_stat = True else: a_stat = False ostat = self.snmp.get("1.3.6.1.2.1.2.2.1.8." + str(i)) if ostat == 1: o_stat = True else: o_stat = False # print repr("%s\n" % admin_status) interfaces += [{ "type": iftype, "name": name.replace("softwareLoopback", "lo"), "mac": mac, "admin_status": a_stat, "oper_status": o_stat, "ifindex": i, "subinterfaces": [{ "name": name.replace("softwareLoopback", "lo"), "admin_status": a_stat, "oper_status": o_stat, "mac": mac, "ifindex": i, "enabled_afi": ["BRIDGE"] }] }] return [{"interfaces": interfaces}] except self.snmp.TimeOutError: pass
def execute_snmp(self): macs = [] for oid, v in self.snmp.getnext(mib["IF-MIB::ifPhysAddress"]): mac = MACAddressParameter().clean(v) if mac == "00:00:00:00:00:00" or mac in macs: continue macs += [mac] macs.sort() return [{ "first_chassis_mac": f, "last_chassis_mac": t } for f, t in self.macs_to_ranges(macs)]
def execute(self): interfaces = [] mac = [] # Try SNMP first if self.has_snmp(): try: for v in self.snmp.getnext("1.3.6.1.2.1.2.2.1.1", cached=True): i = v[1] name = self.snmp.get(mib["IF-MIB::ifDescr", i]) iftype = self.get_interface_type(name) if not name: self.logger.info( "Ignoring unknown interface type: '%s", iftype) continue s = self.snmp.get(mib["IF-MIB::ifPhysAddress", i]) if s: mac = MACAddressParameter().clean(s) astat = self.snmp.get(mib["IF-MIB::ifAdminStatus", i]) if astat == 1: a_stat = True else: a_stat = False ostat = self.snmp.get(mib["IF-MIB::ifOperStatus", i]) if ostat == 1: o_stat = True else: o_stat = False # print repr("%s\n" % admin_status) interfaces += [{ "type": iftype, "name": name, "mac": mac, "admin_status": a_stat, "oper_status": o_stat, "ifindex": i, "subinterfaces": [{ "name": name, "admin_status": a_stat, "oper_status": o_stat, "mac": mac, "ifindex": i, "enabled_afi": ["BRIDGE"], }], }] return [{"interfaces": interfaces}] except self.snmp.TimeOutError: pass
def execute_snmp(self): interfaces = [] for oid, i in self.snmp.getnext("1.3.6.1.2.1.2.2.1.1", cached=True): name = self.snmp.get(mib["IF-MIB::ifDescr", i]) if name.lower().startswith("line"): continue iftype = self.get_interface_type(name) if not name: self.logger.info("Ignoring unknown interface type: '%s", iftype) continue s = self.snmp.get(mib["IF-MIB::ifPhysAddress", i]) if s: mac = MACAddressParameter().clean(s) astat = self.snmp.get(mib["IF-MIB::ifAdminStatus", i]) if astat == 1: a_stat = True else: a_stat = False ostat = self.snmp.get(mib["IF-MIB::ifOperStatus", i]) if ostat == 1: o_stat = True else: o_stat = False interfaces += [{ "type": iftype, "name": name.replace("softwareLoopback", "lo"), "mac": mac, "admin_status": a_stat, "oper_status": o_stat, "ifindex": i, "subinterfaces": [{ "name": name.replace("softwareLoopback", "lo"), "admin_status": a_stat, "oper_status": o_stat, "mac": mac, "ifindex": i, "enabled_afi": ["BRIDGE"], }], }] return [{"interfaces": interfaces}]
def execute(self, interface=None): r = [] v = self.cli("show network") ip = self.rx_ip.findall(v) mac = self.rx_mac.findall(v) gw = self.rx_ip_gw.findall(v) gw_vlan = self.rx_vlan_gw.findall(v) try: macs = parse_table(self.cli("show mac-addr-table vlan 1")) try: mac_gw = MACAddressParameter().clean(macs[0][0]) except (ValueError, IndexError): macs = parse_table( self.cli("show mac-addr-table vlan %s" % gw_vlan[0])) if len(macs[0]) == 3: # Only mac, iface, type mac_gw = MACAddressParameter().clean( [m[0] for m in macs if m[2] == "Learned"][0]) else: mac_gw = MACAddressParameter().clean( [m[0] for m in macs if m[3] == "Learned"][0]) except self.CLISyntaxError: macs = parse_table(self.cli("show mac-addr-table")) f_mac_gw = [m[0] for m in macs if m[2] == "1"] if not f_mac_gw: f_mac_gw = [ m[0] for m in macs if m[2] == gw_vlan[0] and m[3] == "Learned" ] mac_gw = f_mac_gw[0] if mac_gw: r += [{"ip": gw[0], "mac": mac_gw}] r += [{"ip": ip[0], "mac": mac[0]}] return r
def save(self, *args, **kwargs): if not hasattr(self, "_changed_fields") or "name" in self._changed_fields: self.name = self.managed_object.get_profile( ).convert_interface_name(self.name) if (not hasattr(self, "_changed_fields") or "mac" in self._changed_fields) and self.mac: self.mac = MACAddressParameter().clean(self.mac) try: super().save(*args, **kwargs) except Exception as e: raise ValueError("%s: %s" % (e.__doc__, e.message)) if not hasattr(self, "_changed_fields") or "service" in self._changed_fields: ServiceSummary.refresh_object(self.managed_object)
def execute(self, interface=None): r = [] if self.has_snmp(): try: # Get interface status # IF-MIB::ifName, IF-MIB::ifOperStatus, IF-MIB::ifAlias, IF-MIB::ifPhysAddress for i, n, s, d, m in self.join_four_tables( self.snmp, "1.3.6.1.2.1.2.2.1.2", "1.3.6.1.2.1.2.2.1.8", "1.3.6.1.2.1.31.1.1.1.18", "1.3.6.1.2.1.2.2.1.6", ): match = self.rx_snmp_name_eth.search(n) if i >= 1000000: continue if match: n = match.group("port") # print " !!! PORT -- %s " % n macaddr = "" if m: macaddr = MACAddressParameter().clean(m) r += [{ "snmp_ifindex": i, "interface": n, "status": int(s) == 1, "description": d, "mac": macaddr, }] # ifOperStatus up(1) return r except self.snmp.TimeOutError: pass else: # Fallback to CLI v = self.cli("show ports description") for match in self.rx_port.finditer(v): port = match.group("port") c = self.cli("show ports %s information\n\x1B" % port) match1 = self.rx_port_status.search(c) r += [{ "interface": port, "status": match1.group("state") == "active", "description": match.group("descr").strip(), }] return r
def execute_snmp(self, interface=None): # Get interface status r = [] # IF-MIB::ifName, IF-MIB::ifOperStatus for i, a, n, s, m in self.join_four_tables(self.snmp, "1.3.6.1.2.1.2.2.1.7", "1.3.6.1.2.1.31.1.1.1.1", "1.3.6.1.2.1.2.2.1.8", "1.3.6.1.2.1.2.2.1.6"): # ifOperStatus up(1) mac = MACAddressParameter().clean(m) if m else None r += [{ "snmp_ifindex": i, "interface": n, "status": int(s) == 1, "mac": mac }] return r
def execute_snmp(self, interface=None): # Get interface status r = [] for i, n, s, d, m in self.snmp.join( [ mib["IF-MIB::ifDescr"], mib["IF-MIB::ifOperStatus"], mib["IF-MIB::ifAlias"], mib["IF-MIB::ifPhysAddress"], ], join="left", ): match = self.rx_snmp_name_eth.search(n) if match: if match.group("unit") == "0": unit = "1" n = "Eth " + unit + "/" + match.group("port") else: n = "Eth " + match.group("unit") + "/" + match.group( "port") if n.startswith("Trunk ID"): n = "Trunk " + n.replace("Trunk ID ", "").lstrip("0") if n.startswith("Trunk Port ID"): n = "Trunk " + n.replace("Trunk Port ID ", "").lstrip("0") if n.startswith("Trunk Member"): n = "Eth 1/" + str(i) if n.startswith("VLAN ID"): n = "VLAN " + n.replace("VLAN ID ", "").lstrip("0") if n.startswith("VLAN interface"): n = "VLAN " + n.replace("VLAN interface ID ", "").lstrip("0") if n.startswith("Console"): continue if n.startswith("Loopback"): continue r += [{ "snmp_ifindex": i, "interface": n, "status": int(s) == 1, "description": d, "mac": MACAddressParameter().clean(m), }] return r
def execute(self, **kwargs): r = [] try: v = self.cli("display efm all") except self.CLISyntaxError: raise self.NotSupportedError oams = re.findall(self.oam_splitter, v) if not oams: return [] for l in oams: match = self.rx_line.match(l) if match: iface = match.group("interface").strip() mac = match.group("mac") try: mac = MACAddressParameter().clean(mac) except Exception: continue r += [{"interface": iface, "remote_mac": mac, "caps": ["L"]}] return r
def get_neighbor_by_local(self, local): """ Try to find neighbor using arbitrary data """ # Check IPv4 if is_ipv4(local): n = self.get_neighbor_by_ip(local) if n: return n else: # Check MAC try: mac = MACAddressParameter().clean(local) n = self.get_neighbor_by_mac(mac) if n: return n except InterfaceTypeError: pass # Fallback to hostname return self.get_neighbor_by_hostname(local)
def execute_cli(self, **kwargs): r = [] # Fallback to CLI for lldp in self.cli("show lldp neighbors interface").split("\n\n"): match = self.rx_detail.search(lldp) if match: i = { "local_interface": match.group("local_if"), "neighbors": [] } n = {"remote_chassis_id_subtype": match.group("rem_cid_type")} n["remote_port_subtype"] = { "Interface alias": LLDP_PORT_SUBTYPE_ALIAS, # "Port component": 2, "MAC address": LLDP_PORT_SUBTYPE_MAC, "Interface": LLDP_PORT_SUBTYPE_NAME, "Local": LLDP_PORT_SUBTYPE_LOCAL, }[match.group("p_type")] if n["remote_port_subtype"] == LLDP_PORT_SUBTYPE_MAC: remote_port = MACAddressParameter().clean( match.group("port_id")) elif n["remote_port_subtype"] == LLDP_PORT_SUBTYPE_LOCAL: p_id = match.group("port_id") try: remote_port = IntParameter().clean(p_id) except InterfaceTypeError: remote_port = p_id else: remote_port = match.group("port_id") n["remote_chassis_id"] = match.group("id") n["remote_port"] = str(remote_port) # Get capability cap = 0 n["remote_capabilities"] = cap i["neighbors"] += [n] r += [i] return r
def execute_cli(self): r = [] # Fallback to CLI lldp = self.cli("show lldp neighbors") for link in parse_table( lldp, allow_wrap=True, line_wrapper=None, row_wrapper=lambda x: x.strip() ): local_interface = link[0] remote_chassis_id = link[1] remote_port = link[2] remote_system_name = link[3] # Build neighbor data # Get capability cap = lldp_caps_to_bits( link[4].strip().split(","), { "O": LLDP_CAP_OTHER, "r": LLDP_CAP_REPEATER, "B": LLDP_CAP_BRIDGE, "W": LLDP_CAP_WLAN_ACCESS_POINT, "R": LLDP_CAP_ROUTER, "T": LLDP_CAP_TELEPHONE, "D": LLDP_CAP_DOCSIS_CABLE_DEVICE, "S": LLDP_CAP_STATION_ONLY, # S-VLAN "C": 256, # C-VLAN "H": 512, # Host "TP": 1024, # Two Ports MAC Relay }, ) if is_ipv4(remote_chassis_id) or is_ipv6(remote_chassis_id): remote_chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_NETWORK_ADDRESS elif is_mac(remote_chassis_id): remote_chassis_id = MACAddressParameter().clean(remote_chassis_id) remote_chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_MAC else: remote_chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_LOCAL # Get remote port subtype remote_port_subtype = LLDP_PORT_SUBTYPE_ALIAS if is_ipv4(remote_port): # Actually networkAddress(4) remote_port_subtype = LLDP_PORT_SUBTYPE_NETWORK_ADDRESS elif is_mac(remote_port): # Actually macAddress(3) # Convert MAC to common form remote_port = MACAddressParameter().clean(remote_port) remote_port_subtype = LLDP_PORT_SUBTYPE_MAC elif is_int(remote_port): # Actually local(7) remote_port_subtype = LLDP_PORT_SUBTYPE_LOCAL i = {"local_interface": local_interface, "neighbors": []} n = { "remote_chassis_id": remote_chassis_id, "remote_chassis_id_subtype": remote_chassis_id_subtype, "remote_port": remote_port, "remote_port_subtype": remote_port_subtype, "remote_capabilities": cap, } if remote_system_name: n["remote_system_name"] = remote_system_name # # XXX: Dirty hack for older firmware. Switch rebooted. # if remote_chassis_id_subtype != LLDP_CHASSIS_SUBTYPE_LOCAL: i["neighbors"] = [n] r += [i] continue try: c = self.cli("show lldp neighbors %s" % local_interface) match = self.rx_detail.search(c) if match: remote_chassis_id = match.group("dev_id") if is_ipv4(remote_chassis_id) or is_ipv6(remote_chassis_id): remote_chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_NETWORK_ADDRESS elif is_mac(remote_chassis_id): remote_chassis_id = MACAddressParameter().clean(remote_chassis_id) remote_chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_MAC else: remote_chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_LOCAL n["remote_chassis_id"] = remote_chassis_id n["remote_chassis_id_subtype"] = remote_chassis_id_subtype if match.group("sys_name").strip(): sys_name = match.group("sys_name").strip() n["remote_system_name"] = sys_name if match.group("sys_descr").strip(): sys_descr = match.group("sys_descr").strip() n["remote_system_description"] = sys_descr if match.group("port_descr").strip(): port_descr = match.group("port_descr").strip() n["remote_port_description"] = port_descr except Exception: pass i["neighbors"] += [n] r += [i] return r
def execute(self): r = [] try: v = self.cli("show lldp neighbors") except self.CLISyntaxError: raise self.NotSupportedError() if v.startswith("%"): # % LLDP is not enabled return [] v = self.rx_summary_split.split(v)[1] lldp_interfaces = [] # Get LLDP interfaces with neighbors for ll in v.splitlines(): ll = ll.strip() if not ll: break match = self.rx_s_line.match(ll) if not match: continue lldp_interfaces += [match.group("local_if")] # Get LLDP neighbors for local_if in lldp_interfaces: i = {"local_interface": local_if, "neighbors": []} # Get neighbors details try: v = self.cli("show lldp neighbors interface %s detail" % local_if) except self.CLISyntaxError: # Found strange CLI syntax on Catalyst 4900 # Allow ONLY interface name or "detail" # Need testing... raise self.NotSupportedError() # Get remote port match = self.rx_remote_port.search(v) remote_port = match.group("remote_if") remote_port_subtype = 128 if self.rx_mac.match(remote_port): # Actually macAddress(3) # Convert MAC to common form remote_port = MACAddressParameter().clean(remote_port) remote_port_subtype = 3 elif is_ipv4(remote_port): # Actually networkAddress(4) remote_port_subtype = 4 elif is_int(remote_port): # Actually local(7) remote_port_subtype = 7 n = { "remote_port": remote_port, "remote_port_subtype": remote_port_subtype, "remote_chassis_id_subtype": 4, } # Get chassis id match = self.rx_chassis_id.search(v) if not match: continue n["remote_chassis_id"] = match.group("id") # Get capabilities cap = 0 match = self.rx_enabled_caps.search(v) if match: for c in match.group("caps").split(","): c = c.strip() if c: cap |= { "O": 1, "P": 2, "B": 4, "W": 8, "R": 16, "T": 32, "C": 64, "S": 128, "N/A": 256, }[c] n["remote_capabilities"] = cap # Get remote chassis id match = self.rx_system.search(v) if match: n["remote_system_name"] = match.group("name") i["neighbors"] += [n] r += [i] return r
def clean_mac(self): v = self.cleaned_data["mac"] if v: return MACAddressParameter().form_clean(v)
def execute(self): ifaces = {} mac_svi = "" name_ = {} mac_ = {} snmp_ifindex_ = {} descr_ = {} stat_ = {} tagged_ = {} untagged_ = {} # Get interface status for p in self.scripts.get_interface_status(): intf = p["interface"] name_[intf] = intf if "mac" in p: mac_[intf] = p["mac"] if "description" in p: descr_[intf] = p["description"] stat_[intf] = p["status"] if "snmp_ifindex" in p: snmp_ifindex_[intf] = p["snmp_ifindex"] # Get switchport's for p in self.scripts.get_switchport(): intf = p["interface"] if "tagged" in p: tagged_[intf] = p["tagged"] if "untagged" in p: untagged_[intf] = p["untagged"] # Get SVI interface ip_addr = [] sub = {} for ls in self.cli("sh system").splitlines(): match = self.rx_svi_name.search(ls) if match: namesviif = "Vlan " + match.group("vl_id").upper() match = self.rx_ip_if.search(ls) if match: ip = match.group("ip") match = self.rx_ip_mask.search(ls) if match: mask = match.group("mask") ip_addr += [IPv4(ip, netmask=mask).prefix] match = self.rx_ip_mac.search(ls) if match: mac_svi = MACAddressParameter().clean(match.group("mac")) type = "SVI" stat = "up" vlan_ids = [int(namesviif[5:])] enabled_afi = ["IPv4"] sub = { "name": namesviif, "admin_status": stat == "up", "oper_status": stat == "up", "is_ipv4": True, "enabled_afi": enabled_afi, "ipv4_addresses": ip_addr, "vlan_ids": vlan_ids, "mac": mac_svi, } ifaces[namesviif] = { "name": namesviif, "admin_status": stat == "up", "oper_status": stat == "up", "type": type, "mac": mac_svi, "subinterfaces": [sub], } # set name ifaces for current in name_: ifaces[current] = {"name": current} # other for current in ifaces: is_svi = current.startswith("Vlan") if is_svi: continue if current in mac_: ifaces[current]["mac"] = mac_[current] ifaces[current]["admin_status"] = stat_[current] ifaces[current]["oper_status"] = stat_[current] ifaces[current]["type"] = "physical" ifaces[current]["enabled_protocols"] = [] enabled_afi = ["BRIDGE"] sub = { "name": current, "admin_status": stat_[current], "oper_status": stat_[current], "is_bridge": True, "enabled_afi": enabled_afi, } if current in mac_: sub["mac"] = mac_[current] if current in tagged_: sub["tagged_vlans"] = tagged_[current] if current in untagged_: sub["untagged_vlan"] = untagged_[current] if current in snmp_ifindex_: sub["snmp_ifindex"] = snmp_ifindex_[current] ifaces[current]["subinterfaces"] = [sub] # Get VRFs and "default" VRF interfaces r = [] vpns = [{"name": "default", "type": "ip", "interfaces": []}] for fi in vpns: # Forwarding instance rr = { "forwarding_instance": fi["name"], "type": fi["type"], "interfaces": [] } rd = fi.get("rd") if rd: rr["rd"] = rd # create ifaces rr["interfaces"] = list(ifaces.values()) r += [rr] # Return result return r
def execute_cli(self): d = {} if self.has_snmp(): try: for s in self.snmp.getnext("1.3.6.1.2.1.2.2.1.2", max_repetitions=10): n = s[1] sifindex = s[0][len("1.3.6.1.2.1.2.2.1.2") + 1:] if int(sifindex) < 3000: sm = str( self.snmp.get("1.3.6.1.2.1.2.2.1.6.%s" % sifindex)) smac = MACAddressParameter().clean(sm) if n.startswith("oob"): continue sname = self.profile.convert_interface_name(n) else: continue d[sname] = {"sifindex": sifindex, "smac": smac} except self.snmp.TimeOutError: pass # Get portchannels portchannel_members = {} for pc in self.scripts.get_portchannel(): i = pc["interface"] t = pc["type"] == "L" for m in pc["members"]: portchannel_members[m] = (i, t) # Get LLDP interfaces lldp = [] if self.has_capability("Network | LLDP"): c = self.cli("show lldp configuration", ignore_errors=True) if self.rx_lldp_en.search(c): lldp = self.rx_lldp.findall(c) # Get GVRP interfaces gvrp = [] c = self.cli("show gvrp configuration", ignore_errors=True) if self.rx_gvrp_en.search(c): gvrp = self.rx_gvrp.findall(c) # Get STP interfaces stp = [] if self.has_capability("Network | STP"): c = self.cli("show spanning-tree", ignore_errors=True) if self.rx_stp_en.search(c): stp = self.rx_stp.findall(c) # Get ifname and description c = self.cli("show interfaces description").split("\n\n") i = self.rx_sh_int_des.findall("".join(["%s\n\n%s" % (c[0], c[1])])) if not i: i = self.rx_sh_int_des2.findall("".join( ["%s\n\n%s" % (c[0], c[1])])) interfaces = [] mtu = None for res in i: mac = None ifindex = 0 name = res[0].strip() if self.is_has_chgroup: v = self.cli("show interface %s" % name) time.sleep(0.5) for match in self.rx_sh_int.finditer(v): # ifname = match.group("interface") ifindex = match.group("ifindex") mac = match.group("mac") mtu = match.group("mtu") if len(res) == 4: a_stat = res[1].strip().lower() == "up" o_stat = res[2].strip().lower() == "up" description = res[3].strip() else: a_stat = True o_stat = match.group("oper_status").lower() == "up" description = match.group("descr").strip() if not description: description = "" else: if self.profile.convert_interface_name(name) in d: ifindex = d[self.profile.convert_interface_name( name)]["sifindex"] mac = d[self.profile.convert_interface_name(name)]["smac"] if len(res) == 4: a_stat = res[1].strip().lower() == "up" o_stat = res[2].strip().lower() == "up" description = res[3].strip() else: o_stat = True a_stat = True description = res[1].strip() sub = { "name": self.profile.convert_interface_name(name), "admin_status": a_stat, "oper_status": o_stat, "enabled_afi": [], } if description: sub["description"] = description if mtu: sub["mtu"] = mtu if ifindex: sub["snmp_ifindex"] = ifindex if mac: sub["mac"] = mac iface = { "type": self.profile.get_interface_type(name), "name": self.profile.convert_interface_name(name), "admin_status": a_stat, "oper_status": o_stat, "enabled_protocols": [], "subinterfaces": [sub], } if description: iface["description"] = description if ifindex: iface["snmp_ifindex"] = ifindex if mac: iface["mac"] = mac # LLDP protocol if name in lldp: iface["enabled_protocols"] += ["LLDP"] # GVRP protocol if name in gvrp: iface["enabled_protocols"] += ["GVRP"] # STP protocol if name in stp: iface["enabled_protocols"] += ["STP"] # Portchannel member name = self.profile.convert_interface_name(name) if name in portchannel_members: ai, is_lacp = portchannel_members[name] iface["aggregated_interface"] = ai if is_lacp: iface["enabled_protocols"] += ["LACP"] iface["subinterfaces"][0]["enabled_afi"] += ["BRIDGE"] # Vlans cmd = self.cli("show interfaces switchport %s" % name) time.sleep(0.5) rcmd = cmd.split("\n\n") tvlan = [] utvlan = None for vlan in parse_table(rcmd[0]): vlan_id = vlan[0] rule = vlan[2] if rule == "Tagged": tvlan.append(int(vlan_id)) elif rule == "Untagged": utvlan = vlan_id iface["subinterfaces"][0]["tagged_vlans"] = tvlan if utvlan: iface["subinterfaces"][0]["untagged_vlan"] = utvlan cmd = self.cli("show ip interface %s" % name) time.sleep(0.5) for match in self.rx_sh_ip_int.finditer(cmd): if not match: continue ip = match.group("ip") netmask = match.group("mask") ip = ip + "/" + netmask ip_list = [ip] enabled_afi = [] if ":" in ip: ip_interfaces = "ipv6_addresses" enabled_afi += ["IPv6"] else: ip_interfaces = "ipv4_addresses" enabled_afi += ["IPv4"] iface["subinterfaces"][0]["enabled_afi"] = enabled_afi iface["subinterfaces"][0][ip_interfaces] = ip_list interfaces += [iface] ip_iface = self.cli("show ip interface") for match in self.rx_sh_ip_int.finditer(ip_iface): ifname = match.group("interface") typ = self.profile.get_interface_type(ifname) ip = match.group("ip") netmask = match.group("mask") ip = ip + "/" + netmask ip_list = [ip] enabled_afi = [] if ":" in ip: ip_interfaces = "ipv6_addresses" enabled_afi += ["IPv6"] else: ip_interfaces = "ipv4_addresses" enabled_afi += ["IPv4"] if ifname.startswith("vlan"): vlan = ifname.split(" ")[1] ifname = ifname.strip() else: continue if match.group("admin_status"): a_stat = match.group("admin_status").lower() == "up" else: a_stat = True if match.group("oper_status"): o_stat = match.group("oper_status").lower() == "up" else: o_stat = True iface = { "name": self.profile.convert_interface_name(ifname), "type": typ, "admin_status": a_stat, "oper_status": o_stat, "subinterfaces": [{ "name": ifname, "admin_status": a_stat, "oper_status": o_stat, "enabled_afi": enabled_afi, ip_interfaces: ip_list, "vlan_ids": self.expand_rangelist(vlan), }], } interfaces += [iface] return [{"interfaces": interfaces}]
def execute(self): r = [] """ # Try SNMP first if self.snmp and self.access_profile.snmp_ro: try: # lldpRemLocalPortNum # lldpRemChassisIdSubtype lldpRemChassisId # lldpRemPortIdSubtype lldpRemPortId # lldpRemSysName lldpRemSysCapEnabled for v in self.snmp.get_tables(["1.0.8802.1.1.2.1.4.1.1.2", "1.0.8802.1.1.2.1.4.1.1.4", "1.0.8802.1.1.2.1.4.1.1.5", "1.0.8802.1.1.2.1.4.1.1.6", "1.0.8802.1.1.2.1.4.1.1.7", "1.0.8802.1.1.2.1.4.1.1.9", "1.0.8802.1.1.2.1.4.1.1.12" ], bulk=True): local_interface = self.snmp.get("1.3.6.1.2.1.31.1.1.1.1." + v[1], cached=True) remote_chassis_id_subtype = v[2] remotechassisid = ":".join(["%02x" % ord(c) for c in v[3]]) remote_port_subtype = v[4] if remote_port_subtype == 7: remote_port_subtype = 5 remote_port = v[5] remote_system_name = v[6] remote_capabilities = v[7] i = {"local_interface": local_interface, "neighbors": []} n = { "remote_chassis_id_subtype": remote_chassis_id_subtype, "remote_chassis_id": remotechassisid, "remote_port_subtype": remote_port_subtype, "remote_port": remote_port, "remote_capabilities": remote_capabilities, } if remote_system_name: n["remote_system_name"] = remote_system_name i["neighbors"].append(n) r.append(i) return r except self.snmp.TimeOutError: pass """ # Fallback to CLI lldp = self.cli("show lldp neighbors") for link in parse_table(lldp, allow_wrap=True): local_interface = link[0] remote_chassis_id = link[1] remote_port = link[2] remote_system_name = link[3] # Build neighbor data # Get capability cap = 0 for c in link[4].split(","): c = c.strip() if c: cap |= self.CAPS_MAP[c] # Get remote port subtype remote_port_subtype = 5 if self.rx_mac.match(remote_port): # Actually macAddress(3) # Convert MAC to common form remote_port = MACAddressParameter().clean(remote_port) remote_port_subtype = 3 elif is_ipv4(remote_port): # Actually networkAddress(4) remote_port_subtype = 4 elif is_int(remote_port): # Actually local(7) remote_port_subtype = 5 i = {"local_interface": local_interface, "neighbors": []} n = { "remote_chassis_id": remote_chassis_id, "remote_port": remote_port, "remote_capabilities": cap, "remote_port_subtype": remote_port_subtype, } if remote_system_name: n["remote_system_name"] = remote_system_name # @todo: # n["remote_chassis_id_subtype"] = 4 i["neighbors"] += [n] r += [i] return r
def test_macaddress_parameter_error(raw, config): with pytest.raises(InterfaceTypeError): assert MACAddressParameter(**config).clean(raw)
def test_macaddress_parameter(raw, config, expected): assert MACAddressParameter(**config).clean(raw) == expected
def execute(self, interface=None): if self.has_snmp(): try: # Get interface status r = [] for i, n, s, d, m in self.snmp.join([ mib["IF-MIB::ifDescr"], mib["IF-MIB::ifOperStatus"], mib["IF-MIB::ifAlias"], mib["IF-MIB::ifPhysAddress"] ], join="left"): match = self.rx_snmp_name_eth.search(n) if match: if match.group("unit") == "0": unit = "1" n = "Eth " + unit + "/" + match.group("port") else: n = "Eth " + match.group( "unit") + "/" + match.group("port") if n.startswith("Trunk ID"): n = "Trunk " + n.replace("Trunk ID ", "").lstrip('0') if n.startswith("Trunk Port ID"): n = "Trunk " + n.replace("Trunk Port ID ", "").lstrip('0') if n.startswith("Trunk Member"): n = "Eth 1/" + str(i) if n.startswith("VLAN ID"): n = "VLAN " + n.replace("VLAN ID ", "").lstrip('0') if n.startswith("VLAN interface"): n = "VLAN " + n.replace("VLAN interface ID ", "").lstrip('0') if n.startswith("Console"): continue if n.startswith("Loopback"): continue r += [{ "snmp_ifindex": i, "interface": n, "status": int(s) == 1, "description": d, "mac": MACAddressParameter().clean(m) }] return r except self.snmp.TimeOutError: pass # Fallback to CLI r = [] s = [] if self.match_version(platform__contains="4626"): try: cmd = "show interface status | include line protocol is|alias|address is" buf = self.cli(cmd).replace("\n ", " ") except: cmd = "show interface status" buf = self.cli(cmd).replace("\n ", " ") for l in buf.splitlines(): match = self.rx_interface_status.match(l) if match: r += [{ "interface": match.group("interface"), "status": match.group("status") == "up", "mac": MACAddressParameter().clean(match.group("mac")), "snmp_ifindex": match.group("ifindex") }] mdescr = self.rx_interface_descr.match(l) if mdescr: r[-1]["description"] = mdescr.group("descr") else: cmd = "show interface status" buf = self.cli(cmd).lstrip("\n\n") for l in buf.split("\n\n"): match = self.rx_interface_status_3526.search(l + "\n") if match: descr = "" interface = match.group("interface") if interface.startswith("VLAN"): intstatus = "up" linestatus = "up" else: if match.group("block"): block = match.group("block") submatch = self.rx_interface_intstatus_3526.search( block) if submatch: descr = submatch.group("descr") intstatus = submatch.group("intstatus").lower() linestatus = "down" submatch = self.rx_interface_linestatus_3526.search( block) if submatch: linestatus = submatch.group( "linestatus").lower() r += [{ "interface": interface, "mac": MACAddressParameter().clean(match.group("mac")), "status": linestatus.lower() == "up", }] if descr: r[-1]["description"] = descr return r