#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ export_netbox_refs.py — выгрузка справочников NetBox в компактный плоский текст для формирования контекста сторонних агентов (экономия токенов, особенно при обработке проектов vision-моделями: вместо чтения всего NetBox — только нужные справочники в один файл). Запуск: поставить этот скрипт в контейнер NetBox или передать через stdin: docker exec -i netbox-netbox-1 python manage.py shell < export_netbox_refs.py 2>/dev/null > /tmp/nb_ctx.txt (manage.py печатает служебные строки до JSON — хвост после первого '{' и есть JSON) Формат вывода: JSON со справочниками одним блоком; каждый список — плоский, без лишней вложенности (site, location, rack, device_type, role, manufacturer). Фильтры (переменные ниже) позволяют выгрузить только нужный срез: SITE_FILTER, RACK_FILTER, DEVICE_TYPE_FILTER, DEVICE_FILTER, LOCATION_FILTER (по подстроке; регистронезависимо; '*' = все) Этот скрипт предназначен для запуска ИЗ КОНТЕЙНЕРА NetBox (ORM доступен). На хосте без django используй обёртку export_netbox_refs.sh. """ import json import re # === НАСТРОЙКИ ФИЛЬТРОВ ('' = все) === SITE_FILTER = '' # подстрока имени site (напр. 'Винный город') LOCATION_FILTER = '' # подстрока имени location RACK_FILTER = '' # подстрока имени rack DEVICE_TYPE_FILTER = '' # подстрока model device_type DEVICE_FILTER = '' # подстрока имени device ROLE_FILTER = '' # подстрока имени роли # какие секции выгружать (True/False) INCLUDE = dict( sites=True, locations=True, racks=True, manufacturers=True, device_types=True, device_roles=True, devices=True, cables=True, ipam=True, tenancy=True, power=True, ) from dcim.models import (Site, Location, Rack, Manufacturer, DeviceType, DeviceRole, Device, Cable, FrontPort, 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 def sec(name, data): if not INCLUDE.get(name, True) or not data: return print(f"### {name.upper()}") for row in data: print(json.dumps(row, ensure_ascii=False)) 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, 'status': str(d.status)} for d in devs] # --- Cables --- cables = list(Cable.objects.all()) if SITE_FILTER: # фильтр по site через терминации (m2m terminations -> termination имеет site) def _cable_site(c): for t in c.terminations.all()[:4]: term = t.termination s = getattr(term, 'site', None) if s and _match(s.name, SITE_FILTER): return True return False cables = [c for c in cables if _cable_site(c)] out['cables'] = [] for c in cables: terms = list(c.terminations.all()) a = next((t.termination for t in terms if t.cable_end == 'A'), None) b = next((t.termination for t in terms if t.cable_end == 'B'), 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': str(a) if a else None, 'b': str(b) if b else None, }) # --- 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))