bbf8b20802
- скрипты: экспорт справочников (export_netbox_refs) и портовой модели (export_netbox_inventory) для составления CSV-импорта устройств/соединений - docs: CSV-снимки справочников + inventory JSON (2026-10-12, сайт «Винный город») - статус/план/конспекты проекта; .gitignore исключает .venv, skc_pdfs, skc_texts
164 lines
8.0 KiB
Python
164 lines
8.0 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
export_netbox_inventory.py — полная выгрузка справочников + портовой модели
|
|
для составления CSV-файлов импорта устройств и соединений (NetBox CSV import:
|
|
devices / interfaces / cables).
|
|
|
|
Отличие от export_netbox_refs.py: добавляет секции interfaces, front_ports,
|
|
rear_ports и cables с ТОЧНЫМИ конечными точками (имя устройства + имя порта),
|
|
по которым NetBox CSV-импорт соединений сверяет терминации.
|
|
|
|
Запуск (ORM доступен только в контейнере):
|
|
docker exec -i netbox-netbox-1 python manage.py shell < export_netbox_inventory.py 2>/dev/null
|
|
или обёрткой с хоста: export_netbox_inventory.sh
|
|
|
|
Фильтры (подстрока, регистронезависимо; '' = все):
|
|
SITE_FILTER, LOCATION_FILTER, RACK_FILTER, DEVICE_TYPE_FILTER,
|
|
DEVICE_FILTER, ROLE_FILTER
|
|
Отключить портовые секции (для лёгкого контекста): INCLUDE['ports']=False.
|
|
"""
|
|
import json
|
|
import re
|
|
|
|
# === НАСТРОЙКИ ФИЛЬТРОВ ('' = все) ===
|
|
SITE_FILTER = '' # подстрока имени site (напр. 'Винный город')
|
|
LOCATION_FILTER = '' # подстрока имени location
|
|
RACK_FILTER = '' # подстрока имени rack
|
|
DEVICE_TYPE_FILTER = '' # подстрока model device_type
|
|
DEVICE_FILTER = '' # подстрока имени device
|
|
ROLE_FILTER = '' # подстрока имени роли
|
|
# какие секции выгружать
|
|
INCLUDE = dict(
|
|
sites=True, locations=True, racks=True, manufacturers=True,
|
|
device_types=True, device_roles=True, devices=True,
|
|
ports=True, # interfaces + front_ports + rear_ports
|
|
cables=True,
|
|
ipam=True, tenancy=True, power=True,
|
|
)
|
|
|
|
from dcim.models import (Site, Location, Rack, Manufacturer, DeviceType,
|
|
DeviceRole, Device, Cable, FrontPort, RearPort,
|
|
Interface, PowerPanel, PowerFeed)
|
|
from tenancy.models import Tenant
|
|
from virtualization.models import Cluster
|
|
from ipam.models import VRF, Prefix, VLAN, IPAddress
|
|
|
|
def _match(obj, sub):
|
|
return not sub or re.search(sub, str(obj), re.IGNORECASE)
|
|
|
|
def _site_name(x):
|
|
return getattr(x, 'site', None) and x.site.name or None
|
|
|
|
out = {}
|
|
|
|
# --- Sites ---
|
|
objs = [s for s in Site.objects.all() if _match(s.name, SITE_FILTER)]
|
|
out['sites'] = [{'name': s.name, 'slug': s.slug, 'status': str(s.status)} for s in objs]
|
|
|
|
# --- Locations ---
|
|
loc_objs = [l for l in Location.objects.all()
|
|
if (LOCATION_FILTER and _match(l.name, LOCATION_FILTER)) or
|
|
(not LOCATION_FILTER and SITE_FILTER and l.site and _match(l.site.name, SITE_FILTER))]
|
|
out['locations'] = [{'name': l.name, 'slug': l.slug, 'site': l.site.name if l.site else None,
|
|
'parent': l.parent.name if l.parent else None, 'status': str(l.status)} for l in loc_objs]
|
|
|
|
# --- Racks ---
|
|
objs = [r for r in Rack.objects.all()
|
|
if _match(r.name, RACK_FILTER) or (r.site and _match(r.site.name, SITE_FILTER))]
|
|
out['racks'] = [{'name': r.name, 'site': r.site.name if r.site else None,
|
|
'location': r.location.name if r.location else None,
|
|
'u_height': r.u_height, 'status': str(r.status)} for r in objs]
|
|
|
|
# --- Manufacturers ---
|
|
out['manufacturers'] = [{'name': m.name, 'slug': m.slug} for m in Manufacturer.objects.all()]
|
|
|
|
# --- DeviceTypes ---
|
|
objs = [t for t in DeviceType.objects.all() if _match(t.model, DEVICE_TYPE_FILTER)]
|
|
out['device_types'] = [{'model': t.model, 'slug': t.slug,
|
|
'manufacturer': t.manufacturer.name if t.manufacturer else None,
|
|
'u_height': t.u_height, 'count': getattr(t, 'device_count', None)} for t in objs]
|
|
|
|
# --- DeviceRoles ---
|
|
objs = [r for r in DeviceRole.objects.all() if _match(r.name, ROLE_FILTER)]
|
|
out['device_roles'] = [{'name': r.name, 'slug': r.slug, 'color': r.color} for r in objs]
|
|
|
|
# --- Devices ---
|
|
devs = Device.objects.all()
|
|
if SITE_FILTER:
|
|
devs = [d for d in devs if d.site and _match(d.site.name, SITE_FILTER)]
|
|
if RACK_FILTER:
|
|
devs = [d for d in devs if d.rack and _match(d.rack.name, RACK_FILTER)]
|
|
if DEVICE_FILTER:
|
|
devs = [d for d in devs if _match(d.name, DEVICE_FILTER)]
|
|
out['devices'] = [{'name': d.name,
|
|
'device_type': d.device_type.model if d.device_type else None,
|
|
'role': d.role.name if d.role else None,
|
|
'site': d.site.name if d.site else None,
|
|
'rack': d.rack.name if d.rack else None,
|
|
'position': d.position,
|
|
'face': str(d.face) if d.face else None,
|
|
'serial': d.serial or None,
|
|
'status': str(d.status)} for d in devs]
|
|
dev_names = {d.name for d in devs}
|
|
|
|
# --- Ports (interfaces / front / rear) ---
|
|
if INCLUDE.get('ports', True):
|
|
ifs = [i for i in Interface.objects.filter(device__in=devs)]
|
|
out['interfaces'] = [{'device': i.device.name, 'name': i.name,
|
|
'type': str(i.type), 'enabled': i.enabled,
|
|
'mgmt_only': i.mgmt_only, 'description': i.description or None}
|
|
for i in ifs]
|
|
fps = [f for f in FrontPort.objects.filter(device__in=devs)]
|
|
out['front_ports'] = [{'device': f.device.name, 'name': f.name,
|
|
'type': str(f.type), 'positions': f.positions,
|
|
'description': f.description or None} for f in fps]
|
|
rps = [r for r in RearPort.objects.filter(device__in=devs)]
|
|
out['rear_ports'] = [{'device': r.device.name, 'name': r.name,
|
|
'type': str(r.type), 'positions': r.positions,
|
|
'description': r.description or None} for r in rps]
|
|
|
|
# --- Cables (точные терминации A/B: устройство + порт) ---
|
|
if INCLUDE.get('cables', True):
|
|
cables = list(Cable.objects.all())
|
|
out['cables'] = []
|
|
for c in cables:
|
|
terms = list(c.terminations.all())
|
|
ends = {'A': None, 'B': None}
|
|
for t in terms:
|
|
obj = t.termination
|
|
dev = getattr(obj, 'device', None)
|
|
ends[t.cable_end] = {
|
|
'device': dev.name if dev else None,
|
|
'kind': obj._meta.model_name,
|
|
'port': obj.name if hasattr(obj, 'name') else None,
|
|
}
|
|
out['cables'].append({
|
|
'label': c.label or '', 'type': c.type, 'status': str(c.status),
|
|
'length': str(c.length) if c.length else None,
|
|
'a': ends['A'], 'b': ends['B'],
|
|
})
|
|
|
|
# --- IPAM ---
|
|
if INCLUDE.get('ipam', True):
|
|
out['vrfs'] = [{'name': v.name} for v in VRF.objects.all()]
|
|
out['prefixes'] = [{'prefix': str(p.prefix), 'vrf': p.vrf.name if p.vrf else None,
|
|
'site': _site_name(p)} for p in Prefix.objects.all()]
|
|
out['vlans'] = [{'vid': v.vid, 'name': v.name} for v in VLAN.objects.all()]
|
|
out['ip_addresses'] = [{'address': str(a.address), 'dns': a.dns_name,
|
|
'device': a.assigned_object.device.name if getattr(a.assigned_object, 'device', None) else None}
|
|
for a in IPAddress.objects.all()[:500]]
|
|
|
|
# --- Tenancy ---
|
|
if INCLUDE.get('tenancy', True):
|
|
out['tenants'] = [{'name': t.name} for t in Tenant.objects.all()]
|
|
out['clusters'] = [{'name': c.name} for c in Cluster.objects.all()]
|
|
|
|
# --- Power ---
|
|
if INCLUDE.get('power', True):
|
|
out['power_panels'] = [{'name': p.name, 'site': p.site.name if p.site else None,
|
|
'location': p.location.name if p.location else None} for p in PowerPanel.objects.all()]
|
|
out['power_feeds'] = [{'name': f.name, 'panel': f.power_panel.name if f.power_panel else None,
|
|
'voltage': f.voltage} for f in PowerFeed.objects.all()]
|
|
|
|
print(json.dumps(out, ensure_ascii=False, indent=1, default=str)) |