Example #1
0
 def handle(self, input, addresses, jobs, *args, **options):
     self.addresses = set()
     # Direct addresses
     for a in addresses:
         if is_ipv4(a):
             self.addresses.add(a)
     # Read addresses from files
     if input:
         for fn in input:
             try:
                 with open(fn) as f:
                     for line in f:
                         line = line.strip()
                         if is_ipv4(line):
                             self.addresses.add(line)
             except OSError as e:
                 self.die("Cannot read file %s: %s\n" % (fn, e))
     # Ping
     if config.features.use_uvlib:
         from tornaduv import UVLoop
         self.stderr.write("Using libuv\n")
         tornado.ioloop.IOLoop.configure(UVLoop)
     self.ioloop = IOLoop.current()
     self.ping = Ping(io_loop=self.ioloop)
     self.jobs = jobs
     self.queue = tornado.queues.Queue(self.jobs)
     for i in range(self.jobs):
         self.ioloop.spawn_callback(self.ping_worker)
     self.ioloop.run_sync(self.ping_task)
Example #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
Example #3
0
 def handle(self, input, addresses, jobs, community, oid, timeout, convert,
            version, *args, **options):
     self.addresses = set()
     # Direct addresses
     for a in addresses:
         if is_ipv4(a):
             self.addresses.add(a)
     # Read addresses from files
     if input:
         for fn in input:
             try:
                 with open(fn) as f:
                     for line in f:
                         line = line.strip()
                         if is_ipv4(line):
                             self.addresses.add(line)
             except OSError as e:
                 self.die("Cannot read file %s: %s\n" % (fn, e))
     # @todo: Add community oid check
     if not community:
         community = [self.DEFAULT_COMMUNITY]
     # Ping
     self.ioloop = IOLoop.current()
     self.jobs = jobs
     self.convert = convert
     self.version = version
     self.queue = tornado.queues.Queue(self.jobs)
     for i in range(self.jobs):
         self.ioloop.spawn_callback(self.poll_worker, community, oid,
                                    timeout, version)
     self.ioloop.run_sync(self.poll_task)
Example #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
Example #5
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
Example #6
0
 def execute(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 = 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"):
             for c in match.group("caps").split(","):
                 c = c.strip()
                 if c:
                     caps |= {
                         "Other": 1,
                         "Repeater": 2,
                         "Bridge": 4,
                         "Access Point": 8,
                         "Router": 16,
                         "Telephone": 32,
                         "Cable Device": 64,
                         "Station only": 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 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
         r += [{"local_interface": i[0], "neighbors": [neighbor]}]
     return r
Example #7
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
Example #8
0
    def execute_cli(self):
        r = []
        data = []
        try:
            v = self.cli("show lldp neighbors")
        except self.CLISyntaxError:
            raise self.NotSupportedError()
        v = v.replace("\n\n", "\n")
        for l in parse_table(v):
            if not l[0]:
                data[-1] = [s[0] + s[1] for s in zip(data[-1], l)]
                continue
            data += [l]

        for d in data:
            try:
                ifname = self.profile.convert_interface_name(d[0])
            except ValueError:
                continue
            v = self.cli("show lldp neighbors %s" % ifname)
            match = self.rx_neighbor.search(v)
            chassis_id = match.group("chassis_id").strip()
            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").strip()
            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
            capabilities = match.group("caps")
            caps = sum([self.CAPS[s.strip()] for s in capabilities.split(",")])
            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,
            }
            system_name = match.group("system_name").strip()
            if system_name:
                neighbor["remote_system_name"] = system_name
            system_descr = match.group("system_descr").strip()
            if system_descr:
                neighbor["remote_system_description"] = system_descr
            port_descr = match.group("port_descr").strip()
            if port_descr:
                neighbor["remote_port_description"] = port_descr
            r += [{"local_interface": ifname, "neighbors": [neighbor]}]

        return r
Example #9
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
         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
Example #10
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
Example #11
0
File: params.py Project: 0pt1on/noc
 def is_static(svc):
     if ":" not in svc:
         return False
     p = svc.split(":")
     if len(p) != 2:
         return False
     return is_ipv4(p[0]) and is_int(p[1])
Example #12
0
def loop():
    sf = SocketFactory()
    ps4 = Ping4Socket(sf)
    ps6 = Ping6Socket(sf)
    print "Running socket factory"
    t = threading.Thread(target=sf.run)
    t.setDaemon(True)
    t.start()
    print "READY"
    while True:
        try:
            ip = raw_input("IP> ")
        except EOFError:
            print "%% STOP"
            sys.exit(0)
        ip = ip.strip()
        if not ip:
            continue
        if "*" in ip:
            ip, count = ip.split("*")
            ip = ip.strip()
            try:
                count = int(count.strip())
            except ValueError:
                print "%% ERROR: Invald count"
        else:
            count = 1
        if not is_ipv4(ip) and not is_ipv6(ip):
            print "%% ERROR: Invalid IP address"
            continue
        sock = ps6 if ":" in ip else ps4
        for i in range(count):
            sock.ping(ip, count=3, callback=cb)
Example #13
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)
Example #14
0
 def execute(self, address, count=None, source_address=None, size=None,
 df=None, vrf=None):
     cmd = "ping"
     if is_ipv4(address):
         cmd += " ip"
     else:
         cmd += " ipv6"
     if vrf:
         cmd += " vrf %s" % vrf
     cmd += " %s" % address
     if count:
         cmd += " %d" % int(count)
     if source_address:
         cmd += " source address %s" % source_address
     if size:
         cmd += " data-size %d" % int(size)
     match = self.rx_result.search(self.cli(cmd))
     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_result1.search(s)
         return {
             "success": match.group("success"),
             "count": match.group("count")
         }
Example #15
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)
Example #16
0
 def get_ns_name(cls, ns):
     """Add missed '.' to the end of NS name, if given as FQDN"""
     name = ns.name.strip()
     if not is_ipv4(name) and not name.endswith("."):
         return name + "."
     else:
         return name
Example #17
0
 def get_avail_metrics(self, metrics):
     if not self.credentials["path"]:
         return
     check_id = 999
     check_rtt = 998
     for m in metrics:
         if m.metric == "Check | Result":
             check_id = m.id
         if m.metric == "Check | RTT":
             check_rtt = m.id
     for ip in self.credentials["path"].split(","):
         if is_ipv4(ip.strip()):
             result = self.scripts.ping(address=ip)
             self.set_metric(
                 id=check_id,
                 metric="Check | Result",
                 path=("ping", ip),
                 value=bool(result["success"]),
                 multi=True,
             )
             if result["success"] and check_rtt != 998:
                 self.set_metric(
                     id=check_rtt,
                     metric="Check | RTT",
                     path=("ping", ip),
                     value=bool(result["success"]),
                 )
Example #18
0
File: ping.py Project: skripkar/noc
 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")
         }
Example #19
0
 def get_neighbor(self, n):
     nn = self.get_neighbor_by_hostname(n)
     if nn:
         return nn
     if is_ipv4(n):
         return self.get_neighbor_by_ip(n)
     elif is_mac(n):
         return self.get_neighbor_by_mac(n)
     else:
         return None
Example #20
0
File: views.py Project: 0pt1on/noc
 def interpolate_ipv4(s):
     p = s.split(".")
     if len(p) > 4:
         return None
     elif len(p) < 4:
         p += ["0"] * (4 - len(p))
     s = ".".join(p)
     if not is_ipv4(s):
         return None
     return s
Example #21
0
File: ping.py Project: skripkar/noc
 def execute(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()
Example #22
0
File: ping.py Project: skripkar/noc
 def execute(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")
         }
Example #23
0
File: views.py Project: 0pt1on/noc
 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
Example #24
0
File: base.py Project: skripkar/noc
 def parse_iproute(self, tokens):
     """
     create iproute default 10.254.10.129 1
     create iproute 10.0.0.0/255.252.0.0 null0
     create iproute 10.125.0.0/255.255.255.0 10.125.0.1 1 primary
     """
     if tokens[2] == "default":
         prefix = "0.0.0.0/0"
     else:
         net, mask = tokens[2].split("/")
         prefix = str(IPv4(net, netmask=mask))
     f = self.get_static_route_fact(prefix)
     if is_ipv4(tokens[3]):
         f.next_hop = tokens[3]
     else:
         f.interface = tokens[3]
Example #25
0
 def resolve_addresses(self, addr_list, default_port):
     """
     Parses string and returns a list of (ip,port)
     :param addr_list: Comma-separared list of addresses in form:
                       * ip
                       * ip:port
                       * interface
                       * interface:port
     :param default_port:
     :return:
     """
     r = []
     for x in addr_list.split(","):
         x = x.strip()
         if not x:
             continue
         if ":" in x:  # Implicit port notation
             x, port = x.split(":", 1)
             if is_int(port):
                 port = int(port)
             else:
                 import socket
                 try:
                     port = socket.getservbyname(port)
                 except socket.error:
                     raise Exception("Invalid port: %s" % port)
         else:
             port = int(default_port)
         if port <= 0 or port > 65535:
             raise Exception("Invalid port: %s" % port)
         if is_ipv4(x):
             r += [(x, port)]
             continue
         if USE_NETIFACES:  # Can resolve interface names
             try:
                 a = netifaces.ifaddresses(x)
             except ValueError:
                 raise Exception("Invalid interface '%s'" % x)
             try:
                 x = a[2][0]["addr"]
             except (IndexError, KeyError):
                 raise Exception("No ip address for interface: '%s' found" %
                                 x)
             r += [(x, port)]
             continue
         raise Exception("Cannot resolve address '%s'" % x)
     return r
Example #26
0
 def on_ipv4_route(self, tokens):
     """
     ip route-static 0.0.0.0 0.0.0.0 172.20.66.30 preference 30
     @todo ip route-static 10.10.10.0 255.255.254.0 Vlanif7 10.10.100.1
     ip route-static vpn-instance vpn1 1.1.1.1 255.255.255.255 10.10.10.10
     """
     if tokens[2] == "vpn-instance":
         p = IPv4(tokens[4], netmask=tokens[5])
         nh = tokens[6]
     else:
         p = IPv4(tokens[2], netmask=tokens[3])
         nh = tokens[4]
     sf = self.get_static_route_fact(str(p))
     # rest = tokens[3].split()
     # nh = rest.pop(0)
     if is_ipv4(nh):
         sf.next_hop = nh
Example #27
0
 def resolve_address(self, s):
     """
     Resolve interface names to IP addresses
     :param s: Interface name or IPv4 address
     :return:
     """
     if is_ipv4(s):
         return s
     if USE_NETIFACES:
         try:
             a = netifaces.ifaddresses(s)
         except ValueError:
             raise Exception("Invalid interface '%s'" % s)
         try:
             return a[2][0]["addr"]
         except (IndexError, KeyError):
             raise Exception("No ip address for interface: '%s' found" % s)
     raise Exception("Cannot resolve address '%s'" % s)
Example #28
0
    def resolve_expression(cls, s):
        """
        Resolve expression to a list of object.

        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 type(s) in (int, long, str, unicode):
            s = [s]
        if type(s) != list:
            raise ValueError("list required")
        objects = set()
        for so in s:
            if not isinstance(so, six.string_types):
                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)
Example #29
0
File: lldp.py Project: skripkar/noc
 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)
Example #30
0
File: base.py Project: 0pt1on/noc
 def on_ipv4_route(self, tokens):
     p = IPv4(tokens[0], netmask=tokens[1])
     sf = self.get_static_route_fact(str(p))
     rest = tokens[2].split()
     nh = rest.pop(0)
     if is_ipv4(nh):
         sf.next_hop = nh
     else:
         iface = self.convert_interface_name(nh)
         if iface.startswith("Nu"):
             sf.discard = True
         else:
             sf.interface = iface
     if rest and is_int(rest[0]):
         sf.distance = rest.pop(0)
     while rest:
         if rest[0] == "name":
             sf.description = rest[1]
             rest = rest[2:]
         elif rest[0] == "tag":
             sf.tag = rest[1]
             rest = rest[2:]
         else:
             break