示例#1
0
def add_device_types(option='Switch', map_dev=None):
    new_dev = []
    namespace_dev = []
    if option == 'Switch':
        for row in map_dev:
            description_map = map_dev[row].get('description')
            description_map = re.sub(r'^\[.*\]', '', description_map)
            namespace_dev.append(description_map.split('\n')[0].split(' ')[0])

        map_dev = namespace_dev

    if option == 'Modem':
        for row in map_dev:
            namespace_dev.append(map_dev[row].get('model'))
        map_dev = namespace_dev

    if option == 'dev':
        for vendor in config.DEVICE_TYPES:
            for dev_type in config.DEVICE_TYPES[vendor]:
                namespace_dev.append(dev_type)
        map_dev = namespace_dev

    map_dev_name = set(map_dev)

    for dev_name in map_dev_name:
        if option != 'dev':
            dev_name = dev_name
        net = net_box.dcim.device_types.get(slug=slugify(dev_name))

        for vendor in config.DEVICE_TYPES:

            if dev_name in config.DEVICE_TYPES[vendor]:
                try:
                    manufacturer = net_box.dcim.manufacturers.get(
                        slug=slugify(vendor)).id
                except BaseException:
                    print('не найден вендор в системе NetBox:', vendor)
                    return new_dev

                configured_ports = config.DEVICE_TYPES[vendor].get(dev_name)
                custom_fields = configured_ports.get('custom_fields', {})
                if configured_ports:
                    break
            else:
                manufacturer = None
                configured_ports = None

        if net is None and configured_ports:
            new_dev.append(
                formatted_device_type(manufacturer, dev_name, custom_fields))
        elif not configured_ports:
            print('нет конфигурации портов:', dev_name)

    return new_dev
示例#2
0
def main_add_VLANs(regions):
    VLANs = []
    for region in regions:
        for vlan_groups in regions[region]:
            slug_group = slugify(vlan_groups[1])
            group = net_box.ipam.vlan_groups.get(slug=slug_group)

            if not group:
                group = add_VLAN_G(vlan_groups[1])

            vlans_list = add_vlans_list(group, vlan_groups)

            for vlan in vlans_list:
                try:
                    tmp = net_box.ipam.vlans.get(name=vlan['name'])

                    if tmp:
                        VLANs.append(tmp)
                    elif not (tmp):
                        VLANs.append(net_box.ipam.vlans.create(vlan))
                except ValueError:
                    print(vlan, 'Вернул несколько значений. ДУБЛЬ')
            add_prefixes(VLANs, vlan_groups)
        print(VLANs)

    return VLANs
示例#3
0
def add_VLAN_G(name, slug=None):
    if not slug:
        slug = slugify(name)

    VLAN_G = net_box.ipam.vlan_groups.create({'name': name, 'slug': slug})

    return VLAN_G
示例#4
0
def add_device_types(
    option='Switch',
    map_dev=None,
):
    new_dev = []
    namespace_dev = []
    if option == 'Switch':
        for row in map_dev:
            namespace_dev.append(
                map_dev[row].get('description').split('\n')[0].split(' ')[0])
        map_dev = namespace_dev

    if option == 'Modem':
        for row in map_dev:
            namespace_dev.append(map_dev[row].get('model'))
        map_dev = namespace_dev

    if option == 'dev':
        for vendor in config.DEVICE_TYPES:
            for dev_type in config.DEVICE_TYPES[vendor]:
                namespace_dev.append(dev_type)
        map_dev = namespace_dev

    map_dev = set(map_dev)

    for dev_name in map_dev:
        if option != 'dev':
            dev_name = 'T1-' + dev_name
        net = net_box.dcim.device_types.get(slug=slugify(dev_name))

        for vendor in config.DEVICE_TYPES:

            if dev_name in config.DEVICE_TYPES[vendor]:
                try:
                    manufacturer = net_box.dcim.manufacturers.get(
                        name=vendor).id
                except BaseException:
                    print('не найден вендор в системе NetBox ', vendor)
                    return new_dev

                configured_ports = config.DEVICE_TYPES[vendor].get(
                    dev_name.upper())
                if configured_ports:
                    break
            else:
                manufacturer = None
                configured_ports = None

        if net is None and configured_ports:
            new_dev.append(formatted_device_type(manufacturer, dev_name))
        elif not configured_ports:
            print('нет конфигурации портов:', dev_name)

    return new_dev
示例#5
0
def formatted_device_type(vendor, name):

    create_list = {
        "manufacturer": vendor,
        "model": name,
        "slug": slugify(name),
        "tags": [
            "test-0919",
        ],
        "is_full_depth": 0,
    }

    info = net_box.dcim.device_types.create(create_list)

    return info
示例#6
0
def formatted_device_type(vendor_id, name, custom_fields={}):
    info = None

    create_list = {
        "manufacturer": vendor_id,
        "model": name,
        "slug": slugify(name),
        "tags": config.TAGS,
        "is_full_depth": 0,
        'custom_fields': custom_fields,
    }

    try:
        info = net_box.dcim.device_types.create(create_list)
    except pynetbox.RequestError as e:
        print(e.error)

    return info
示例#7
0
def add_regions(name, parent=None, slug=None):
    name = name.strip()
    if parent:
        parent = parent.strip()
        parent_id = net_box.dcim.regions.get(name=parent).id

    slug = slug or slugify(name)

    if not net_box.dcim.regions.get(name=name):
        if parent and parent_id:

            region_info = net_box.dcim.regions.create({"name": name,
                                                       "slug": slug,
                                                       "parent": parent_id,
                                                       })
        else:
            region_info = net_box.dcim.regions.create({"name": name,
                                                       "slug": slug,
                                                       })
        print("add_regions:", region_info)
        return region_info
示例#8
0
def add_site(trans_name, name, region):
    backup_region = None
    region_id = None

    backup_region = net_box.dcim.regions.get(slug=region)
    if backup_region:
        region_id = backup_region.id
    elif not backup_region:
        raise ValueError(f"No region_info for {trans_name}")

    slug = slugify(name)

    site_info = net_box.dcim.sites.create({
        "name": name,
        "slug": slug,
        "region": region_id,
        "tags": config.TAGS,
        "description": trans_name,
    })

    print("add_site:", site_info)
    return site_info
示例#9
0
def get_names():
    for init in map_scan:

        dev = map_scan[init]

        ip_address = dev.get('address')

        site_arr = xl_map.get(ip_address)

        if (dev.get('description') and site_arr):
            site_arr[3].update({'hint': dev.get('description')})
            desc_tmp = site_arr[3]
            dev['description'] = desc_tmp

        if not site_arr:
            continue

        number_house = re.sub('[,/]', '_',
                              dev.get('name').split()[-1].split('.')[0])
        site_name = (site_arr[0] + ' ' + number_house).strip()
        trans_name = site_arr[2]
        site_name = transliterate(site_name)
        site_info = net_box.dcim.sites.get(name=site_name.strip())

        if not site_info:
            site_info = net_box.dcim.sites.get(slug=slugify(site_name.strip()))

        region_info = net_box.dcim.regions.get(slug=region)

        names_regions = []
        region_tmp = region
        if not region_info:
            while region_tmp:

                name_this_region = net_box.dcim.regions.get(slug=region_tmp)
                names_regions.append(name_this_region.slug)
                region_tmp = name_this_region.parent
                if region_tmp:
                    region_tmp = region_tmp.slug
            names_regions = names_regions[-1]
        else:
            names_regions = region_info.slug

        name_prefix_tmp = dev.get('name').split('.')
        name_prefix_tmp.remove(name_prefix_tmp[0])
        name_prefix = '.'.join(name_prefix_tmp)

        name = '-'.join((names_regions, site_info.slug))
        if name_prefix:
            name = name + '.' + name_prefix

        removed = True

        if site_arr[3].get('P_REMOVED') == '1':
            dev_removed = net_box.dcim.devices.get(name="REMOVED " + name)
            if not dev_removed:
                removed = False
            elif not dev_removed.custom_fields('P_REMOVED'):
                removed = False
        else:
            dev_tmp = net_box.net_box.dcim.devices.get(name=name)
            if dev_tmp:
                if dev_tmp.custom_fields('P_REMOVED'):
                    removed = False

    if removed:
        renamed(name)

    return ''
示例#10
0
def data_dev_hook(model):

    slug_model = slugify('' + model)
    type_id = net_box.dcim.device_types.get(slug=slug_model).id

    return type_id
示例#11
0
def device_name_SWITCH(map_dev, xl_map, region):

    device_role = net_box.dcim.device_roles.get(name='Switch').id

    ip_mask = '/' + region[3].split('/')[-1]

    region = region[1].strip()

    result = []

    region = slugify(region)

    for init in map_dev:

        dev = map_dev[init]

        ip_address = dev.get('address')

        if net_box.ipam.ip_addresses.get(address=ip_address):
            continue

        site_arr = xl_map.get(ip_address)

        if (dev.get('description') and site_arr):
            site_arr[3].update({'hint': dev.get('description')})
            desc_tmp = site_arr[3]
            dev['description'] = desc_tmp

        if not site_arr:
            continue

        site_arr[3]['P_RESERVED3'] = str(site_arr[2]) + '_' + str(site_arr[1])

        number_house = transliterate(
            re.sub('[,/]', '_', site_arr[1].split()[-1].split('.')[0]))
        site_name = (site_arr[0] + ' ' + number_house).strip()
        trans_name = site_arr[2]
        try:
            prefix = re.match(r'^[\w-]+\.', site_name).group(0)
            if prefix in prefixes:
                site_name = re.sub(r'^[\w-]+\.', prefixes[prefix], site_name)
        except BaseException as ex:
            print(ex)

        site_info = net_box.dcim.sites.get(name=site_name.strip())

        if not site_info:
            site_info = net_box.dcim.sites.get(slug=slugify(site_name.strip()))
        region_info = net_box.dcim.regions.get(slug=region)

        if not region_info:
            raise ValueError(f"No region_info for {map_dev[init]}")

        if site_info:
            site = site_info
        else:
            site = sites.add_site(trans_name + ' ' + number_house, site_name,
                                  region)
        site_id = site.id

        names_regions = []
        region_tmp = region

        while region_tmp:

            name_this_region = net_box.dcim.regions.get(slug=region_tmp)
            names_regions.append(name_this_region.slug)
            region_tmp = name_this_region.parent
            if region_tmp:
                region_tmp = region_tmp.slug

        names_regions = names_regions[-1]

        name_prefix_tmp = site_arr[1].split('.')
        name_prefix_tmp.remove(name_prefix_tmp[0])
        name_prefix = transliterate('.'.join(name_prefix_tmp))

        name = '-'.join((names_regions, site.slug))
        if name_prefix:
            name = name + '.' + name_prefix

        if site_arr[3].get('P_REMOVED') == '1':
            removed = net_box.dcim.devices.get(name="REMOVED " + name)
            name = "REMOVED " + name
        else:
            removed = None

        name_type_tmp = dev.get('description')['hint'].split('\n')[0]
        name_type = re.sub(r'^\[font .*\]', '', name_type_tmp).split(' ')[0]
        type_dev = net_box.dcim.device_types.get(model='' + name_type)

        if type_dev:
            if not removed:
                type_id = type_dev.id
                description = dev.get('description')
                if description['P_REMOVED'] == '1':
                    description['P_REMOVED'] = True
                elif description['P_REMOVED'] == '0':
                    description['P_REMOVED'] = False
                if description['P_TRANSIT'] == '1':
                    description['P_TRANSIT'] = True
                elif description['P_TRANSIT'] == '0':
                    description['P_TRANSIT'] = False
                json_dev = {
                    "name": name,
                    "device_type": type_id,
                    "device_role": device_role,
                    "site": site_id,
                    "tags": config.TAGS,
                    "comments": description.pop('hint'),
                    "custom_fields": description
                }

                result.append([
                    json_dev, {
                        "primary_ip": ip_address + ip_mask,
                        "addresses": dev.get('addresses'),
                    }
                ])
            else:
                print('Dev has removed but in netbox')
        else:
            print('Не установлен Тип в config для данного устройства:',
                  name_type, name, ip_address)

    create_dev = add_devices(result)

    return create_dev