Ejemplo n.º 1
0
 def usage(self):
     if self.afi == "4":
         size = IPv4(self.prefix).size
         if not size:
             return 100.0
         n_ips = Address.objects.filter(prefix=self).count()
         n_pfx = sum(
             IPv4(p).size for p in Prefix.objects.filter(parent=self).only(
                 "prefix").values_list("prefix", flat=True))
         if n_ips:
             if size > 2:  # Not /31 or /32
                 size -= 2  # Exclude broadcast and network
         return float(n_ips + n_pfx) * 100.0 / float(size)
     else:
         return None
Ejemplo n.º 2
0
 def forwards(self):
     PrefixTable = db.mock_model(model_name="PrefixTable",
                                 db_table="main_prefixtable",
                                 db_tablespace="",
                                 pk_field_name="id",
                                 pk_field_type=models.AutoField)
     db.add_column(
         "sa_activator", "prefix_table",
         models.ForeignKey(PrefixTable,
                           verbose_name=_("Prefix Table"),
                           null=True,
                           blank=True))
     # Migrate data
     for id, name, ip, to_ip in db.execute(
             "SELECT id, name, ip, to_ip FROM sa_activator"):
         pt_name = "Activator::%s" % name
         db.execute(
             """
             INSERT INTO main_prefixtable(name)
             VALUES(%s)
             """, [pt_name])
         pt_id, = db.execute(
             "SELECT id FROM main_prefixtable WHERE name = %s",
             [pt_name])[0]
         for p in IPv4.range_to_prefixes(ip, to_ip):
             db.execute(
                 """
                 INSERT INTO main_prefixtableprefix(table_id, afi, prefix)
                 VALUES(%s, '4', %s)
                 """, [pt_id, p.prefix])
         db.execute(
             "UPDATE sa_activator SET prefix_table_id=%s WHERE id=%s",
             [pt_id, id])
Ejemplo n.º 3
0
    def execute(self):

        data = self.profile.var_data(self, "/setup_get.cgi")
        ip = data["ip"].encode('UTF8')
        mask = IPv4.netmask_to_len(data["mask"].encode('UTF8'))

        iface = {
            "name":
            'Fa1',
            "admin_status":
            True,
            "oper_status":
            True,
            "type":
            "physical",
            "description":
            data["location"].encode('UTF8'),
            "mac":
            data["mac"].encode('UTF8'),
            "subinterfaces": [{
                "name": 'Fa1',
                "admin_status": True,
                "oper_status": True,
                "type": "physical",
                "description": data["hostname"].encode('UTF8'),
                "mac": data["mac"].encode('UTF8'),
                "enabled_afi": ["IPv4"],
                "ipv4_addresses": ["%s/%s" % (ip, mask)]
            }]
        }
        return [{"interfaces": [iface]}]
Ejemplo n.º 4
0
 def on_interface_address(self, tokens):
     ip = str(IPv4(tokens[0], netmask=tokens[1]))
     si = self.get_current_subinterface()
     if len(tokens) > 2 and tokens[2] == "secondary":
         si.ipv4_addresses += [ip]
     else:
         si.ipv4_addresses = [ip] + si.ipv4_addresses
     si.add_afi("IPv4")
Ejemplo n.º 5
0
 def get_ipaddr(self, name):
     try:
         v = self.cli("show interface " + name)
     except self.CLISyntaxError:
         return
     match = self.rx_ip.match(v)
     if match:
         return [
             IPv4(match.group("ip"), netmask=match.group("mask")).prefix
         ]
Ejemplo n.º 6
0
    def execute(self):
        sw = self.scripts.get_switchport()
        ports = self.scripts.get_interface_status()
        mv = self.rx_mv.search(self.cli("show vlan", cached=True))
        if mv:
            mv = int(mv.group("mv"))
        else:
            mv = 1
        interfaces = []
        for p in ports:
            ifname = p['interface']
            i = {
                "name": ifname,
                "type": "physical",
                "oper_status": p['status'],
                "enabled_protocols": [],
                "subinterfaces": [{
                    "name": ifname,
                    "oper_status": p['status'],
                    # "ifindex": 1,
                    "enabled_afi": ['BRIDGE']
                }]
            }
            for p1 in sw:
                if p1['interface'] == ifname:
                    i['subinterfaces'][0]['tagged_vlans'] = p1['tagged']
                    if 'untagged' in p1:
                        i['subinterfaces'][0]['untagged_vlan'] = p1['untagged']
            interfaces += [i]
        match = self.rx_swi.search(self.cli("show switch"))
        if match:
            i = {
                "name": "System",
                "type": "SVI",
                "oper_status": True,
                "admin_status": True,
                "enabled_protocols": [],
                "subinterfaces": [{
                    "name": "System",
                    "oper_status": True,
                    "admin_status": True,
                    "mac": match.group("mac"),
                    "vlan_ids": [mv],
                    "enabled_afi": ['IPv4']
                }]
            }
            addr = match.group("ip")
            mask = match.group("mask")
            ip_address = "%s/%s" % (addr, IPv4.netmask_to_len(mask))
            i['subinterfaces'][0]["ipv4_addresses"] = [ip_address]
            interfaces += [i]

        return [{"interfaces": interfaces}]
Ejemplo n.º 7
0
 def get_rip_addresses(self):
     """
     Returns set of IP addresses of RIP interfaces
     :return: set of ip addresses
     :rtype: set
     """
     try:
         v = self.cli("show router rip", cached=True)
     except self.CLISyntaxError:
         return set()
     return set(IPv4(match.group("ip"), netmask=match.group("mask")).prefix
         for match in self.rx_rip_status.finditer(v)
         if match.group("direction").lower() != "none")
Ejemplo n.º 8
0
 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]
Ejemplo n.º 9
0
 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
Ejemplo n.º 10
0
    def execute(self):
        iface = {}
        interfaces = []
        step = len(self.objstr)
        lines = self.cli("walkMIB " +
                         " ".join(self.objstr.keys())).split("\n")[:-1]
        sh_ip = self.cli("show ip")

        try:
            sh_ospf = self.cli("show ip ospf interface")
        except:
            sh_ospf = False

        portchannel_members = {}  # member -> (portchannel, type)

        for pc in self.scripts.get_portchannel():
            i = pc["interface"]
            t = pc["type"] == "L"
            for m in pc["members"]:
                portchannel_members[m] = (i, t)

        pvm = {}
        switchports = {}
        vlans = self.scripts.get_vlans()
        if vlans:
            for sp in self.scripts.get_switchport():
                switchports[sp["interface"]] = (sp["untagged"] if "untagged"
                                                in sp else None, sp["tagged"])

        i = 0
        for s in range(len(lines) / step):
            for str in lines[i:i + step]:
                leaf = str.split(".")[0]
                val = str.split("=")[1].lstrip()
                if leaf == "ifPhysAddress":
                    if not val:
                        continue
                    iface[self.objstr[leaf]] = val.rstrip().replace(" ", ":")
                elif leaf == "ifType":
                    iface[self.objstr[leaf]] = self.iftypes[val]
                elif leaf[-6:] == "Status":
                    iface[self.objstr[leaf]] = val == "1"
                else:
                    iface[self.objstr[leaf]] = val
            ifname = iface['name']
            sub = iface.copy()
            ifindex = str.split("=")[0].split(".")[1].rstrip()
            sub["snmp_ifindex"] = int(ifindex)
            sub["enabled_afi"] = []
            del sub["type"]

            for l in sh_ip.split("\n"):
                match = self.rx_ip.search(l)
                if match:
                    if match.group("name") == sub["name"]:
                        sub["enabled_afi"] += ["IPv4"]
                        sub["ipv4_addresses"] = [
                            IPv4(match.group("ip"),
                                 netmask=match.group("mask")).prefix
                        ]
                        if sh_ospf:
                            for o in sh_ospf.split("\n"):
                                if o.split():
                                    if o.split()[0] == match.group("ip"):
                                        sub["is_ospf"] = True
            if ifname in switchports and not ifname in portchannel_members:
                sub["enabled_afi"] += ["BRIDGE"]
                u, t = switchports[ifname]
                if u:
                    sub["untagged_vlan"] = u
                if t:
                    sub["tagged_vlans"] = t

            iface["subinterfaces"] = [sub]
            interfaces += [iface]
            iface = {}
            i = i + step
        return [{"interfaces": interfaces}]
Ejemplo n.º 11
0
 def execute(self):
     interfaces = []
     ospfs = self.get_ospfint()
     types = {
         "L": 'loopback',
         "E": 'physical',
         "G": 'physical',
         "T": 'physical',
         "M": 'management',
         "R": 'aggregated',
         "P": 'aggregated'
     }
     v = self.cli("show interface")
     for s in v.split("\nInterface "):
         match = self.rx_int.search(s)
         if match:
             ifname = match.group('interface')
             if ifname in ['Virtual254', 'Tunnel0', 'Tunnel1']:
                 continue
             a_stat = match.group('admin_status').lower() == "up"
             o_stat = match.group('oper_status').lower() == "up"
             alias = match.group('alias')
             match = self.rx_mac.search(s)
             if match:
                 mac = match.group('mac')
             sub = {
                 "name": ifname,
                 "admin_status": a_stat,
                 "oper_status": o_stat,
                 "description": alias,
                 "mac": mac,
                 "enabled_afi": [],
                 "enabled_protocols": []
             }
             match = self.rx_ip.search(s)
             if match:
                 ip = IPv4(match.group('ip'),
                           netmask=match.group('mask')).prefix
                 sub['ipv4_addresses'] = [ip]
                 sub['enabled_afi'] += ["IPv4"]
             match = self.rx_vlan.search(s)
             if match:
                 vlan = match.group('vlan')
                 sub['vlan_ids'] = [vlan]
             if alias in ospfs:
                 sub['enabled_protocols'] += ["OSPF"]
             phys = ifname.find('.') == -1
             if phys:
                 iface = {
                     "name": ifname,
                     "admin_status": a_stat,
                     "oper_status": o_stat,
                     "description": alias,
                     "type": types[ifname[0]],
                     "mac": mac,
                     'subinterfaces': [sub]
                 }
                 interfaces.append(iface)
             else:
                 if interfaces[-1]['name'] == interfaces[-1][
                         'subinterfaces'][-1]['name']:
                     interfaces[-1]['subinterfaces'] = [sub]
                 else:
                     interfaces[-1]['subinterfaces'] += [sub]
         else:
             continue
     return [{"interfaces": interfaces}]
Ejemplo n.º 12
0
    def execute(self):
        try:
            c = self.cli("show ip protocols")
        except self.CLISyntaxError:
            c = ""

        bgp = []
        bgp_enable = self.rx_bgp_gs.search(c) is not None
        if bgp_enable:
            try:
                c_if = self.cli("show ip bgp interface")
            except self.CLISyntaxError:
                c_if = ""
            for match in self.rx_bgp.finditer(c_if):
                bgp += [match.group("ipif")]

        ospf = []
        ospf_enable = self.rx_ospf_gs.search(c) is not None
        if ospf_enable:
            try:
                c_if = self.cli("show ip ospf interface")
            except self.CLISyntaxError:
                c_if = ""
            for match in self.rx_ospf.finditer(c_if):
                ospf += [match.group("ipif")]

        ospf3 = []
        ospf3_enable = self.rx_ospf3_gs.search(c) is not None
        if ospf3_enable:
            try:
                c_if = self.cli("show ip ospf3 interface")
            except self.CLISyntaxError:
                c_if = ""
            for match in self.rx_ospf3.finditer(c_if):
                ospf3 += [match.group("ipif")]

        rip = []
        rip_enable = self.rx_rip_gs.search(c) is not None
        if rip_enable:
            try:
                c_if = self.cli("show ip rip interface")
            except self.CLISyntaxError:
                c_if = ""
            for match in self.rx_rip.finditer(c_if):
                rip += [match.group("ipif")]

        ripng = []
        ripng_enable = self.rx_ripng_gs.search(c) is not None
        if ripng_enable:
            try:
                c_if = self.cli("show ip ripng interface")
            except self.CLISyntaxError:
                c_if = ""
            for match in self.rx_ripng.finditer(c_if):
                ripng += [match.group("ipif")]

        dvmrp = []
        dvmrp_enable = self.rx_dvmrp_gs.search(c) is not None
        if dvmrp_enable:
            try:
                c_if = self.cli("show ip dvmrp interface")
            except self.CLISyntaxError:
                c_if = ""
            for match in self.rx_dvmrp.finditer(c_if):
                dvmrp += [match.group("ipif")]

        pim = []
        pim_enable = self.rx_pim_gs.search(c) is not None
        if pim_enable:
            try:
                c_if = self.cli("show ip pim interface")
            except self.CLISyntaxError:
                c_if = ""
            for match in self.rx_pim.finditer(c_if):
                pim += [match.group("ipif")]

        isis = []
        isis_enable = self.rx_isis_gs.search(c) is not None
        if isis_enable:
            try:
                c_if = self.cli("show ip isis interface")
            except self.CLISyntaxError:
                c_if = ""
            for match in self.rx_isis.finditer(c_if):
                isis += [match.group("ipif")]

        lldp = []
        try:
            c = self.cli("show lldp local-system")
        except self.CLISyntaxError:
            c = ""
        lldp_enable = self.rx_lldp_gs.search(c) is not None
        if lldp_enable:
            try:
                c = self.cli("show lldp config")
            except self.CLISyntaxError:
                c = ""
            for match in self.rx_lldp.finditer(c):
                lldp += [match.group("port")]

        udld = []
        try:
            c = self.cli("show udld configuration")
        except self.CLISyntaxError:
            c = ""
        udld_enable = self.rx_udld_gs.search(c) is not None
        if udld_enable:
            try:
                c = self.cli("show udld status port")
            except self.CLISyntaxError:
                c = ""
            for match in self.rx_udld.finditer(c):
                udld += [match.group("port")]

        r = []
        try:
            v = self.cli("show interfaces")
        except self.CLISyntaxError:
            raise self.NotSupportedError()
        i = {
            "forwarding_instance": "default",
            "interfaces": [],
            "type": "physical"
        }
        switchports = {}
        for swp in self.scripts.get_switchport():
            switchports[swp["interface"]] = (swp["untagged"] if "untagged"
                                             in swp else None, swp["tagged"])

        portchannel_members = {}
        for pc in self.scripts.get_portchannel():
            i = pc["interface"]
            print i
            t = pc["type"] == "L"
            print t
            for m in pc["members"]:
                portchannel_members[m] = (i, t)
            n = {}
            iface = "Ag %s" % i
            n["name"] = iface
            n["admin_status"] = True
            n["oper_status"] = True
            n["description"] = ""
            n["subinterfaces"] = [{
                "name": iface,
                "admin_status": True,
                "oper_status": True,
                "enabled_afi": ["BRIDGE"],
                "description": "",
            }]
            if switchports[iface][1]:
                n["subinterfaces"][0]["tagged_vlans"] = switchports[iface][1]
            if switchports[iface][0]:
                n["subinterfaces"][0]["untagged_vlan"] = switchports[iface][0]
            n["type"] = "aggregated"
            r += [n]
        v = "\n" + v

        for s in self.rx_line.split(v)[1:]:
            n = {}
            enabled_protocols = []
            match = self.rx_name.search(s)
            if not match:
                continue
            n["name"] = match.group("name")
            iface = n["name"]
            data1 = self.cli("show lldp %s local-port" % iface)
            for match1 in self.rx_ifindex.finditer(data1):
                ifindex = match1.group("ifindex")
            if iface not in portchannel_members:
                match = self.rx_mac_local.search(s)
                if not match:
                    continue
                n["mac"] = match.group("mac")
                match = self.rx_oper_status.search(s)
                if not match:
                    continue
                n["oper_status"] = match.group("status")
                status = match.group("status").lower() == "up"
                n["admin_status"] = match.group("status")
                n["subinterfaces"] = [{
                    "name": iface,
                    "admin_status": True,
                    "oper_status": True,
                    "enabled_afi": ["BRIDGE"],
                    "mac": n["mac"],
                    "snmp_ifindex": ifindex,
                    "description": ""
                }]
                if switchports[iface][1]:
                    n["subinterfaces"][0]["tagged_vlans"] = switchports[iface][
                        1]
                if switchports[iface][0]:
                    n["subinterfaces"][0]["untagged_vlan"] = switchports[
                        iface][0]
                if lldp_enable and iface in lldp:
                    enabled_protocols += ["LLDP"]
                if udld_enable and iface in udld:
                    enabled_protocols += ["UDLD"]
                n["enabled_protocols"] = enabled_protocols
                n["type"] = "physical"
                r += [n]
            if iface in portchannel_members:
                ai, is_lacp = portchannel_members[iface]
                ai = "Ag %s" % ai
                n["aggregated_interface"] = ai
                n["enabled_protocols"] = ["LACP"]
                match = self.rx_mac_local.search(s)
                if not match:
                    continue
                n["mac"] = match.group("mac")
                match = self.rx_oper_status.search(s)
                if not match:
                    continue
                n["oper_status"] = match.group("status")
                status = match.group("status").lower() == "up"
                n["admin_status"] = match.group("status")
                n["subinterfaces"] = [{
                    "name": iface,
                    "admin_status": True,
                    "oper_status": True,
                    "enabled_afi": ["BRIDGE"],
                    "mac": n["mac"],
                    "snmp_ifindex": ifindex,
                    "description": ""
                }]
                n["type"] = "physical"
                r += [n]
        ip_int = self.cli("show ip interface")
        for match in self.rx_sh_svi.finditer(ip_int):
            ifname = match.group("name")
            ip = match.group("ip")
            enabled_afi = []
            enabled_protocols = []
            if ":" in ip:
                ip_interfaces = "ipv6_addresses"
                enabled_afi += ["IPv6"]
                ip = IPv6(ip, netmask=match.group("mask")).prefix
                ip_list = [ip]
            else:
                ip_interfaces = "ipv4_addresses"
                enabled_afi += ["IPv4"]
                ip = IPv4(ip, netmask=match.group("mask")).prefix
                ip_list = [ip]
            vlan = match.group("vlan")
            a_stat = "UP"
            print ifname
            if ospf_enable and ifname in ospf:
                enabled_protocols += ["OSPF"]
            if ospf3_enable and ifname in ospf3:
                enabled_protocols += ["OSPF3"]
            if pim_enable and ifname in pim:
                enabled_protocols += ["PIM"]
            if ripng_enable and ifname in ripng:
                enabled_protocols += ["RIPng"]
            if dvmrp_enable and ifname in dvmrp:
                enabled_protocols += ["DVMRP"]
            if isis_enable and ifname in isis:
                enabled_protocols += ["ISIS"]
            if bgp_enable and ifname in bgp:
                enabled_protocols += ["BGP"]
            print ifname
            iface = {
                "name":
                ifname,
                "type":
                "SVI",
                "admin_status":
                True,
                "oper_status":
                True,
                "description":
                "",
                "subinterfaces": [{
                    "name": ifname,
                    "enabled_protocols": enabled_protocols,
                    "description": ifname,
                    "admin_status": True,
                    "oper_status": True,
                    "enabled_afi": enabled_afi,
                    ip_interfaces: ip_list,
                    "vlan_ids": ranges_to_list_str(vlan),
                }]
            }
            r += [iface]
        return [{"interfaces": r}]
Ejemplo n.º 13
0
 def execute(self):
     self.portchannel = self.scripts.get_portchannel()
     self.if_stp = []
     self.interfaces = []
     self.iface = {}
     self.subiface = {}
     self.parent = ""
     self.snmp_ifindex = 0
     for s in self.cli("ifconfig -v", cached=True).splitlines():
         match = self.rx_if_name.search(s)
         if match:
             self.snmp_ifindex += 1
             self.add_iface()
             flags = match.group("flags")
             self.iface["name"] = match.group("ifname")
             self.subiface["name"] = match.group("ifname")
             self.iface["admin_status"] = flags.startswith("UP,")
             self.subiface["admin_status"] = flags.startswith("UP,")
             self.subiface["enabled_afi"] = []
             self.subiface["mtu"] = int(match.group("mtu"))
             self.iface["snmp_ifindex"] = self.snmp_ifindex
             self.iface["enabled_protocols"] = []
             if "LOOPBACK" in flags:
                 self.iface["type"] = "loopback"
                 self.iface["oper_status"] = flags.startswith("UP,")
                 self.subiface["oper_status"] = flags.startswith("UP,")
             if "POINTOPOINT" in flags:
                 self.iface["type"] = "tunnel"
             continue
         match = self.rx_if_descr.search(s)
         if match:
             self.iface["descriptions"] = match.group("descr")
             self.subiface["descriptions"] = match.group("descr")
             continue
         match = self.rx_if_mac.search(s)
         if match:
             self.iface["mac"] = match.group("mac")
             self.subiface["mac"] = match.group("mac")
             self.iface["type"] = "physical"
             continue
         match = self.rx_if_inet.search(s)
         if match:
             ip = match.group("inet")
             netmask = match.group("netmask")
             mask = IPv4._to_prefix(int(netmask, 16), 32).address
             mask = IPv4.netmask_to_len(mask)
             ipv4_addr = "%s/%s" % (ip, mask)
             if "ipv4_addresses" in self.subiface:
                 self.subiface["ipv4_addresses"] += [ipv4_addr]
             else:
                 self.subiface["ipv4_addresses"] = [ipv4_addr]
                 self.subiface["enabled_afi"] += ["IPv4"]
             continue
         match = self.rx_if_inet6.search(s)
         if match:
             ipv6 = match.group("inet6")
             if ipv6.find("%") >= 0:
                 continue
             prefixlen = match.group("prefixlen")
             ipv6_addr = "%s/%s" % (ipv6, prefixlen)
             if "ipv6_addresses" in self.subiface:
                 self.subiface["ipv6_addresses"] += [ipv6_addr]
             else:
                 self.subiface["ipv6_addresses"] = [ipv6_addr]
                 self.subiface["enabled_afi"] += ["IPv6"]
             continue
         match = self.rx_if_status.search(s)
         if match:
             self.iface["oper_status"] = True
             self.subiface["oper_status"] = True
             continue
         match = self.rx_if_vlan.search(s)
         if match:
             self.subiface.update({"vlan_ids": [int(match.group("vlan"))]})
             self.parent = match.group("parent")
             continue
         for i in self.portchannel:
             if self.iface["name"] == i["interface"]:
                 self.iface["type"] = "aggregated"
                 #self.subiface["enabled_afi"] = ["BRIDGE"]
             if self.iface["name"] in i["members"]:
                 if i["type"] == "L" and \
                 not "LACP" in self.iface["enabled_protocols"]:
                     self.iface["enabled_protocols"] += ["LACP"]
                 self.iface["aggregated_interface"] = i["interface"]
         match = self.rx_if_wlan.search(s)
         if match:
             self.parent = "IEEE 802.11"
             continue
         match = self.rx_if_bridge.search(s)
         if match:
             self.iface["type"] = "SVI"
             if not "BRIDGE" in self.subiface["enabled_afi"]:
                 self.subiface["enabled_afi"] += ["BRIDGE"]
             continue
         match = self.rx_if_bridge_m.search(s)
         if match:
             ifname = match.group("ifname")
             continue
         match = self.rx_if_bridge_i.search(s)
         if match:
             caps = {
                 "name": ifname,
                 "ifindex": match.group("ifindex"),
                 "parent": self.iface["name"]
             }
             match = self.rx_if_bridge_s.search(s)
             if match:
                 caps["STP"] = True
             self.if_stp += [caps]
     self.add_iface()
     if len(self.if_stp) > 0:
         for i in self.interfaces:
             for s in self.if_stp:
                 if i["name"] == s["name"]:
                     # For verify
                     i["snmp_ifindex"] = int(s["ifindex"])
                     i["aggregated_interface"] = s["parent"]
                 if "STP" in s:
                     i["enabled_protocols"] += ["STP"]
     return [{"interfaces": self.interfaces}]
Ejemplo n.º 14
0
    def execute(self):
        ifaces = {}
        current = None
        is_bundle = False
        is_svi = False
        vlan_ids = []
        mac_svi = ""
        name_ = {}
        mac_ = {}
        snmp_ifindex_ = {}
        descr_ = {}
        stat_ = {}
        tagged_ = {}
        untagged_ = {}
        end_if = False

        # 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 = []
        seen = set()
        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"] = ifaces.values()
        r += [rr]
        # Return result
        return r
Ejemplo n.º 15
0
    def execute(self):
        rip = []
        try:
            c = self.cli('show ip rip int | inc ^Interface')
        except self.CLISyntaxError:
            c = ''

        c = c.strip('\n')
        for ii in c.split('\n'):
            ii = ii.lower()
            if ii.find('ve') > 0:
                ii = ii.replace('ve ', 've')
            else:
                ii = ii.replace('Eth ', '')
            if ii != '':
                ii = ii.split(' ')[1]
            rip += [ii]

        ospf = []
        try:
            c = self.cli('sh ip ospf int | inc ospf enabled')
        except self.CLISyntaxError:
            c = ''

        c = c.strip('\n')
        for ii in c.split('\n'):
            ii = ii.lower().split(',')[0]
            if ii.startswith('ve '):
                ii = ii.replace('ve ', 've')
                ii = ii.split(' ')[0]
            elif ii.startswith('v'):
                ii = ii.replace('v', 've')
                ii = ii.split(' ')[0]
            elif ii.startswith('loop'):
                ii = ii.replace('loopback ', 'lb')
                ii = ii.split(' ')[0]
            elif ii.startswith('lb'):
                ii = ii
                ii = ii.split(' ')[0]
            elif ii.startswith('tn'):
                ii = ii
                ii = ii.split(' ')[0]
            elif ii != '':
                ii = ii.split(' ')[1]
            self.debug(ii)
            ospf += [ii.strip()]

        pim = []
        try:
            c = self.cli('sh ip pim int | inc ^Int')
        except self.CLISyntaxError:
            c = ''

        if c != '':
            for ii in c.split('\n'):
                ii = ii.split(' ')[1]
                if ii.startswith('v'):
                    ii = ii.replace('v', 've')
                else:
                    ii = ii.replace('e', '')
                pim += [ii]

        dvmrp = []
        try:
            c = self.cli('sh ip dvmrp int | inc ^Int')
        except self.CLISyntaxError:
            c = ''

        if c != '':
            c = c.strip('\n')
            for ii in c.split('\n'):
                ii = ii.split(' ')[1]
                if ii.startswith('v'):
                    ii = ii.replace('v', 've')
                else:
                    ii = ii.replace('e', '')
                dvmrp += [ii]

        stp = []
        try:
            c = self.cli('show span | inc /')
        except self.CLISyntaxError:
            c = ''

        c = c.strip('\n')
        for ii in c.split('\n'):
            ii = ii.split(' ')[0]

        gvrp = []
        try:
            c = self.cli('show gvrp')
        except self.CLISyntaxError:
            c = ''

        igmp = []
        try:
            c = self.cli('sh ip igmp int | exc group:')
        except self.CLISyntaxError:
            c = ''

        c = c.strip('\n')
        for ii in c.split('\n'):
            ii = ii.strip()
            ii = ii.split(' ')[0]
            ii = ii.strip(':')
            if ii.startswith('v'):
                ii = ii.replace('v', 've')
            else:
                ii = ii.replace('e', '')
            if not ii.startswith("IGMP"):
                igmp += [ii]

        interfaces = []
        shrunvlan = self.cli('sh running-config vlan | excl tag-type')
        tagged = {}
        untagged = {}
        r = []
        for v in shrunvlan.split('!'):
            self.debug('\nPROCESSING:' + v + '\n')
            match = self.rx_vlan_list.findall(v)
            if match:
                tag = 1
                m2 = match
                for m in match:
                    self.debug('    m[0]:' + m[0] + '\n')
                    if not m[0]:
                        tag = 0
                        continue
                    if m[0].split()[0] == 'vlan':
                        vlan = int(m[0].split()[1])
                        continue
                    elif m[0][:3] == 've ':
                        ifc = ''.join(m[0].split())
                        if ifc in untagged:
                            untagged[ifc].append(vlan)
                        else:
                            untagged[ifc] = vlan
                        continue
                    elif not m[0].split()[0] == 'ethe':
                        continue
                    elif not m[1]:
                        ifc = m[0].split()[1]
                        if tag == 1:
                            if ifc in tagged:
                                tagged[ifc].append(vlan)
                            else:
                                tagged[ifc] = [vlan]
                        else:
                            untagged[ifc] = vlan
                    else:
                        first = m[0].split()[1].split('/')[1]
                        last = m[1].split()[1].split('/')[1]
                        for n in range(int(first), int(last) + 1):
                            ifc = m[0].split()[1].split('/')[0] + '/' + repr(n)
                            if tag == 1:
                                if ifc in tagged:
                                    tagged[ifc].append(vlan)
                                else:
                                    tagged[ifc] = [vlan]
                            else:
                                untagged[ifc] = vlan

        c = self.cli('sh int br | excl Port')
        c = c.strip('\n')
        for ii in c.split('\n'):
            if not ii.startswith('Port'):
                self.debug('\nPROCESSING LINE: ' + ii + '\n')
                ii = ii.lower()
                ii = ii.replace('disabled', ' disabled ')
                ii = ii.replace('disabn', ' disabled n')
                ii = ii.replace('up', ' up ')
                ii = ii.replace('  ', ' ')
                port = ii.split()
                if len(port) > 1:
                    ifname = port[0]
                    ift = ''
                    self.debug('INT :' + ifname + '\n')
                    if ifname.find('/') > 0:
                        ift = 'physical'
                        self.debug('FOUND PHYSICAL\n')
                    if ifname.find('e') > 0:
                        ift = 'SVI'
                        self.debug('FOUND VIRTUAL\n')
                    if ifname.find('b') > 0:
                        ift = 'loopback'
                        self.debug('FOUND LOOPBACK\n')
                    if ifname.find('g') > 0:
                        ift = 'management'
                        self.debug('FOUND MANAGEMENT\n')
                    if ifname.find('n') > 0:
                        ift = 'tunnel'
                    i = {
                        'name':
                        ifname,
                        'type':
                        ift,
                        'admin_status':
                        port[1] == 'up',
                        'oper_status':
                        port[1] == 'up',
                        'enabled_protocols': [],
                        'subinterfaces': [{
                            'name': ifname,
                            'admin_status': port[1] == 'up',
                            'oper_status': port[1] == 'up'
                        }]
                    }
                    if ift == 'SVI':
                        i['subinterfaces'][0].update(
                            {'vlan_ids': [untagged[ifname]]})
                        ipa = self.cli('show run int %s | inc ip addr' %
                                       ifname)
                        ipal = ipa.splitlines()
                        ip_address = []
                        for l in ipal:
                            l = l.strip()
                            self.debug('ip.split len:' + str(len(l.split())))
                            if len(l.split()) > 3:
                                ip_address.append(
                                    '%s/%s' %
                                    (l.split()[2],
                                     IPv4.netmask_to_len(l.split()[3])))
                            else:
                                ip_address.append(l.split()[2])

                        i['subinterfaces'][0].update({'enabled_afi': ['IPv4']})
                        i['subinterfaces'][0].update(
                            {'ipv4_addresses': ip_address})
                    if len(port) > 9:
                        desc = port[9]
                    else:
                        desc = ''
                    i['subinterfaces'][0].update({'description': desc})
                    if ift == 'physical':
                        i['subinterfaces'][0].update({'is_bridge': True})
                        if ifname in tagged:
                            i['subinterfaces'][0].update(
                                {'tagged_vlans': tagged[ifname]})
                        if ifname in untagged:
                            i['subinterfaces'][0].update(
                                {'untagged_vlan': untagged[ifname]})
                    l2protos = []
                    l3protos = []
                    if ifname in stp:
                        l2protos += ['STP']
                    if ifname in gvrp:
                        l2protos += ['GVRP']
                    i.update({'enabled_protocols': l2protos})
                    if ifname in rip:
                        l3protos += ['RIP']
                    if ifname in ospf:
                        l3protos += ['OSPF']
                    if ifname in pim:
                        l3protos += ['PIM']
                    if ifname in dvmrp:
                        l3protos += ['DVMRP']
                    if ifname in igmp:
                        l3protos += ['IGMP']
                    i['subinterfaces'][0].update(
                        {'enabled_protocols': l3protos})
                    interfaces += [i]

        return [{'interfaces': interfaces}]
Ejemplo n.º 16
0
    def execute(self):
        rip = []
        try:
            c = self.cli("show ip rip int | inc ^Interface")
        except self.CLISyntaxError:
            c = ""
        c = c.strip("\n")
        for ii in c.split("\n"):
            ii = ii.lower()
            if ii.find("ve") > 0:
                ii = ii.replace("ve ", "ve")
            else:
                ii = ii.replace("Eth ", "")
            if ii != '':
                ii = ii.split(" ")[1]
            rip += [ii]
        ospf = []
        try:
            c = self.cli("sh ip ospf int | inc OSPF enabled")
        except self.CLISyntaxError:
            c = ""
        c = c.strip("\n")
        for ii in c.split("\n"):
            ii = ii.lower().split(",")[0]
            if ii.startswith("ve "):
                ii = ii.replace("ve ", "ve")
            elif ii.startswith("v"):
                ii = ii.replace("v", "ve")
            elif ii.startswith("loop"):
                ii = ii.replace("loopback ", "lb")
            elif ii.startswith("lb"):
                ii = ii
            elif ii != '':
                ii = ii.split(" ")[1]
            ospf += [ii.strip()]
        pim = []
        try:
            c = self.cli("sh ip pim int | inc ^Int")
        except self.CLISyntaxError:
            c = ""
        if c != '':
            for ii in c.split("\n"):
                ii = ii.split(" ")[1]
                if ii.startswith("v"):
                    ii = ii.replace("v", "ve")
                else:
                    ii = ii.replace("e", "")
                pim += [ii]
        dvmrp = []
        try:
            c = self.cli("sh ip dvmrp int | inc ^Int")
        except self.CLISyntaxError:
            c = ""
        if c != '':
            c = c.strip("\n")
            for ii in c.split("\n"):
                ii = ii.split(" ")[1]
                if ii.startswith("v"):
                    ii = ii.replace("v", "ve")
                else:
                    ii = ii.replace("e", "")
                dvmrp += [ii]
        stp = []
        try:
            c = self.cli("show span | inc /")
        except self.CLISyntaxError:
            c = ""
        c = c.strip("\n")
        for ii in c.split("\n"):
            ii = ii.split(" ")[0]
        gvrp = []
        try:
            c = self.cli("show gvrp")
        except self.CLISyntaxError:
            c = ""
        igmp = []
        try:
            c = self.cli("sh ip igmp int | exc group:")
        except self.CLISyntaxError:
            c = ""
        c = c.strip("\n")
        for ii in c.split("\n"):
            ii = ii.strip()
            ii = ii.split(" ")[0]
            ii = ii.strip(":")
            if ii.startswith("v"):
                ii = ii.replace("v", "ve")
            else:
                ii = ii.replace("e", "")
            igmp += [ii]
        interfaces = []
        shrunvlan = self.cli("sh running-config vlan")
        tagged = {}
        untagged = {}
        r = []
        for v in shrunvlan.split('!'):
            match = self.rx_vlan_list.findall(v)
            if match:
                tag = 1
                m2 = match
                for m in match:
                    if not m[0]:
                        tag = 0
                        continue

                    if m[0].split()[0] == "vlan":
                        vlan = int(m[0].split()[1])
                        continue

                    elif m[0][:3] == "ve ":
                        ifc = ''.join(m[0].split())
                        if ifc in untagged:
                            untagged[ifc].append(vlan)
                        else:
                            untagged[ifc] = vlan
                        continue

                    elif not m[0].split()[0] == 'ethe':
                        continue

                    elif not m[1]:
                        ifc = m[0].split()[1]
                        if tag == 1:
                            if ifc in tagged:
                                tagged[ifc].append(vlan)
                            else:
                                tagged[ifc] = [vlan]
                        else:
                            untagged[ifc] = vlan

                    else:
                        first = m[0].split()[1].split('/')[1]
                        last = m[1].split()[1].split('/')[1]
                        for n in range(int(first), int(last) + 1):
                            ifc = m[0].split()[1].split('/')[0] + '/' + repr(n)
                            if tag == 1:
                                if ifc in tagged:
                                    tagged[ifc].append(vlan)
                                else:
                                    tagged[ifc] = [vlan]
                            else:
                                untagged[ifc] = vlan

        c = self.cli("sh int br | excl Port")
        c = c.strip("\n")
        for ii in c.split("\n"):
            ii = ii.lower()
            ii = ii.replace("disabled", " disabled ")
            ii = ii.replace("disabn", " disabled n")
            ii = ii.replace("up", " up ")
            ii = ii.replace("  ", " ")
            port = ii.split()
            if len(port) > 1:
                ifname = port[0]
                if ifname.find("/") > 0:
                    ift = "physical"
                if ifname.find("e") > 0:
                    ift = "SVI"
                if ifname.find("b") > 0:
                    ift = "loopback"
                if ifname.find("m") > 0:
                    ift = "management"
                i = {
                    "name":
                    ifname,
                    "type":
                    ift,
                    "admin_status":
                    port[1] == "up",
                    "oper_status":
                    port[1] == "up",
                    "enabled_protocols": [],
                    "subinterfaces": [{
                        "name": ifname,
                        "admin_status": port[1] == "up",
                        "oper_status": port[1] == "up"
                    }]
                }
                if ift == "SVI":
                    i['subinterfaces'][0].update(
                        {"vlan_ids": [untagged[ifname]]})
                    ipa = self.cli("show run int %s | inc ip addr" % ifname)
                    ipa = ipa.strip()
                    if len(ipa) > 1:
                        i['subinterfaces'][0].update({"enabled_afi": ["IPv4"]})
                        self.debug("ip.split len:" + str(len(ipa.split())))
                        if len(ipa.split()) > 3:
                            ip_address = "%s/%s" % (ipa.split()[2],
                                                    IPv4.netmask_to_len(
                                                        ipa.split()[3]))
                        else:
                            ip_address = ipa.split()[2]
                        i['subinterfaces'][0].update(
                            {"ipv4_addresses": [ip_address]})

                if len(port) > 9:
                    desc = port[9]
                else:
                    desc = ''
                i['subinterfaces'][0].update({"description": desc})
                if ift == "physical":
                    i['subinterfaces'][0].update({"is_bridge": True})
                    if ifname in tagged:
                        i['subinterfaces'][0].update(
                            {"tagged_vlans": tagged[ifname]})
                    if ifname in untagged:
                        i['subinterfaces'][0].update(
                            {"untagged_vlan": untagged[ifname]})
                l2protos = []
                l3protos = []
                if ifname in stp: l2protos += ["STP"]
                if ifname in gvrp: l2protos += ["GVRP"]
                i.update({"enabled_protocols": l2protos})
                # L3 protocols check:
                if ifname in rip: l3protos += ["RIP"]
                if ifname in ospf: l3protos += ["OSPF"]
                if ifname in pim: l3protos += ["PIM"]
                if ifname in dvmrp: l3protos += ["DVMRP"]
                if ifname in igmp: l3protos += ["IGMP"]
                i['subinterfaces'][0].update({"enabled_protocols": l3protos})

                interfaces += [i]
        return [{"interfaces": interfaces}]
Ejemplo n.º 17
0
 def wildcard(self):
     if self.afi == "4":
         return IPv4(self.prefix).wildcard.address
     else:
         return ""
Ejemplo n.º 18
0
 def size(self):
     if self.afi == "4":
         return IPv4(self.prefix).size
     else:
         return None
Ejemplo n.º 19
0
 def netmask(self):
     if self.afi == "4":
         return IPv4(self.prefix).netmask.address
     else:
         return None
Ejemplo n.º 20
0
 def broadcast(self):
     if self.afi == "4":
         return IPv4(self.prefix).last.address
     else:
         return None
Ejemplo n.º 21
0
    def execute(self):
        interfaces = []
        ospf_addresses = self.get_ospf_addresses()
        rip_addresses = self.get_rip_addresses()

        # Get portchannes
        portchannel_members = {}  # member -> (portchannel, type)
        with self.cached():
            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 portchannel members' details
        for m in portchannel_members:
            admin = self.get_admin_status(m)
            oper = self.scripts.get_interface_status(interface=m)[0]["status"]
            iface = {
                "name": m,
                "admin_status": admin,
                "oper_status": oper,
                "type": "physical",
                "subinterfaces": [],
                "aggregated_interface": portchannel_members[m][0],
                # @todo: description
            }
            if portchannel_members[m][1]:
                iface["enabled_protocols"] = ["LACP"]
            interfaces += [iface]

        # Get mac
        mac = self.scripts.get_chassis_id()[0]["first_chassis_mac"]

        # Get switchports
        for swp in self.scripts.get_switchport():
            admin = False
            if len(swp["members"]) > 0:
                for m in swp["members"]:
                    admin = self.get_admin_status(m)
                    if admin:
                        break
            else:
                admin = self.get_admin_status(swp["interface"])
            name = swp["interface"]
            iface = {
                "name": name,
                "type": "aggregated" if len(swp["members"]) > 0
                    else "physical",
                "admin_status": admin,
                "oper_status": swp["status"],
                "mac": mac,
                "subinterfaces": [{
                    "name": name,
                    "admin_status": admin,
                    "oper_status": swp["status"],
                    "enabled_afi": ["BRIDGE"],
                    "mac": mac,
                    #"snmp_ifindex": self.scripts.get_ifindex(interface=name)
                }]
            }
            if swp["tagged"]:
                iface["subinterfaces"][0]["tagged_vlans"] = swp["tagged"]
            try:
                iface["subinterfaces"][0]["untagged_vlan"] = swp["untagged"]
            except KeyError:
                pass
            if swp["description"]:
                iface["description"] = swp["description"]
                iface["subinterfaces"][0]["description"] = swp["description"]
            interfaces += [iface]

        # Get SVIs
        ipifarr = {}
        for match in self.rx_ipif.finditer(self.cli("show ip")):
            vid = int(match.group("vid"))
            ip = IPv4(match.group("ip"), netmask=match.group("mask")).prefix
            if vid not in ipifarr:
                ipifarr[vid] = [ip]
            else:
                ipifarr[vid].append(ip)
        for v in ipifarr.keys():
            iface = {
                "name": "vlan%d" % v if v else "Management",
                "mac": mac,  # @todo: get mgmt mac
                # @todo: get vlan name to form better description
                "description": "vlan%d" % v if v else "Outband management",
                "admin_status": True,  # always True, since inactive
                "oper_status": True,   # SVIs aren't shown at all
                "subinterfaces": [{
                    "name": "vlan%d" % v if v else "Management",
                    "description": "vlan%d" % v if v else "Outband management",
                    "admin_status": True,
                    "oper_status": True,
                    "enabled_afi": ["IPv4"],
                    "ipv4_addresses": ipifarr[v],
                    "mac": mac,
                    "enabled_protocols": []
                }]
            }
            if v == 0:  # Outband management
                iface["type"] = "management"
                # @todo: really get status
            else:
                iface["type"] = "SVI"
                iface["subinterfaces"][0]["vlan_ids"] = [v]
            for i in ipifarr[v]:
                if i in rip_addresses:
                    iface["subinterfaces"][0]["enabled_protocols"] += ["RIP"]
                if i in ospf_addresses:
                    iface["subinterfaces"][0]["enabled_protocols"] += ["OSPF"]
            interfaces += [iface]
        return [{"interfaces": interfaces}]
Ejemplo n.º 22
0
    def execute(self):
        ifaces = {}
        current = None
        is_bundle = False
        is_svi = False
        vlan_ids = []
        mac_svi = ""
        name_ = {}
        mac_ = {}
        snmp_ifindex_ = {}
        descr_ = {}
        stat_ = {}
        tagged_ = {}
        untagged_ = {}
        end_if = False

        # Tested only ES3510MA, ES3510, ES3526XAv2, ES3528M, ES3552M, ES4612
        if (self.match_version(platform__contains="4626")):
            raise self.NotSupportedError()

        # Get interface status
        for p in self.scripts.get_interface_status():
            intf = p["interface"]
            name_[intf] = intf
            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 LLDP
        lldp = set()
        try:
            buf = self.cli("sh lldp config")
        except self.CLISyntaxError:
            # On 3526S LLDP is not supported
            buf = ""
        for p in buf.splitlines():
            match = self.rx_lldp_35xx.match(p)
            if match:
                for v in buf.splitlines():
                    match = self.rx_lldp_ports_35xx.match(v)
                    if match:
                        lldp.add(
                            self.profile.convert_interface_name(
                                match.group("name")))

        # Get SVI interfaces on 4612
        if (self.match_version(platform__contains="4612")):
            for ls in self.cli("show ip interface").splitlines():
                match = self.rx_svi_name_stat_4612.search(ls)
                if match:
                    ip_addr = []
                    sub = {}
                    namesviif = match.group("name").upper()
                    stat = match.group("stat")

                match = self.rx_ip_if_4612.search(ls)
                if match:
                    ip = match.group("ip")
                    mask = match.group("mask")
                    ip_addr += [IPv4(ip, netmask=mask).prefix]

                if (ls.strip().startswith("Split")):
                    if not ip_addr:
                        continue
                    type = "SVI"
                    vlan_ids = [int(namesviif[5:])]
                    mac_svi = mac_[namesviif]
                    enabled_afi = ["IPv4"]
                    sub = {
                        "name": namesviif,
                        "admin_status": stat == "up",
                        "oper_status": stat == "up",
                        "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],
                    }

        # Dirty-hack 3510/3526/3528/3552 managment SVI interface
        if (self.match_version(platform__contains="3510")
                or self.match_version(platform__contains="3526")
                or self.match_version(platform__contains="3528")
                or self.match_version(platform__contains="2228N")
                or self.match_version(platform__contains="3552")
                or self.match_version(platform__contains="ECS4210")):

            # Dirty-hack 3510MA managment SVI interface
            if (self.match_version(platform__contains="3510MA")
                    or self.match_version(platform__contains="ECS4210")):
                for ls in self.cli("show ip interface").splitlines():
                    match = self.rx_svi_name_stat_3510MA.search(ls)
                    if match:
                        ip_addr = []
                        sub = {}
                        namesviif = match.group("name").upper()
                        a_stat = match.group("a_stat")
                        o_stat = match.group("o_stat")

                    match = self.rx_ip_if_3510MA.search(ls)
                    if match:
                        ip = match.group("ip")
                        mask = match.group("mask")
                        ip_addr = [IPv4(ip, netmask=mask).prefix]
                        type = "SVI"
                        enabled_afi = ["IPv4"]
                        vlan_ids = [int(namesviif[5:])]
                        if namesviif in mac_:
                            mac_svi = mac_[namesviif]
                        sub = {
                            "name": namesviif,
                            "admin_status": a_stat == "Up",
                            "oper_status": o_stat == "Up",
                            "enabled_afi": enabled_afi,
                            "ipv4_addresses": ip_addr,
                            "vlan_ids": vlan_ids,
                        }
                        if mac_svi:
                            sub["mac"] = mac_svi
                        ifaces[namesviif] = {
                            "name": namesviif,
                            "admin_status": a_stat == "Up",
                            "oper_status": o_stat == "Up",
                            "type": type,
                            "subinterfaces": [sub],
                        }
                        if mac_svi:
                            ifaces[namesviif]["mac"] = mac_svi

            # 3510/3526/3528/3552
            for ls in self.cli("show ip interface").splitlines():
                match = self.rx_ip_if_35.search(ls + "\n")
                if match:
                    ip = match.group("ip")
                    mask = match.group("mask")
                    namesviif = match.group("name")
                    ip_addr = IPv4(ip, netmask=mask).prefix
                    status = "Up"
                    type = "SVI"
                    enabled_afi = ["IPv4"]
                    vlan_ids = [int(namesviif[5:])]
                    if namesviif in mac_:
                        mac_svi = mac_[namesviif]
                    sub = {
                        "name": namesviif,
                        "admin_status": status == "Up",
                        "oper_status": status == "Up",
                        "enabled_afi": enabled_afi,
                        "ipv4_addresses": [ip_addr],
                        "vlan_ids": vlan_ids,
                    }
                    if mac_svi:
                        sub["mac"] = mac_svi
                    ifaces[namesviif] = {
                        "name": namesviif,
                        "admin_status": status == "Up",
                        "oper_status": status == "Up",
                        "type": type,
                        "subinterfaces": [sub],
                    }
                    if mac_svi:
                        ifaces[namesviif]["mac"] = mac_svi

        # Pre-process portchannel members
        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)

        # Simulate hard working

        # set name ifaces
        for current in name_:
            is_svi = current.startswith("VLAN")
            if is_svi:
                continue
            ifaces[current] = {"name": current}
        # other
        for current in ifaces:
            is_svi = current.startswith("VLAN")
            if is_svi:
                continue
            is_bundle = current.startswith("Trunk")
            if is_bundle:
                enabled_afi = ["BRIDGE"]
                ifaces[current]["mac"] = mac_[current]
                ifaces[current]["admin_status"] = stat_[current]
                ifaces[current]["oper_status"] = stat_[current]
                ifaces[current]["type"] = "aggregated"
                ifaces[current]["enabled_protocols"] = []
                # Sub-interface
                sub = {
                    "name": current,
                    "admin_status": stat_[current],
                    "oper_status": stat_[current],
                    "enabled_afi": enabled_afi,
                    "tagged_vlans": tagged_.get(current, []),
                    "mac": mac_[current],
                }
                if current in untagged_:
                    sub["untagged_vlan"] = untagged_[current]
                if current in lldp:
                    ifaces[current]["enabled_protocols"] += ["LLDP"]
                if current in descr_:
                    ifaces[current]["description"] = descr_[current]
                    sub["description"] = descr_[current]
                if current in snmp_ifindex_:
                    sub["snmp_ifindex"] = snmp_ifindex_[current]
                ifaces[current]["subinterfaces"] = [sub]

            else:
                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],
                    "enabled_afi": enabled_afi,
                    "mac": mac_[current],
                }
                if current in lldp:
                    ifaces[current]["enabled_protocols"] += ["LLDP"]
                if current in descr_:
                    ifaces[current]["description"] = descr_[current]
                    sub["description"] = descr_[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]

                # Portchannel member
                if current in portchannel_members:
                    ai, is_lacp = portchannel_members[current]
                    ifaces[current]["aggregated_interface"] = ai
                    ifaces[current]["enabled_protocols"] += ["LACP"]

        # 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"] = ifaces.values()
        r += [rr]
        # Return result
        return r
Ejemplo n.º 23
0
    def execute(self):
        interfaces = []
        # Get portchannes
        portchannel_members = {}  # member -> (portchannel, type)
        # with self.cached():
        #    for pc in self.scripts.get_portchannel():
        #        i = pc["interface"]
        #        t = pc["type"] == "L"
        #        for m in pc["members"]:
        #            portchannel_members[m] = (i, t)
        admin_status = {}
        if self.snmp and self.access_profile.snmp_ro:
            try:
                for n, s in self.snmp.join_tables("1.3.6.1.2.1.31.1.1.1.1",
                                                  "1.3.6.1.2.1.2.2.1.7",
                                                  bulk=True):  # IF-MIB
                    if n[:3] == 'Aux' or n[:4] == 'Vlan' \
                    or n[:11] == 'InLoopBack':
                        continue
                    else:
                        if n[:6] == "Slot0/":
                            n = n[6:]
                        admin_status.update({n: int(s) == 1})
            except self.snmp.TimeOutError:
                pass
        else:
            ports = self.profile.get_ports(self)
            for p in ports:
                admin_status.update({p['port']: p['admin_state']})

        # Get switchports
        for swp in self.scripts.get_switchport():
            admin = admin_status[swp["interface"]]
            name = swp["interface"]
            iface = {
                "name":
                name,
                "type":
                "aggregated" if len(swp["members"]) > 0 else "physical",
                "admin_status":
                admin,
                "oper_status":
                swp["status"],
                # "mac": mac,
                "subinterfaces": [{
                    "name": name,
                    "admin_status": admin,
                    "oper_status": swp["status"],
                    "enabled_afi": ['BRIDGE'],
                    # "mac": mac,
                    # "snmp_ifindex": self.scripts.get_ifindex(interface=name)
                }]
            }
            if swp["tagged"]:
                iface["subinterfaces"][0]["tagged_vlans"] = swp["tagged"]
            try:
                iface["subinterfaces"][0]["untagged_vlan"] = swp["untagged"]
            except KeyError:
                pass
            if 'description' in swp:
                iface["description"] = swp["description"]
            if name in portchannel_members:
                iface["aggregated_interface"] = portchannel_members[name][0]
                if portchannel_members[name][1]:
                    n["enabled_protocols"] = ["LACP"]
            interfaces += [iface]

        ipif = self.cli("show ipif")
        match = self.rx_ipif.search(ipif)
        if match:
            i = {
                "name":
                "System",
                "type":
                "SVI",
                "admin_status":
                True,
                "oper_status":
                True,
                "subinterfaces": [{
                    "name": "System",
                    "admin_status": True,
                    "oper_status": True,
                    "enabled_afi": ["IPv4"]
                }]
            }
            ip_address = match.group("ip_address")
            ip_subnet = match.group("ip_subnet")
            ip_address = \
                "%s/%s" % (ip_address, IPv4.netmask_to_len(ip_subnet))
            i['subinterfaces'][0]["ipv4_addresses"] = [ip_address]
            ch_id = self.scripts.get_chassis_id()
            i["mac"] = ch_id[0]['first_chassis_mac']
            i['subinterfaces'][0]["mac"] = ch_id[0]['first_chassis_mac']
            mgmt_vlan = 1
            sw = self.cli("show switch", cached=True)
            match = self.rx_mgmt_vlan.search(ipif)
            if match:
                vlan = match.group("vlan")
                if vlan != "Disabled":
                    vlans = self.profile.get_vlans(self)
                    for v in vlans:
                        if vlan == v['name']:
                            mgmt_vlan = int(v['vlan_id'])
                            break
            # Need hardware to testing
            i['subinterfaces'][0].update({"vlan_ids": [mgmt_vlan]})
            interfaces += [i]

        return [{"interfaces": interfaces}]
Ejemplo n.º 24
0
    def execute(self):

        # TODO
        # Get portchannes
        portchannel_members = {}  # member -> (portchannel, type)
#        with self.cached():
#            for pc in self.scripts.get_portchannel():
#                i = pc["interface"]
#                t = pc["type"] == "L"
#                for m in pc["members"]:
#                    portchannel_members[m] = (i, t)

        interfaces = []

        # Try SNMP first

        """
        # SNMP working but without IP
        
        if self.snmp and self.access_profile.snmp_ro:
            try:
                # Get mac
                mac = self.scripts.get_chassis_id()
                # Get switchports
                for swp in self.scripts.get_switchport():
                    iface = swp["interface"]
                    if iface[0] == "T":
                        return 1
                    # IF-MIB::ifAdminStatus
                    if len(iface.split('/')) < 3:
                        if_OID = iface.split('/')[1]
                    else:
                        if_OID = iface.split('/')[2]
                    s = self.snmp.get("1.3.6.1.2.1.2.2.1.7.%d" % int(if_OID))
                    admin = int(s) == 1

                    name = swp["interface"]
                    iface = {
                        "name": name,
                        "type": "aggregated" if len(swp["members"]) > 0 else "physical",
                        "admin_status": admin,
                        "oper_status": swp["status"],
                        "mac": mac,
                        "subinterfaces": [{
                            "name": name,
                            "admin_status": admin,
                            "oper_status": swp["status"],
                            "is_bridge": True,
                            "mac": mac,
                            #"snmp_ifindex": self.scripts.get_ifindex(interface=name)
                        }]
                    }
                    if swp["tagged"]:
                        iface["subinterfaces"][0]["tagged_vlans"] = swp["tagged"]
                    try:
                        iface["subinterfaces"][0]["untagged_vlan"] = swp["untagged"]
                    except KeyError:
                        pass
                    if swp["description"]:
                        iface["description"] = swp["description"]
                    if name in portchannel_members:
                        iface["aggregated_interface"] = portchannel_members[name][0]
                        iface["is_lacp"] = portchannel_members[name][1]
                    interfaces += [iface]

                return [{"interfaces": interfaces}]

            except self.snmp.TimeOutError:
                pass  # Fallback to CLI
        """

        # Fallback to CLI
        # Get port-to-vlan mappings
        pvm = {}
        switchports = {}  # interface -> (untagged, tagged)
        for swp in self.scripts.get_switchport():
            switchports[swp["interface"]] = (
                    swp["untagged"] if "untagged" in swp else None,
                    swp["tagged"],
                    swp["description"]
                    )

        interfaces = []

        # Get L3 interfaces
        try:
            enabled_afi = []
            ip_int = self.cli("show ip interface")  # QWS-3xxx
            match = self.rx_mac.search(ip_int)
            mac = match.group("mac")

            # TODO Get router interfaces
            ospfs = self.get_ospfint()
            rips = self.get_ripint()
            bgps = self.get_bgpint()

            for match in self.rx_sh_svi.finditer(ip_int):
                description = match.group("description")
                if not description:
                    description = 'Outband managment'
                ifname = match.group("interface")
                ip1 = match.group("ip1")
                ip2 = match.group("ip2")
                if ":" in ip1:
                    ip_interfaces = "ipv6_addresses"
                    enabled_afi += ["IPv6"]
                    ip1 = IPv6(ip1, netmask=match.group("mask1")).prefix
                    if ip2:
                        ip2 = IPv6(ip2, netmask=match.group("mask2")).prefix
                        ip_list = [ip1, ip2]
                    else:
                        ip_list = [ip1]
                else:
                    ip_interfaces = "ipv4_addresses"
                    enabled_afi += ["IPv4"]
                    ip1 = IPv4(ip1, netmask=match.group("mask1")).prefix
                    if ip2:
                        ip2 = IPv4(ip2, netmask=match.group("mask2")).prefix
                        ip_list = [ip1, ip2]
                    else:
                        ip_list = [ip1]
                vlan = match.group("vlan")
                a_stat = match.group("admin_status").lower() == "up"
                iface = {
                    "name": ifname,
                    "type": "SVI",
                    "admin_status": a_stat,
                    "oper_status": a_stat,
                    "mac": mac,
                    "description": description,
                    "subinterfaces": [{
                                "name": ifname,
                                "description": description,
                                "admin_status": a_stat,
                                "oper_status": a_stat,
                                "enabled_afi": enabled_afi,
                                ip_interfaces: ip_list,
                                "mac": mac,
                                "vlan_ids": self.expand_rangelist(vlan),
                            }]
                    }
                interfaces += [iface]

        except self.CLISyntaxError:
            enabled_afi = []
            ip_int = self.cli("show ip")  # QWS-2xxx
            match = self.rx_sh_mng.search(ip_int)
            ip = match.group("ip")
            if ":" in ip:
                ip_interfaces = "ipv6_addresses"
                enabled_afi += ["IPv6"]
                ip = IPv6(ip, netmask=match.group("mask")).prefix
            else:
                ip_interfaces = "ipv4_addresses"
                enabled_afi += ["IPv4"]
                ip = IPv4(ip, netmask=match.group("mask")).prefix
            ip_list = [ip]
            vlan = match.group("vlan")
            mac = match.group("mac")

            iface = {
                "name": "VLAN-" + vlan,
                "type": "management",
                "admin_status": True,
                "oper_status": True,
                "mac": mac,
                "description": 'Managment',
                "subinterfaces": [{
                            "name": "VLAN-" + vlan,
                            "description": 'Managment',
                            "admin_status": True,
                            "oper_status": True,
                            "enabled_afi": enabled_afi,
                            ip_interfaces: ip_list,
                            "mac": mac,
                            "vlan_ids": self.expand_rangelist(vlan),
                        }]
                }
            interfaces += [iface]
        #

        # Get L2 interfaces
        mac = self.scripts.get_chassis_id()[0]["first_chassis_mac"]
        status = self.cli("show interface")
        for match in self.rx_status.finditer(status):
            ifname = match.group("interface")
            a_stat = match.group("admin_status").lower() == "enabled"
            o_stat = match.group("oper_status").lower() == "up"

            iface = {
                "name": self.profile.convert_interface_name(ifname),
                "type": self.types[ifname[:1]],
                "admin_status": a_stat,
                "oper_status": o_stat,
                "mac": mac,
                "description": switchports[ifname][2],
                "subinterfaces": [{
                            "name": ifname,
                            "description": switchports[ifname][2],
                            "admin_status": a_stat,
                            "oper_status": o_stat,
                            "enabled_afi": ["BRIDGE"],
                            "mac": mac,
                            #"snmp_ifindex": self.scripts.get_ifindex(interface=name)
                        }]
                }

            if switchports[ifname][1]:
                iface["subinterfaces"][0]["tagged_vlans"] = switchports[ifname][1]
            if switchports[ifname][0]:
                iface["subinterfaces"][0]["untagged_vlan"] = switchports[ifname][0]

#            iface["description"] = switchports[ifname][2]

            # Portchannel member
            if ifname in portchannel_members:
                ai, is_lacp = portchannel_members[ifname]
                iface["aggregated_interface"] = ai
                if is_lacp:
                    iface["enabled_protocols"] = ["LACP"]
            interfaces += [iface]

        return [{"interfaces": interfaces}]
Ejemplo n.º 25
0
    def execute(self):
        ipif_found = False
        if self.match_version(DxS_L2):
            L2_Switch = True
        else:
            L2_Switch = False

            rip = []
            try:
                c = self.cli("show rip")
            except self.CLISyntaxError:
                c = ""
            rip_enable = self.rx_rip_gs.search(c) is not None
            if rip_enable:
                for match in self.rx_rip.finditer(c):
                    rip += [match.group("ipif")]

            ospf = []
            try:
                c = self.cli("show ospf")
            except self.CLISyntaxError:
                c = ""
            ospf_enable = self.rx_ospf_gs.search(c) is not None
            if ospf_enable:
                for match in self.rx_ospf.finditer(c):
                    ospf += [match.group("ipif")]

            ospfv3 = []
            try:
                c = self.cli("show ospfv3")
            except self.CLISyntaxError:
                c = ""
            ospfv3_enable = self.rx_ospfv3_gs.search(c) is not None
            if ospfv3_enable:
                for match in self.rx_ospfv3.finditer(c):
                    ospf += [match.group("ipif")]

            pim = []
            try:
                c = self.cli("show pim")
            except self.CLISyntaxError:
                c = ""
            pim_enable = self.rx_pim_gs.search(c) is not None
            if pim_enable:
                for match in self.rx_pim.finditer(c):
                    pim += [match.group("ipif")]

            igmp = []
            try:
                c = self.cli("show igmp")
            except self.CLISyntaxError:
                c = ""
            for match in self.rx_igmp.finditer(c):
                igmp += [match.group("ipif")]

        lldp = []
        macs = []
        try:
            c = self.cli("show lldp")
            lldp_enable = self.rx_lldp_gs.search(c) is not None
            try:
                c = self.cli("show lldp local_ports")
                for match in self.rx_lldp1.finditer(c):
                    macs += [{
                        "port": match.group("port"),
                        "mac": match.group("mac")
                    }]
            except self.CLISyntaxError:
                pass
        except self.CLISyntaxError:
            lldp_enable = False
        if lldp_enable:
            try:
                c = self.cli("show lldp ports")
            except self.CLISyntaxError:
                c = ""
            for match in self.rx_lldp.finditer(c):
                lldp += [match.group("port")]

        if len(macs) == 0:
            if self.match_version(DGS3620, version__gte="2.60.16") \
            or self.match_version(DGS3120, version__gte="4.00.00"):
                try:
                    c = self.cli("show ports details")
                    for match in self.rx_pd.finditer(c):
                        macs += [{
                            "port": match.group("port"),
                            "mac": match.group("mac")
                        }]
                except self.CLISyntaxError:
                    pass

        udld = []
        try:
            c = self.cli("show duld ports")
        except self.CLISyntaxError:
            c = ""
        for match in self.rx_udld.finditer(c):
            udld += [match.group("ipif")]

        ctp = []
        try:
            c = self.cli("show loopdetect")
        except self.CLISyntaxError:
            c = ""
        ctp_enable = self.rx_ctp_gs.search(c) is not None
        if ctp_enable:
            c = []
            try:
                c = self.cli_object_stream("show loopdetect ports all",
                                           parser=self.parse_ctp,
                                           cmd_next="n",
                                           cmd_stop="q")
            except self.CLISyntaxError:
                c = []
            if c == []:
                self.reset_cli_queue()
                c = self.cli_object_stream("show loopdetect ports",
                                           parser=self.parse_ctp,
                                           cmd_next="n",
                                           cmd_stop="q")
            for i in c:
                if i['state'] == 'Enabled':
                    ctp += [i['port']]

        gvrp = []
        try:
            c = self.cli("show gvrp")
        except self.CLISyntaxError:
            c = ""
        gvrp_enable = self.rx_gvrp_gs.search(c) is not None
        if gvrp_enable:
            try:
                c1 = self.cli("show port_vlan")
            except self.CLISyntaxError:
                c1 = c
            for match in self.rx_gvrp.finditer(c1):
                gvrp += [match.group("ipif")]

        stp = []
        try:
            if self.match_version(DES3x2x):
                c = self.cli("show stp\nq")
            else:
                c = self.cli("show stp")
        except self.CLISyntaxError:
            pass
        stp_enable = self.rx_stp_gs.search(c) is not None
        if stp_enable:
            c = self.cli_object_stream("show stp ports",
                                       parser=self.parse_stp,
                                       cmd_next="n",
                                       cmd_stop="q")
            for i in c:
                if i['state'] in ['Enabled', 'Yes']:
                    stp += [i['port']]

        ports = self.profile.get_ports(self)
        vlans = self.profile.get_vlans(self)
        fdb = self.scripts.get_mac_address_table()

        interfaces = []
        for p in ports:
            ifname = p['port']
            i = {
                "name":
                ifname,
                "type":
                "physical",
                "admin_status":
                p['admin_state'],
                "oper_status":
                p['status'],
                "enabled_protocols": [],
                "subinterfaces": [{
                    "name": ifname,
                    "admin_status": p['admin_state'],
                    "oper_status": p['status'],
                    # "ifindex": 1,
                    "enabled_afi": ['BRIDGE']
                }]
            }
            desc = p['desc']
            if desc != '' and desc != 'null':
                i.update({"description": desc})
                i['subinterfaces'][0].update({"description": desc})
            for m in macs:
                if p['port'] == m['port']:
                    i['mac'] = m['mac']
                    i['subinterfaces'][0]["mac"] = m['mac']
            tagged_vlans = []
            for v in vlans:
                if p['port'] in v['tagged_ports']:
                    tagged_vlans += [v['vlan_id']]
                if p['port'] in v['untagged_ports']:
                    i['subinterfaces'][0]["untagged_vlan"] = v['vlan_id']
            if len(tagged_vlans) != 0:
                i['subinterfaces'][0]['tagged_vlans'] = tagged_vlans
            if lldp_enable and ifname in lldp:
                i["enabled_protocols"] += ["LLDP"]
            if ctp_enable and ifname in ctp:
                i["enabled_protocols"] += ["CTP"]
            if ifname in udld:
                i["enabled_protocols"] += ["UDLD"]
            if gvrp_enable and ifname in gvrp:
                i["enabled_protocols"] += ["GVRP"]
            if stp_enable and ifname in stp:
                i["enabled_protocols"] += ["STP"]
            interfaces += [i]

        ipif = self.cli("show ipif")
        for match in self.rx_ipif1.finditer(ipif):
            admin_status = match.group("admin_state") == "Enabled"
            o_status = match.group("oper_status")
            oper_status = re.match(self.rx_link_up, o_status) is not None
            i = {
                "name":
                match.group("ifname"),
                "type":
                "SVI",
                "admin_status":
                admin_status,
                "oper_status":
                oper_status,
                "subinterfaces": [{
                    "name": match.group("ifname"),
                    "admin_status": admin_status,
                    "oper_status": oper_status,
                    "enabled_afi": ["IPv4"]
                }]
            }
            desc = match.group("desc")
            if desc is not None and desc != '':
                desc = desc.strip()
                i.update({"description": desc})
                i['subinterfaces'][0].update({"description": desc})
            ip_address = match.group("ip_address")
            ip_subnet = match.group("ip_subnet")
            ip_address = "%s/%s" % (ip_address, IPv4.netmask_to_len(ip_subnet))
            i['subinterfaces'][0]["ipv4_addresses"] = [ip_address]
            ipv6_address = match.group("ipv6_address")
            if ipv6_address is not None:
                i['subinterfaces'][0]["ipv6_addresses"] = [ipv6_address]
                i['subinterfaces'][0]["enabled_afi"] += ["IPv6"]
            vlan_name = match.group("vlan_name")
            for v in vlans:
                if vlan_name == v['vlan_name']:
                    vlan_id = v['vlan_id']
                    i['subinterfaces'][0].update({"vlan_ids": [vlan_id]})
                    for f in fdb:
                        if 'CPU' in f['interfaces'] \
                        and vlan_id == f['vlan_id']:
                            i.update({"mac": f['mac']})
                            i['subinterfaces'][0].update({"mac": f['mac']})
                            break
                    break
            interfaces += [i]
            ipif_found = True

        for match in self.rx_ipif2.finditer(ipif):
            enabled_afi = []
            enabled_protocols = []
            admin_status = match.group("admin_state") == "Enabled"
            o_status = match.group("oper_status")
            if o_status is not None:
                oper_status = re.match(self.rx_link_up, o_status) is not None
            else:
                oper_status = admin_status
            ifname = match.group("ifname")
            i = {
                "name":
                ifname,
                "type":
                "SVI",
                "admin_status":
                admin_status,
                "oper_status":
                oper_status,
                "subinterfaces": [{
                    "name": ifname,
                    "admin_status": admin_status,
                    "oper_status": oper_status,
                    "enabled_afi": []
                }]
            }
            mtu = match.group("mtu")
            if mtu is not None:
                i['subinterfaces'][0]["mtu"] = int(mtu)
            # TODO: Parse secondary IPv4 address and IPv6 address
            ipv4_addresses = []
            ipv4_address = match.group("ipv4_address")
            if ipv4_address is not None:
                ipv4_addresses += [ipv4_address]
                if not "IPv4" in enabled_afi:
                    enabled_afi += ["IPv4"]
            ipv4_addr_pri = match.group("ipv4_addr_pri")
            if ipv4_addr_pri is not None:
                ipv4_addresses += [ipv4_addr_pri]
                if not "IPv4" in enabled_afi:
                    enabled_afi += ["IPv4"]
            if ipv4_address is not None \
            or ipv4_addr_pri is not None:
                i['subinterfaces'][0].update(
                    {"ipv4_addresses": ipv4_addresses})
            ipv6_address = match.group("ipv6_address")
            if ipv6_address is not None:
                i['subinterfaces'][0]["ipv6_addresses"] = [ipv6_address]
                enabled_afi += ["IPv6"]
            i['subinterfaces'][0].update({"enabled_afi": enabled_afi})
            vlan_name = match.group("vlan_name")
            # Found illegal stuff in DES-1210-28/ME/B2
            # In this rotten device System interface always in vlan 1
            if not vlan_name:
                vlan_name = "default"
            for v in vlans:
                if vlan_name == v['vlan_name']:
                    vlan_id = v['vlan_id']
                    i['subinterfaces'][0].update({"vlan_ids": [vlan_id]})
                    for f in fdb:
                        if 'CPU' in f['interfaces'] \
                        and vlan_id == f['vlan_id']:
                            i.update({"mac": f['mac']})
                            i['subinterfaces'][0].update({"mac": f['mac']})
                            break
                    break
            if not L2_Switch:
                if rip_enable and ifname in rip:
                    enabled_protocols += ["RIP"]
                if ospf_enable and ifname in ospf:
                    enabled_protocols += ["OSPF"]
                if ospfv3_enable and ifname in ospfv3:
                    enabled_protocols += ["OSPFv3"]
                if pim_enable and ifname in pim:
                    enabled_protocols += ["PIM"]
                if ifname in igmp:
                    enabled_protocols += ["IGMP"]
                i['subinterfaces'][0]["enabled_protocols"] = enabled_protocols
            interfaces += [i]
            ipif_found = True

        if self.match_version(DGS3620):
            match = self.rx_ipmgmt.search(ipif)
            if match:
                admin_status = match.group("admin_state") == "Enabled"
                o_status = match.group("oper_status")
                oper_status = re.match(self.rx_link_up, o_status) is not None
                i = {
                    "name":
                    match.group("ifname"),
                    "type":
                    "management",
                    "admin_status":
                    admin_status,
                    "oper_status":
                    oper_status,
                    "subinterfaces": [{
                        "name": match.group("ifname"),
                        "admin_status": admin_status,
                        "oper_status": oper_status,
                        "enabled_afi": ["IPv4"]
                    }]
                }
                ip_address = match.group("ip_address")
                ip_subnet = match.group("ip_subnet")
                ip_address = "%s/%s" % (ip_address,
                                        IPv4.netmask_to_len(ip_subnet))
                i['subinterfaces'][0]["ipv4_addresses"] = [ip_address]
                interfaces += [i]

        if not ipif_found:
            c = self.cli("show switch", cached=True)
            match = self.rx_ipswitch.search(c)
            if match:
                i = {
                    "name":
                    "System",
                    "type":
                    "SVI",
                    "admin_status":
                    True,
                    "oper_status":
                    True,
                    "subinterfaces": [{
                        "name": "System",
                        "admin_status": True,
                        "oper_status": True,
                        "enabled_afi": ["IPv4"]
                    }]
                }
                mac_address = match.group("mac_address")
                ip_address = match.group("ip_address")
                ip_subnet = match.group("ip_subnet")
                vlan_name = match.group("vlan_name")
                ip_address = "%s/%s" % (ip_address,
                                        IPv4.netmask_to_len(ip_subnet))
                i['subinterfaces'][0]["ipv4_addresses"] = [ip_address]
                for v in vlans:
                    if vlan_name == v['vlan_name']:
                        i['subinterfaces'][0].update(
                            {"vlan_ids": [v['vlan_id']]})
                        break
                i.update({"mac": mac_address})
                i['subinterfaces'][0].update({"mac": mac_address})
                interfaces += [i]

        return [{"interfaces": interfaces}]
Ejemplo n.º 26
0
    def execute(self):
        # get interfaces' status
        int_status = {}
        for s in self.scripts.get_interface_status():
            int_status[s["interface"]] = s["status"]

        # get switchports
        swports = {}
        for sp in self.scripts.get_switchport():
            swports[sp["interface"]] = (sp["untagged"] if "untagged" in sp else
                                        None, sp["tagged"])

        # get portchannels
        pc_members = {}
        for pc in self.scripts.get_portchannel():
            i = pc["interface"]
            t = pc["type"] == "L"
            for m in pc["members"]:
                pc_members[m] = (i, t)

        # process all interfaces and form result
        r = []
        cmd = self.cli("show interface")
        for l in cmd.splitlines():
            # find interface name
            match = self.rx_interface.match(l)
            if match:
                ifname = match.group("interface")
                # some initial settings
                iface = {
                    "name": ifname,
                    "admin_status": True,
                    "enabled_protocols": [],
                    "subinterfaces": []
                }
                # detect interface type
                if ifname.startswith("Eth"):
                    iface["type"] = "physical"
                elif ifname.startswith("Po"):
                    iface["type"] = "aggregated"
                elif ifname.startswith("Vlan"):
                    iface["type"] = "SVI"
                # get interface statuses
                iface["oper_status"] = int_status.get(ifname, False)
                if match.group("admin_status").startswith("administratively"):
                    iface["admin_status"] = False
                # process portchannels' members
                if ifname in pc_members:
                    iface["aggregated_interface"] = pc_members[ifname][0]
                    if pc_members[ifname][1]:
                        iface["enabled_protocols"] += ["LACP"]
                        iface["is_lacp"] = True  # @todo: Deprecated
                # process subinterfaces
                if "aggregated_interface" not in iface:
                    sub = {
                        "name": ifname,
                        "admin_status": iface["admin_status"],
                        "oper_status": iface["oper_status"],
                        "enabled_afi": []
                    }
                    # process switchports
                    if ifname in swports:
                        u, t = swports[ifname]
                        if u:
                            sub["untagged_vlan"] = u
                        if t:
                            sub["tagged_vlans"] = t
                        sub["enabled_afi"] += ["BRIDGE"]
                        sub["is_bridge"] = True  # @todo: Deprecated
            # get snmp ifindex
            match = self.rx_ifindex.search(l)
            if match:
                sub["snmp_ifindex"] = match.group("ifindex")
            # get description
            match = self.rx_description.search(l)
            if match:
                descr = match.group("description")
                if not "(null)" in descr:
                    iface["description"] = descr
                    sub["description"] = descr
            # get ipv4 addresses
            match = self.rx_ipv4.match(l)
            if match:
                if not "ipv4 addresses" in sub:
                    sub["enabled_afi"] += ["IPv4"]
                    sub["is_ipv4"] = True  # @todo: Deprecated
                    sub["ipv4_addresses"] = []
                    vid = re.search("(?P<vid>\d+)", ifname)
                    sub["vlan_ids"] = [int(vid.group("vid"))]
                ip = IPv4(match.group("ip"),
                          netmask=match.group("mask")).prefix
                sub["ipv4_addresses"] += [ip]
            # get mac address
            match = self.rx_mac.search(l)
            if match:
                iface["mac"] = match.group("mac")
                sub["mac"] = iface["mac"]
                iface["subinterfaces"] += [sub]
                r += [iface]

        return [{"interfaces": r}]
Ejemplo n.º 27
0
    def execute(self):

        # Get portchannels
        portchannel_members = {}
        portchannel_interface = []
        for pc in self.scripts.get_portchannel():
            i = pc["interface"]
            t = pc["type"] == "L"
            portchannel_interface += [i]
            for m in pc["members"]:
                portchannel_members[m] = (i, t)

        lldp = []
        try:
            c = self.cli("show lldp")
        except self.CLISyntaxError:
            c = ""
            pass
        lldp_enable = self.rx_lldp_gs.search(c) is not None
        if lldp_enable:
            try:
                c = self.cli("show lldp ports")
            except self.CLISyntaxError:
                c = ""
            for match in self.rx_lldp.finditer(c):
                lldp += [match.group("ipif")]

        ports = []
        objects = []
        descriptions = {}
        try:
            d = self.cli("show ports descr all")
        except self.CLISyntaxError:
            d = ""
            pass
        if d:
            for match in self.rx_descrs.finditer(d):
                descriptions[match.group("port")] = match.group("description")
        try:
            c = self.cli("show ports all")
        except self.CLISyntaxError:
            c = ""
            pass
        if c:
            for match in self.rx_ports.finditer(c):
                objects += [{
                    "port": match.group("port"),
                    "admin_state": match.group("admin_state") == "Enabled",
                    "admin_speed": match.group("admin_speed"),
                    "admin_duplex": match.group("admin_duplex"),
                    "admin_flowctrl": match.group("admin_flowctrl"),
                    "status": match.group("status") is None,
                    "speed": match.group("speed"),
                    "duplex": match.group("duplex"),
                    "flowctrl": match.group("flowctrl"),
                    "address_learning": match.group("addr_learning").strip(),
                    "desc": descriptions[match.group("port")] \
                        if match.group("port") in descriptions else "None"
                }]
        for i in objects:
            ports += [i]
        vlans = []
        try:
            c = self.cli("show vlan")
        except self.CLISyntaxError:
            c = ""
            pass
        if c:
            for match in self.rx_vlan.finditer(c):
                members = self.expand_interface_range(
                    self.profile.open_brackets(match.group("member_ports")))
                tagged_ports = []
                untagged_ports = self.expand_interface_range(
                    self.profile.open_brackets(match.group("untagged_ports")))
                for p in members:
                    if not (p in untagged_ports):
                        tagged_ports += [p]
                vlans += [{
                    "vlan_id": int(match.group("vlan_id")),
                    "vlan_name": match.group("vlan_name"),
                    "vlan_type": match.group("vlan_type"),
                    "tagged_ports": tagged_ports,
                    "untagged_ports": untagged_ports
                }]

        interfaces = []
        for p in ports:
            ifname = p['port']
            i = {
                "name":
                ifname,
                "type":
                "physical",
                "admin_status":
                p['admin_state'],
                "oper_status":
                p['status'],
                "enabled_protocols": [],
                "subinterfaces": [{
                    "name": ifname,
                    "admin_status": p['admin_state'],
                    "oper_status": p['status'],
                    # "ifindex": 1,
                    "enabled_afi": ["BRIDGE"]
                }]
            }
            desc = p['desc']
            if desc != '' and desc != 'null':
                i.update({"description": desc})
                i['subinterfaces'][0].update({"description": desc})
            tagged_vlans = []
            for v in vlans:
                if p['port'] in v['tagged_ports']:
                    tagged_vlans += [v['vlan_id']]
                if p['port'] in v['untagged_ports']:
                    i['subinterfaces'][0]["untagged_vlan"] = v['vlan_id']
            if len(tagged_vlans) != 0:
                i['subinterfaces'][0]['tagged_vlans'] = tagged_vlans
            if lldp_enable and ifname in lldp:
                i["enabled_protocols"] += ["LLDP"]
            # Portchannel member
            if ifname in portchannel_members:
                ai, is_lacp = portchannel_members[ifname]
                i["aggregated_interface"] = ai
                i["enabled_protocols"] += ["LACP"]
                i['subinterfaces'][0].update({"enabled_afi": []})
            # Portchannel interface
            if ifname in portchannel_interface:
                i["type"] = "aggregated"
            interfaces += [i]

        mac = self.scripts.get_chassis_id()[0]["first_chassis_mac"]
        ipif = self.cli("show ipif")
        for match in self.rx_ipif.finditer(ipif):
            admin_status = match.group("admin_state") == "Enabled"
            o_status = match.group("oper_status")
            oper_status = re.match(self.rx_link_up, o_status) is not None
            i = {
                "name":
                "System",
                "type":
                "SVI",
                "admin_status":
                admin_status,
                "oper_status":
                oper_status,
                "subinterfaces": [{
                    "name": "System",
                    "admin_status": admin_status,
                    "oper_status": oper_status,
                    "enabled_afi": ["IPv4"]
                }]
            }
            ip_address = match.group("ip_address")
            ip_subnet = match.group("ip_subnet")
            ip_address = "%s/%s" % (ip_address, IPv4.netmask_to_len(ip_subnet))
            i['subinterfaces'][0]["ipv4_addresses"] = [ip_address]
            vlan_name = match.group("vlan_name")
            for v in vlans:
                if vlan_name == v['vlan_name']:
                    i['subinterfaces'][0]["vlan_ids"] = [v['vlan_id']]
                    break
            i['subinterfaces'][0]["mac"] = mac
            interfaces += [i]
        return [{"interfaces": interfaces}]