예제 #1
0
파일: ping.py 프로젝트: nbashev/noc
 def execute_cli(self, address, count=None, source_address=None, size=None):
     if is_ipv4(address):
         cmd = "ping ip %s" % address
     elif is_ipv6(address):
         cmd = "ping ipv6 %s" % address
     if count:
         cmd += " count %d" % int(count)
     if size:
         cmd += " size %d" % int(size)
     try:
         s = self.cli(cmd)
     except self.CLISyntaxError:
         if is_ipv4(address):
             cmd = "ping"
         elif is_ipv6(address):
             cmd = "ping6 %s"
         if count:
             cmd += " -n %d" % int(count)
         if size:
             cmd += " -l %d" % int(size)
         cmd = "%s %s" % (cmd, address)
         s = self.cli(cmd)
     match = self.rx_result1.search(s)
     if match:
         return {
             "success": match.group("success"),
             "count": match.group("count"),
             "min": match.group("min"),
             "avg": match.group("avg"),
             "max": match.group("max"),
         }
     else:
         match = self.rx_result2.search(s)
         return {"success": match.group("success"), "count": match.group("count")}
예제 #2
0
 def execute_cli(self):
     r = []
     v = self.cli("show lldp neighbors")
     for match in self.rx_local_port.finditer(v):
         local_interface = match.group("port")
         c = self.cli("show lldp neighbors interface %s" % local_interface)
         match1 = self.rx_remote.search(c)
         chassis_id = match1.group("chassis_id")
         if is_ipv4(chassis_id) or is_ipv6(chassis_id):
             chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_NETWORK_ADDRESS
         elif is_mac(chassis_id):
             chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_MAC
         else:
             chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_LOCAL
         port_id = match1.group("port_id")
         if is_ipv4(port_id) or is_ipv6(port_id):
             port_id_subtype = LLDP_PORT_SUBTYPE_NETWORK_ADDRESS
         elif is_mac(port_id):
             port_id_subtype = LLDP_PORT_SUBTYPE_MAC
         else:
             port_id_subtype = LLDP_PORT_SUBTYPE_LOCAL
         neighbor = {
             "remote_chassis_id_subtype": chassis_id_subtype,
             "remote_chassis_id": chassis_id,
             "remote_port_subtype": port_id_subtype,
             "remote_port": port_id,
         }
         port_descr = match1.group("port_descr").strip()
         if port_descr and "-- not advertised" not in port_descr:
             neighbor["remote_port_description"] = port_descr
         r += [{
             "local_interface": local_interface,
             "neighbors": [neighbor]
         }]
     return r
예제 #3
0
    def execute_cli(self):
        r = []
        t = parse_table(self.cli("show lldp neighbor"), allow_wrap=True)
        for i in t:
            c = self.cli("show lldp neighbor %s" % i[0])
            match = self.rx_neighbor.search(c)
            chassis_id = match.group("chassis_id")
            if is_ipv4(chassis_id) or is_ipv6(chassis_id):
                chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_NETWORK_ADDRESS
            elif is_mac(chassis_id):
                chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_MAC
            else:
                chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_LOCAL
            port_id = match.group("port_id")
            if is_ipv4(port_id) or is_ipv6(port_id):
                port_id_subtype = LLDP_PORT_SUBTYPE_NETWORK_ADDRESS
            elif is_mac(port_id):
                port_id_subtype = LLDP_PORT_SUBTYPE_MAC
            else:
                port_id_subtype = LLDP_PORT_SUBTYPE_LOCAL
            neighbor = {
                "remote_chassis_id": chassis_id,
                "remote_chassis_id_subtype": chassis_id_subtype,
                "remote_port": port_id,
                "remote_port_subtype": port_id_subtype,
            }
            if match.group("port_descr"):
                port_descr = match.group("port_descr").strip()
                if port_descr:
                    neighbor["remote_port_description"] = port_descr
            if match.group("system_name"):
                system_name = match.group("system_name").strip()
                if system_name:
                    neighbor["remote_system_name"] = system_name
            if match.group("system_descr"):
                system_descr = match.group("system_descr").strip()
                if system_descr:
                    neighbor["remote_system_description"] = system_descr
            caps = 0
            match = self.rx_caps.search(c)
            if match:
                caps = lldp_caps_to_bits(
                    match.group("caps").strip().split(","),
                    {
                        "other": LLDP_CAP_OTHER,
                        "repeater": LLDP_CAP_REPEATER,
                        "bridge": LLDP_CAP_BRIDGE,
                        "access point": LLDP_CAP_WLAN_ACCESS_POINT,
                        "router": LLDP_CAP_ROUTER,
                        "telephone": LLDP_CAP_TELEPHONE,
                        "cable device": LLDP_CAP_DOCSIS_CABLE_DEVICE,
                        "station only": LLDP_CAP_STATION_ONLY,
                    },
                )
            neighbor["remote_capabilities"] = caps

            r += [{"local_interface": i[0], "neighbors": [neighbor]}]
        return r
예제 #4
0
 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
         elif is_mac(chassis_id):
             chassis_id_subtype = 4
         else:
             chassis_id_subtype = 7
         port_id = i[2]
         if is_ipv4(port_id) or is_ipv6(port_id):
             port_id_subtype = 4
         elif is_mac(port_id):
             port_id_subtype = 3
         else:
             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]
         s = self.cli("show lldp neighbors ethernet %s" % i[0])
         match = self.rx_sysdescr.search(s)
         if match:
             neighbor["remote_system_description"] = match.group(
                 "descr").strip()
         match = self.rx_portdescr.search(s)
         if match:
             neighbor["remote_port_description"] = match.group(
                 "descr").strip()
         r += [{"local_interface": i[0], "neighbors": [neighbor]}]
     return r
예제 #5
0
 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
예제 #6
0
    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
예제 #7
0
 def execute_l(self, res):
     r = []
     for line in res.splitlines():
         match = self.rx_search.search(line)
         if not match:
             continue
         iface = self.cli("show lldp neighbors interface %s" %
                          match.group("iface"))
         iface_match = self.rx_port2.search(iface)
         chassis_id = iface_match.group("device_id")
         if is_ipv4(chassis_id) or is_ipv6(chassis_id):
             chassis_id_subtype = 5
         elif is_mac(chassis_id):
             chassis_id_subtype = 4
         else:
             chassis_id_subtype = 7
         port_id = iface_match.group("port_id")
         if is_ipv4(port_id) or is_ipv6(port_id):
             port_id_subtype = 4
         elif is_mac(port_id):
             port_id_subtype = 3
         else:
             port_id_subtype = 7
         caps = 0
         for c in iface_match.group("capabilities").split():
             c = c.strip()
             if c:
                 caps |= self.data[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 iface_match.group("system_name"):
             neighbor["remote_system_name"] = iface_match.group(
                 "system_name")
         if iface_match.group("system_description"):
             neighbor["remote_system_description"] = iface_match.group(
                 "system_description").strip()
         if iface_match.group("port_description"):
             neighbor["remote_port_description"] = iface_match.group(
                 "port_description").strip()
         r += [{
             "local_interface": match.group("iface"),
             "neighbors": [neighbor]
         }]
     return r
예제 #8
0
 def execute(self):
     r = []
     try:
         v = self.cli("show lldp info")
     except self.CLISyntaxError:
         raise self.NotSupportedError()
     for match in self.rx_line.finditer(v):
         chassis_id = match.group("chassis_id")
         if is_ipv4(chassis_id) or is_ipv6(chassis_id):
             chassis_id_subtype = 5
         elif is_mac(chassis_id):
             chassis_id_subtype = 4
         else:
             chassis_id_subtype = 7
         port_id = match.group("port_id")
         if is_ipv4(port_id) or is_ipv6(port_id):
             port_id_subtype = 4
         elif is_mac(port_id):
             port_id_subtype = 3
         else:
             port_id_subtype = 7
         caps = 0
         # Need more examples
         if "Bridge" in match.group("caps"):
             caps += 4
         if "Router" in match.group("caps"):
             caps += 16
         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").strip()
         if match.group("system_description"):
             neighbor["remote_system_description"] = match.group(
                 "system_description").strip()
         if match.group("port_description"):
             neighbor["remote_port_description"] = match.group(
                 "port_description").strip()
         r += [{
             "local_interface": match.group("port"),
             "neighbors": [neighbor]
         }]
     return r
예제 #9
0
 def on_syslog_server(self, tokens):
     """
     logging <server>
     """
     h = tokens[1]
     if is_ipv4(h) or is_ipv6(h):
         self.get_sysloghost_fact(h)
예제 #10
0
    def get_zone(cls, name):
        """
        Resolve name to zone object
        :return:
        """
        def get_closest(n):
            """
            Return closest matching zone
            """
            while n:
                try:
                    return DNSZone.objects.get(name=n)
                except DNSZone.DoesNotExist:
                    pass
                n = ".".join(n.split(".")[1:])
            return None

        if not name:
            return None
        if is_ipv4(name):
            # IPv4 zone
            n = name.split(".")
            n.reverse()
            return get_closest("%s.in-addr.arpa" % (".".join(n[1:])))
        elif is_ipv6(name):
            # IPv6 zone
            d = IPv6(name).digits
            d.reverse()
            c = ".".join(d)
            return get_closest("%s.ip6.arpa" % c) or get_closest(
                "%s.ip6.int" % c)
        else:
            return get_closest(name)
예제 #11
0
 def fix_ip_addr(self, ipaddr_section):
     """
     :rtype : dict
     """
     result = {
         "ipv4_addresses": [],
         "ipv6_addresses": [],
         "enabled_afi": []
     }
     if not ipaddr_section:
         return result
     if "Unnumbered If" in ipaddr_section:
         return result
     for line in ipaddr_section.splitlines():
         match_obj = self.re_ipaddr.search(line)
         if match_obj:
             afi = match_obj.group(1)
             ip = match_obj.group(2)
             if afi == "IP Addr/mask" and "Not" not in ip:
                 result["ipv4_addresses"] += [ip]
             elif afi == "IPv6 Addr" and is_ipv6(ip):
                 result["ipv6_addresses"] += [ip]
     if result["ipv4_addresses"]:
         result["enabled_afi"] += ["IPv4"]
     if result["ipv6_addresses"]:
         result["enabled_afi"] += ["IPv6"]
     return result
예제 #12
0
 def migrate(self):
     fixes, dot_fixes = [], []
     for mo_id, address in self.db.execute("SELECT id, address FROM sa_managedobject"):
         if not address:
             continue
         if is_ipv4(address) or is_ipv6(address):
             continue
         if address.endswith("."):
             fixes += [str(mo_id)]
         else:
             dot_fixes += [str(mo_id)]
     if fixes:
         self.db.execute(
             """
             UPDATE sa_managedobject
             SET fqdn=address, address_resolution_policy='O'
             WHERE id IN (%s)
             """
             % ",".join(fixes)
         )
     if dot_fixes:
         self.db.execute(
             """
             UPDATE sa_managedobject
             SET fqdn=concat(address, '.'), address_resolution_policy='O'
             WHERE id IN (%s)
             """
             % ",".join(dot_fixes)
         )
예제 #13
0
 def clean(self, value):
     if value is None and self.default is not None:
         return self.default
     v = super(IPv6Parameter, self).clean(value)
     if not is_ipv6(v):
         self.raise_error(value)
     return IPv6(v).normalized.address
예제 #14
0
 def execute(self,
             address,
             count=None,
             source_address=None,
             size=None,
             df=None,
             vrf=None):
     if is_ipv4(address):
         cmd = "ping ip %s" % address
     elif is_ipv6(address):
         cmd = "ping ipv6 %s" % address
     if count:
         cmd += " count %d" % int(count)
     if size:
         cmd += " size %d" % int(size)
     s = self.cli(cmd)
     match = self.rx_result1.search(s)
     if match:
         return {
             "success": match.group("success"),
             "count": match.group("count"),
             "min": match.group("min"),
             "avg": match.group("avg"),
             "max": match.group("max"),
         }
     else:
         match = self.rx_result2.search(s)
         return {
             "success": match.group("success"),
             "count": match.group("count")
         }
예제 #15
0
 def execute_cli(self):
     r = []
     try:
         v = self.cli("show lldp neighbors")
     except self.CLISyntaxError:
         raise self.NotSupportedError()
     for match in self.rx_line.finditer(v):
         chassis_id = match.group("chassis_id")
         if is_ipv4(chassis_id) or is_ipv6(chassis_id):
             chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_NETWORK_ADDRESS
         elif is_mac(chassis_id):
             chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_MAC
         else:
             chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_LOCAL
         port_id = match.group("port_id")
         if is_ipv4(port_id) or is_ipv6(port_id):
             port_id_subtype = LLDP_PORT_SUBTYPE_NETWORK_ADDRESS
         elif is_mac(port_id):
             port_id_subtype = LLDP_PORT_SUBTYPE_MAC
         else:
             port_id_subtype = LLDP_PORT_SUBTYPE_LOCAL
         caps = 0
         # Need more examples
         if "Bridge" in match.group("caps"):
             caps += LLDP_CAP_BRIDGE
         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").strip()
         if match.group("system_description"):
             neighbor["remote_system_description"] = match.group(
                 "system_description").strip()
         if match.group("port_description"):
             neighbor["remote_port_description"] = match.group(
                 "port_description").strip()
         r += [{
             "local_interface": match.group("port"),
             "neighbors": [neighbor]
         }]
     return r
예제 #16
0
 def execute_n(self, res):
     r = []
     t = parse_table(res, allow_wrap=True)
     for i in t:
         chassis_id = i[1]
         if is_ipv4(chassis_id) or is_ipv6(chassis_id):
             chassis_id_subtype = 5
         elif is_mac(chassis_id):
             chassis_id_subtype = 4
         else:
             chassis_id_subtype = 7
         port_id = i[2]
         if is_ipv4(port_id) or is_ipv6(port_id):
             port_id_subtype = 4
         elif is_mac(port_id):
             port_id_subtype = 3
         else:
             port_id_subtype = 7
         caps = 0
         for c in i[4].split(","):
             c = c.strip()
             if c:
                 caps |= self.data[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]
         try:
             v = self.cli("show lldp neighbors %s" % i[0])
             match = self.rx_port.search(v)
         except self.CLISyntaxError:
             pass
         if match:
             neighbor["remote_system_description"] = match.group(
                 "system_description").strip()
             neighbor["remote_port_description"] = match.group(
                 "port_description").strip()
         r += [{"local_interface": i[0], "neighbors": [neighbor]}]
     return r
예제 #17
0
 def execute_cli(self, address, count=None, source_address=None, size=None):
     if is_ipv4(address):
         cmd = "ping ip %s" % address
     elif is_ipv6(address):
         cmd = "ping ipv6 %s" % address
     if count:
         cmd += " repeat %d" % int(count)
     if size:
         cmd += " size %d" % int(size)
     s = self.cli(cmd)
     match = self.rx_result.search(s)
     return match.groupdict()
예제 #18
0
 def clean(self, data):
     data = super(AddressRangeApplication, self).clean(data)
     afi = data["afi"]
     from_address = data["from_address"]
     to_address = data["to_address"]
     # Check AFI
     address_validator = is_ipv4 if afi == "4" else is_ipv6
     if not address_validator(from_address):
         raise ValueError("Invalid IPv%(afi)s 'From Address'" %
                          {"afi": afi})
     if not address_validator(to_address):
         raise ValueError("Invalid IPv%(afi)s 'To Address'" % {"afi": afi})
     # Check from address not greater than to address
     if IP.prefix(from_address) > IP.prefix(to_address):
         raise ValueError(
             "'To Address' must be greater or equal than 'From Address'")
     # Check for valid "action" combination
     if "fqdn_template" in data and data[
             "fqdn_template"] and data["action"] != "G":
         raise ValueError(
             "'FQDN Template' must be clean for selected 'Action'")
     if "reverse_nses" in data and data[
             "reverse_nses"] and data["action"] != "D":
         raise ValueError(
             "'Reverse NSes' must be clean for selected 'Action'")
     # Set range as locked for "G" and "D" actions
     if data["action"] != "N":
         data["is_locked"] = True
     # @todo: check FQDN template
     # Check reverse_nses is a list of FQDNs or IPs
     if "reverse_nses" in data and data["reverse_nses"]:
         reverse_nses = data["reverse_nses"]
         for ns in reverse_nses.split(","):
             ns = ns.strip()
             if not is_ipv4(ns) and not is_ipv6(ns) and not is_fqdn(ns):
                 raise ValueError("%s is invalid nameserver" % ns)
     # Check no locked range overlaps another locked range
     if data["is_locked"]:
         r = [
             r for r in AddressRange.get_overlapping_ranges(
                 data["vrf"], data["afi"], data["from_address"],
                 data["to_address"])
             if r.is_locked is True and r.name != data["name"]
         ]
         if r:
             raise ValueError(
                 "Locked range overlaps with ahother locked range: %s" %
                 unicode(r[0]))
     return data
예제 #19
0
 def execute(self, address, count=None, source_address=None, size=None, df=None):
     if is_ipv4(address):
         cmd = "ping ip %s" % address
     elif is_ipv6(address):
         cmd = "ping ipv6 %s" % address
     if count:
         cmd += " count %d" % int(count)
     if size:
         cmd += " size %d" % int(size)
     if source_address:
         cmd += " source %s" % source_address
     if df:
         cmd += " df-bit"
     ping = self.cli(cmd)
     match = self.rx_result.search(ping)
     return {"success": match.group("success"), "count": match.group("count")}
예제 #20
0
    def get_objects_from_expression(cls, s):
        """
        Get list of Managed Object matching selector expression

        Expression must be string or list.
        Elements must be one of:
        * string starting with @ - treated as selector name
        * string containing numbers - treated as object's id
        * string - managed object name.
        * string - IPv4 or IPv6 address - management address

        Raises ManagedObject.DoesNotExists if object is not found.
        Raises ManagedObjectSelector.DoesNotExists if selector is not found
        :param cls:
        :param s:
        :return:
        """
        from .managedobject import ManagedObject

        if isinstance(s, int) or isinstance(s, str):
            s = [s]
        if not isinstance(s, list):
            raise ValueError("list required")
        objects = set()
        for so in s:
            if not isinstance(so, str):
                so = str(so)
            if so.startswith("@"):
                # Selector expression: @<selector name>
                o = ManagedObjectSelector.objects.get(name=so[1:])
                objects |= set(o.managed_objects)
            else:
                # Search by name
                q = Q(name=so)
                if is_int(so):
                    # Search by id
                    q |= Q(id=int(so))
                if is_ipv4(so) or is_ipv6(so):
                    q |= Q(address=so)
                o = ManagedObject.objects.get(q)
                objects.add(o)
        return list(objects)
예제 #21
0
    def execute_cli(self):
        r = defaultdict(list)  # local_iface -> neighbors
        try:
            lldp = self.cli("show lldp neighbors")
        except self.CLISyntaxError:
            raise self.NotSupportedError()
        for match in self.rx_lldp_nei.finditer(lldp):
            local_interface = match.group("interface")
            remote_chassis_id = match.group("chassis_id")
            remote_port = match.group("port_id")

            # Build neighbor data
            # Get capability
            cap = 4
            # Get remote port subtype
            remote_port_subtype = LLDP_PORT_SUBTYPE_NAME
            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

            n = {
                "remote_chassis_id": remote_chassis_id,
                "remote_port": remote_port,
                "remote_capabilities": cap,
                "remote_port_subtype": remote_port_subtype,
            }
            if is_ipv4(n["remote_chassis_id"]) or is_ipv6(
                    n["remote_chassis_id"]):
                n["remote_chassis_id_subtype"] = LLDP_CHASSIS_SUBTYPE_NETWORK_ADDRESS
            elif is_mac(n["remote_chassis_id"]):
                n["remote_chassis_id_subtype"] = LLDP_CHASSIS_SUBTYPE_MAC
            else:
                n["remote_chassis_id_subtype"] = LLDP_CHASSIS_SUBTYPE_LOCAL
            try:
                c = self.cli("show lldp ports %s neighbors detailed" %
                             local_interface)
                match = self.rx_lldp_detail.search(c)
                if match:
                    port_descr = match.group("port_descr")
                    if port_descr:
                        n["remote_port_description"] = port_descr.replace(
                            '"', "").strip()
                        n["remote_port_description"] = re.sub(
                            r"\\\n\s*", "", n["remote_port_description"])
                    n["remote_system_name"] = match.group(
                        "system_name").replace('"', "").strip()
                    n["remote_system_name"] = re.sub(r"\\\n\s*", "",
                                                     n["remote_system_name"])
                    sys_descr = match.group("system_descr")
                    if sys_descr:
                        n["remote_system_description"] = sys_descr.replace(
                            '"', "").strip()
                        n["remote_system_description"] = re.sub(
                            r"\\\n\s*", "", n["remote_system_description"])
                    n["remote_port_subtype"] = self.port_types[match.group(
                        "port_id_subtype").strip()]
                    n["remote_chassis_id_subtype"] = self.chassis_types[
                        match.group("chassis_id_subtype").strip()]
            except self.CLISyntaxError:
                pass
            r[local_interface].append(n)
        return [{"local_interface": x, "neighbors": r[x]} for x in r]
예제 #22
0
 def execute_cli(self):
     r = []
     r_rem = []
     v = self.cli("show lldp remote")
     for match in self.rx_lldp_rem.finditer(v):
         chassis_id = match.group("ch_id")
         if is_ipv4(chassis_id) or is_ipv6(chassis_id):
             chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_NETWORK_ADDRESS
         elif is_mac(chassis_id):
             chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_MAC
         else:
             chassis_id_subtype = LLDP_CHASSIS_SUBTYPE_LOCAL
         r_rem += [
             {
                 "local_interface": match.group("port"),
                 "remote_chassis_id": chassis_id,
                 "remote_chassis_id_subtype": chassis_id_subtype,
             }
         ]
     v = self.cli("show lldp remote detail")
     # If detail command not contain ch id
     ext_ch_id = False
     lldp_iter = list(self.rx_lldp.finditer(v))
     if not lldp_iter:
         ext_ch_id = True
         lldp_iter = list(self.rx_lldp_womac.finditer(v))
         self.logger.debug("Not Find MAC in re")
     for match in lldp_iter:
         i = {"local_interface": match.group("port"), "neighbors": []}
         cap = lldp_caps_to_bits(
             match.group("sys_caps_enabled").strip().split(","),
             {
                 "n/a": 0,
                 "other": LLDP_CAP_OTHER,
                 "repeater/hub": LLDP_CAP_REPEATER,
                 "bridge/switch": LLDP_CAP_BRIDGE,
                 "router": LLDP_CAP_ROUTER,
                 "telephone": LLDP_CAP_TELEPHONE,
                 "station": LLDP_CAP_STATION_ONLY,
             },
         )
         n = {
             "remote_chassis_id_subtype": {
                 "macAddress": LLDP_CHASSIS_SUBTYPE_MAC,
                 "networkAddress": LLDP_CHASSIS_SUBTYPE_NETWORK_ADDRESS,
             }[match.group("ch_type")],
             "remote_chassis_id": match.group("ch_id") if not ext_ch_id else None,
             "remote_port_subtype": {
                 "ifAlias": LLDP_PORT_SUBTYPE_ALIAS,
                 "macAddress": LLDP_PORT_SUBTYPE_MAC,
                 "ifName": LLDP_PORT_SUBTYPE_NAME,
                 "portComponent": LLDP_PORT_SUBTYPE_NAME,
                 "local": LLDP_PORT_SUBTYPE_LOCAL,
             }[match.group("port_id_subtype")],
             "remote_port": match.group("port_id"),
             "remote_capabilities": cap,
         }
         if match.group("sys_name").strip() != "N/A":
             n["remote_system_name"] = match.group("sys_name").strip()
         if match.group("sys_descr").strip() != "N/A":
             sd = match.group("sys_descr").strip()
             if "SysDesc:" in sd:
                 sd = sd.split()[-1]
             n["remote_system_description"] = re.sub("\n\s{29,30}", "", sd)
         if match.group("port_descr").strip() != "N/A":
             n["remote_port_description"] = re.sub(
                 "\n\s{29,30}", "", match.group("port_descr").strip()
             )
             match.group("port_descr")
         if n["remote_chassis_id"] is None:
             for j in r_rem:
                 if i["local_interface"] == j["local_interface"]:
                     n["remote_chassis_id"] = j["remote_chassis_id"]
                     n["remote_chassis_id_subtype"] = j["remote_chassis_id_subtype"]
                     break
         i["neighbors"] += [n]
         r += [i]
     return r
예제 #23
0
 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
예제 #24
0
 def execute(self):
     r = []
     try:
         v = self.cli("show lldp neighbors")
     except self.CLISyntaxError:
         raise self.NotSupportedError()
     t = parse_table(v, allow_wrap=True)
     for i in t:
         chassis_id = i[1]
         if is_ipv4(chassis_id) or is_ipv6(chassis_id):
             chassis_id_subtype = 5
         elif is_mac(chassis_id):
             chassis_id_subtype = 4
         else:
             chassis_id_subtype = 7
         port_id = i[2]
         if is_ipv4(port_id) or is_ipv6(port_id):
             port_id_subtype = 4
         elif is_mac(port_id):
             port_id_subtype = 3
         else:
             port_id_subtype = 7
         caps = 0
         for c in i[4].split(","):
             c = c.strip()
             if c:
                 caps |= {
                     "O": 1,
                     "r": 2,
                     "B": 4,
                     "W": 8,
                     "R": 16,
                     "T": 32,
                     "C": 64,
                     "S": 128
                 }[c]
         """
         if "O" in i[4]:
             caps += 1
         elif "r" in i[4]:
             caps += 2
         elif "B" in i[4]:
             caps += 4
         elif "W" in i[4]:
             caps += 8
         elif "R" in i[4]:
             caps += 16
         elif "T" in i[4]:
             caps += 32
         elif "D" in i[4]:
             caps += 64
         elif "H" in i[4]:
             caps += 128
         """
         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]
         try:
             v = self.cli("show lldp neighbors %s" % i[0])
             match = self.rx_port.search(v)
             if match:
                 neighbor["remote_system_description"] = match.group(
                     "system_description").strip()
                 neighbor["remote_port_description"] = match.group(
                     "port_description").strip()
         except self.CLISyntaxError:
             pass
         r += [{"local_interface": i[0], "neighbors": [neighbor]}]
     return r
예제 #25
0
 def interpolate_ipv6(s):
     if not is_ipv6(s):
         return None
     return s
예제 #26
0
 def execute_cli(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 line in v.splitlines():
         line = line.strip()
         if not line:
             break
         match = self.rx_s_line.match(line)
         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 %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.re_search(self.rx_remote_port, v)
         remote_port = match.group("remote_if")
         remote_port_subtype = 1
         if is_ipv4(remote_port):
             # Actually networkAddress(4)
             remote_port = IPv4Parameter().clean(remote_port)
             remote_port_subtype = 4
         elif is_mac(remote_port):
             # Actually macAddress(3)
             # Convert MAC to common form
             remote_port = MACAddressParameter().clean(remote_port)
             remote_port_subtype = 3
         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,
         }
         match = self.rx_descr.search(v)
         if match:
             n["remote_port_description"] = match.group("descr")
         # 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,
                     }[c]
         n["remote_capabilities"] = cap
         # Get remote chassis id
         match = self.rx_system.search(v)
         if match:
             n["remote_system_name"] = match.group("name")
         if is_ipv4(n["remote_chassis_id"]) or is_ipv6(
                 n["remote_chassis_id"]):
             n["remote_chassis_id_subtype"] = 5
         elif is_mac(n["remote_chassis_id"]):
             pass
         else:
             n["remote_chassis_id_subtype"] = 7
         i["neighbors"] += [n]
         r += [i]
     return r
예제 #27
0
def test_is_ipv6(raw, expected):
    assert is_ipv6(raw) is expected
예제 #28
0
    def execute_cli(self):
        r = []
        with self.profile.switch(self):
            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]
                # Get capability
                cap = 0
                for c in link[4].split(","):
                    c = c.strip()
                    if c:
                        cap |= self.CAPS_MAP[c]

                if is_ipv4(remote_chassis_id) or is_ipv6(remote_chassis_id):
                    remote_chassis_id_subtype = 5
                elif is_mac(remote_chassis_id):
                    remote_chassis_id = MACAddressParameter().clean(
                        remote_chassis_id)
                    remote_chassis_id_subtype = 4
                else:
                    remote_chassis_id_subtype = 7

                # Get remote port subtype
                remote_port_subtype = 1
                if is_ipv4(remote_port):
                    # Actually networkAddress(4)
                    remote_port_subtype = 4
                elif is_mac(remote_port):
                    # Actually macAddress(3)
                    # Convert MAC to common form
                    remote_port = MACAddressParameter().clean(remote_port)
                    remote_port_subtype = 3
                elif is_int(remote_port):
                    # Actually local(7)
                    remote_port_subtype = 7
                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

                try:
                    c = self.cli("show lldp neighbors interface %s" %
                                 local_interface)
                    match = self.rx_detail.search(c)
                    if match:
                        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
예제 #29
0
 def execute_cli(self):
     r = []
     try:
         v = self.cli("show lldp neighbors")
     except self.CLISyntaxError:
         raise self.NotSupportedError()
     t = parse_table(v, allow_wrap=True)
     for i in t:
         local_if = i[0]
         v = self.cli("show lldp neighbors %s" % local_if)
         match = self.rx_neighbor.search(v)
         remote_chassis_id = match.group("remote_chassis_id")
         if is_ipv4(remote_chassis_id) or is_ipv6(remote_chassis_id):
             # Actually networkAddress(4)
             remote_chassis_id_subtype = 5
         elif is_mac(remote_chassis_id):
             # Actually macAddress(3)
             # Convert MAC to common form
             remote_chassis_id_subtype = 4
         else:
             remote_chassis_id_subtype = 7
         remote_port = match.group("remote_port")
         if is_ipv4(remote_port) or is_ipv6(remote_port):
             # Actually networkAddress(4)
             remote_port_subtype = 4
         elif is_mac(remote_port):
             # Actually macAddress(3)
             remote_port_subtype = 3
         elif is_int(remote_port):
             # Actually local(7)
             remote_port_subtype = 7
         else:
             remote_port_subtype = 5
         # Get capability
         cap = 0
         s = match.group("caps")
         for c in s.strip().split(", "):
             cap |= {
                 "Other": 1,
                 "Repeater": 2,
                 "Bridge": 4,
                 "WLAN": 8,
                 "Router": 16,
                 "Telephone": 32,
                 "Cable": 64,
                 "Station": 128,
             }[c]
         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,
         }
         match = self.rx_system_name.search(v)
         if match and match.group("system_name"):
             n["remote_system_name"] = match.group("system_name")
         match = self.rx_port_descr.search(v)
         if match and match.group("port_descr"):
             n["remote_port_description"] = match.group("port_descr")
         i = {"local_interface": local_if, "neighbors": [n]}
         r += [i]
     return r
예제 #30
0
 def execute_cli(self):
     r = []
     try:
         v = self.cli("show lldp neighbors")
     except self.CLISyntaxError:
         raise self.NotSupportedError()
     t = parse_table(v, allow_wrap=True)
     for i in t:
         chassis_id = i[1]
         if is_ipv4(chassis_id) or is_ipv6(chassis_id):
             chassis_id_subtype = 5
         elif is_mac(chassis_id):
             chassis_id_subtype = 4
         else:
             chassis_id_subtype = 7
         port_id = i[2]
         if is_ipv4(port_id) or is_ipv6(port_id):
             port_id_subtype = 4
         elif is_mac(port_id):
             port_id_subtype = 3
         else:
             port_id_subtype = 7
         caps = 0
         for c in i[4].split(","):
             c = c.strip()
             if c and c != "not":
                 caps |= {
                     "O": 1,
                     "P": 2,
                     "B": 4,
                     "W": 8,
                     "R": 16,
                     "r": 16,
                     "T": 32,
                     "C": 64,
                     "S": 128,
                 }[c]
         """
         if "O" in i[4]:
             caps += 1
         elif "r" in i[4]:
             caps += 2
         elif "B" in i[4]:
             caps += 4
         elif "W" in i[4]:
             caps += 8
         elif "R" in i[4]:
             caps += 16
         elif "T" in i[4]:
             caps += 32
         elif "D" in i[4]:
             caps += 64
         elif "H" in i[4]:
             caps += 128
         """
         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]}]
     if not t:
         for iface in self.scripts.get_interface_status():
             c = self.cli("show lldp neighbors interface %s" %
                          iface["interface"],
                          ignore_errors=True)
             c = c.replace("\n\n", "\n")
             neighbors = []
             for match in self.rx_neighbor.finditer(c):
                 chassis_id = match.group("chassis_id")
                 if is_ipv4(chassis_id) or is_ipv6(chassis_id):
                     chassis_id_subtype = 5
                 elif is_mac(chassis_id):
                     chassis_id_subtype = 4
                 else:
                     chassis_id_subtype = 7
                 port_id = match.group("port_id")
                 if is_ipv4(port_id) or is_ipv6(port_id):
                     port_id_subtype = 4
                 elif is_mac(port_id):
                     port_id_subtype = 3
                 else:
                     port_id_subtype = 7
                 caps = 0
                 if match.group("caps").strip():
                     for c in match.group("caps").split():
                         c = c.strip()
                         if c in {"not", "advertised"}:
                             # not caps
                             break
                         if c and (c != "--"):
                             caps |= {
                                 "O": 1,
                                 "P": 2,
                                 "B": 4,
                                 "W": 8,
                                 "R": 16,
                                 "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,
                 }
                 port_descr = match.group("port_descr").strip()
                 system_name = match.group("system_name").strip()
                 system_descr = match.group("system_descr").strip()
                 if bool(port_descr):
                     neighbor["remote_port_description"] = port_descr
                 if bool(system_name):
                     neighbor["remote_system_name"] = system_name
                 if bool(system_descr):
                     neighbor["remote_system_description"] = system_descr
                 neighbors += [neighbor]
             if neighbors:
                 r += [{
                     "local_interface": iface["interface"],
                     "neighbors": neighbors
                 }]
     return r