Netbox linux ip address

Netbox — документируем сеть

Netbox — это открытое (open source) веб приложение, разработанное для управления и документирования компьютерных сетей. Изначально Netbox придуман командой сетевых инженеров DigitalOcean специально для системных администраторов.

  • IP address management (IPAM) — IP сети и адреса, VRFs, и VLAN
  • DataCenter infrastructure management (DCIM) — организация стоечного оборудования по группам и устройствам
  • Устройства — типы устройств и место установки
  • Соединения — сеть, консоль, силовые соединения
  • Виртуализация — виртуальные машины и кластеры
  • Схемы передачи данных — схемы дальней связи и провайдеры
  • Секреты — зашифрованное хранение конфиденциальных учетных данных

Возможна интеграция с LDAP. Небольшой минус — отсутствие локализации.

  • HTTP service — nginx или Apache
  • WSGI service — gunicorn или uWSGI
  • Application — Django/Python
  • Database — PostgreSQL 9.6+
  • Task queuing — Redis/django-rq
  • Live device access — NAPALM

Для управления я его не использую, но вот для документирования, информации и отрисовки стоек с оборудованием — самое то! Не могу накидать много скриншотов, поскольку в текущем приложении у меня много служебной информации.

Можно создавать свои типы устройств и назначать им роли, выделяя собственный цвет в стойке.

Пример схемы стойки.

Приложение имеет REST API, с помощью которого можно получать или изменять информацию в Netbox. API применяется для интеграции Netbox с другими системами: виртуализация, мониторинг, логи, резервирование и прочее. Никто не запрещает писать свои модули.

Источник

Как установить NetBox на Ubuntu 18.04 LTS

NetBox – это веб-приложение IPAM / DCIM с открытым исходным кодом, используемое для управления и документирования компьютерных сетей и управления IP-адресами.

Первоначально он был задуман командой сетевой инженерии в DigitalOcean.

Netbox включает в себя следующие аспекты управления сетью:

  • Управление IP-адресами (IPAM) – IP-сети и адреса, VRF и VLAN
  • Стеллажи для оборудования – организованы по группам и сайтам
  • Устройства – типы устройств и где они установлены
  • Соединения – сетевые, консольные и силовые соединения между устройствами
  • Виртуализация – виртуальные машины и кластеры
  • Цепи передачи данных. Цепи и поставщики дальней связи
  • Секреты – Зашифрованное хранение конфиденциальных учетных данных

Установка NetBox на Ubuntu 18.04 LTS

В этом разделе будут обсуждаться реальные шаги, которые необходимо выполнить, чтобы установить NetBox на вашем сервере Ubuntu 18.04 LTS.

Следуйте им в порядке появления, хотя вы можете пропустить часть, если у вас уже установлено программное обеспечение, которое потребуется.

Шаг 1: Установите необходимые зависимости

Начните с установки всех зависимых приложений, необходимых для запуска NetBox в Ubuntu 18.04 LTS.

Шаг 2: Установите и настройте сервер базы данных PostgreSQL

NetBox использует сервер базы данных PostgreSQL для хранения своих данных.

Так что установите и настройте его на Ubuntu 18.04, используя наше предыдущее руководство

Создайте базу данных и пользователя для NetBox.

Подтвердите, что вы можете войти в базу данных как пользователь netbox.

Шаг 3: Установите и настройте Netbox

Перейдите в каталог /opt/

Создать файл конфигурации

Отредактируйте файл конфигурации и задайте разрешенные данные для входа в хост и базу данных

Замените 192.168.121.31 на IP-адрес вашего сервера Netbox.

Сгенерируйте секретный ключ Django:

Затем установите ключ в файле /opt/netbox/netbox/netbox/configuration.py

Установить зависимости Netbox

Перенос данных базы данных:

Пример вывода для миграции базы данных.

Переместите статические файлы

Загрузите исходные данные

Установите и настройте gunicorn

Установите gunicorn с помощью pip3:

Настройте gunicorn для Netbox

Создайте файл конфигурации супервизора

Перезапустите и включите службу supervisord для запуска при загрузке.

Статус должен показывать работу с выводом netbox.

Настройте веб-сервер Nginx

Давайте настроим веб-сервер Nginx, чтобы помочь нам получить доступ к Netbox через имя домена, а не указывать IP-адрес и порт.

Создайте новый файл конфигурации Nginx для Netbox.

Проверьте синтаксис конфигурации Nginx и перезапустите его сервис

Если все в порядке, перезапустите сервис Nginx

Доступ к Netbox Web UI

Откройте веб-браузер по умолчанию и откройте имя хоста сервера Netbox.

Чтобы внести изменения, войдите администратором, созданным ранее.

Наслаждайтесь использованием Netbox для документирования вашей сетевой инфраструктуры.

Источник

KitPloit — PenTest & Hacking Tools

KitPloit — leading source of Security Tools, Hacking Tools, CyberSecurity and Network Security ☣

Читайте также:  Windows advanced ip scanner

NetBox — IP Address Management (IPAM) and Data Center Infrastructure Management (DCIM) Tool

Installation
Please see docs/getting-started.md for instructions on installing NetBox.
To upgrade NetBox, please download the latest release and run upgrade.sh .

Components
NetBox understands all of the physical and logical building blocks that comprise network infrastructure, and the manners in which they are all related.

DCIM
DCIM comprises all the physical installations and connections which comprise a network. NetBox tracks where devices are installed, as well as their individual power, console, and network connections.
Site: A physical location (typically a building) where network devices are installed. Devices in different sites cannot be directly connected to one another.
Rack: An equipment rack into which devices are installed. Each rack belongs to a site.
Device: Any type of rack-mounted device. For example, routers, switches, servers, console servers, PDUs, etc. 0U (non-rack-mounted) devices are supported.

IPAM
IPAM deals with the IP addressing and VLANs in use on a network. NetBox makes a distinction between IP prefixes (networks) and individual IP addresses.
Because NetBox is a combined DCIM/IPAM system, IP addresses can be assigned to device interfaces in the application just as they are in the real world.
Aggregate: A top-level aggregate of IP address space; for example, 10.0.0.0/8 or 2001:db8::/32. Each aggregate belongs to a regional Internet registry (RIR) like ARIN or RIPE, or to an authoritative standard such as RFC 1918.
VRF: A virtual routing table. VRF support is currently still under development.
Prefix: An IPv4 or IPv6 network. A prefix can be assigned to a VRF; if not, it is considered to belong to the global table. Prefixes are grouped by aggregates automatically and can optionally be assigned to sites.
IP Address: An individual IPv4 or IPv6 address (with CIDR mask). IP address can be assigned to device interfaces.
VLAN: VLANs are assigned to sites, and can optionally have one or more IP prefixes assigned to them. VLAN IDs are unique only within the scope of a site.

Circuits
Long-distance data connections are typically referred to as circuits . NetBox provides a method for managing circuits and their providers. Individual circuits can be terminated to device interfaces.
Provider: An entity to which a network connects to. This can be a transit provider, peer, or some other organization.
Circuit: A data circuit which connects to a provider. The local end of a circuit can be assigned to a device interface.

Secrets
NetBox provides encrypted storage of sensitive data it calls secrets . Each user may be issued an encryption key with which stored secrets can be retrieved.
Note that NetBox does not merely hash secrets, a function which is only useful for validation. It employs fully reversible AES-256 encryption so that secret data can be retrieved and consumed by other services.
Secrets Any piece of confidential data which must be retrievable. For example: passwords, SNMP communities, RADIUS shared secrets, etc.
User Key: An individual user’s encrypted copy of the master key, which can be used to retrieve secret data.

Источник

REST API Overview

What is a REST API?

REST stands for representational state transfer. It’s a particular type of API which employs HTTP requests and JavaScript Object Notation (JSON) to facilitate create, retrieve, update, and delete (CRUD) operations on objects within an application. Each type of operation is associated with a particular HTTP verb:

  • GET : Retrieve an object or list of objects
  • POST : Create an object
  • PUT / PATCH : Modify an existing object. PUT requires all mandatory fields to be specified, while PATCH only expects the field that is being modified to be specified.
  • DELETE : Delete an existing object

Additionally, the OPTIONS verb can be used to inspect a particular REST API endpoint and return all supported actions and their available parameters.

One of the primary benefits of a REST API is its human-friendliness. Because it utilizes HTTP and JSON, it’s very easy to interact with NetBox data on the command line using common tools. For example, we can request an IP address from NetBox and output the JSON using curl and jq . The following command makes an HTTP GET request for information about a particular IP address, identified by its primary key, and uses jq to present the raw JSON data returned in a more human-friendly format. (Piping the output through jq isn’t strictly required but makes it much easier to read.)

Each attribute of the IP address is expressed as an attribute of the JSON object. Fields may include their own nested objects, as in the case of the assigned_object field above. Every object includes a primary key named id which uniquely identifies it in the database.

Читайте также:  Qt static linking windows

Interactive Documentation

Comprehensive, interactive documentation of all REST API endpoints is available on a running NetBox instance at /api/docs/ . This interface provides a convenient sandbox for researching and experimenting with specific endpoints and request types. The API itself can also be explored using a web browser by navigating to its root at /api/ .

Endpoint Hierarchy

NetBox’s entire REST API is housed under the API root at https:// /api/ . The URL structure is divided at the root level by application: circuits, DCIM, extras, IPAM, plugins, tenancy, users, and virtualization. Within each application exists a separate path for each model. For example, the provider and circuit objects are located under the «circuits» application:

Likewise, the site, rack, and device objects are located under the «DCIM» application:

The full hierarchy of available endpoints can be viewed by navigating to the API root in a web browser.

Each model generally has two views associated with it: a list view and a detail view. The list view is used to retrieve a list of multiple objects and to create new objects. The detail view is used to retrieve, update, or delete an single existing object. All objects are referenced by their numeric primary key ( id ).

  • /api/dcim/devices/ — List existing devices or create a new device
  • /api/dcim/devices/123/ — Retrieve, update, or delete the device with ID 123

Lists of objects can be filtered using a set of query parameters. For example, to find all interfaces belonging to the device with ID 123:

See the filtering documentation for more details.

Serialization

The REST API employs two types of serializers to represent model data: base serializers and nested serializers. The base serializer is used to present the complete view of a model. This includes all database table fields which comprise the model, and may include additional metadata. A base serializer includes relationships to parent objects, but does not include child objects. For example, the VLANSerializer includes a nested representation its parent VLANGroup (if any), but does not include any assigned Prefixes.

Related objects (e.g. ForeignKey fields) are represented using nested serializers. A nested serializer provides a minimal representation of an object, including only its direct URL and enough information to display the object to a user. When performing write API actions ( POST , PUT , and PATCH ), related objects may be specified by either numeric ID (primary key), or by a set of attributes sufficiently unique to return the desired object.

For example, when creating a new device, its rack can be specified by NetBox ID (PK):

Or by a set of nested attributes which uniquely identify the rack:

Note that if the provided parameters do not return exactly one object, a validation error is raised.

Generic Relations

Some objects within NetBox have attributes which can reference an object of multiple types, known as generic relations. For example, an IP address can be assigned to either a device interface or a virtual machine interface. When making this assignment via the REST API, we must specify two attributes:

Together, these values identify a unique object in NetBox. The assigned object (if any) is represented by the assigned_object attribute on the IP address model.

If we wanted to assign this IP address to a virtual machine interface instead, we would have set assigned_object_type to virtualization.vminterface and updated the object ID appropriately.

Brief Format

Most API endpoints support an optional «brief» format, which returns only a minimal representation of each object in the response. This is useful when you need only a list of available objects without any related data, such as when populating a drop-down list in a form. As an example, the default (complete) format of an IP address looks like this:

The brief format is much more terse:

The brief format is supported for both lists and individual objects.

Excluding Config Contexts

When retrieving devices and virtual machines via the REST API, each will included its rendered configuration context data by default. Users with large amounts of context data will likely observe suboptimal performance when returning multiple objects, particularly with very high page sizes. To combat this, context data may be excluded from the response data by attaching the query parameter ?exclude=config_context to the request. This parameter works for both list and detail views.

Pagination

API responses which contain a list of many objects will be paginated for efficiency. The root JSON object returned by a list endpoint contains the following attributes:

  • count : The total number of all objects matching the query
  • next : A hyperlink to the next page of results (if applicable)
  • previous : A hyperlink to the previous page of results (if applicable)
  • results : The list of objects on the current page
Читайте также:  Установить google earth линукс

Here is an example of a paginated response:

The default page is determined by the PAGINATE_COUNT configuration parameter, which defaults to 50. However, this can be overridden per request by specifying the desired offset and limit query parameters. For example, if you wish to retrieve a hundred devices at a time, you would make a request for:

The response will return devices 1 through 100. The URL provided in the next attribute of the response will return devices 101 through 200:

The maximum number of objects that can be returned is limited by the MAX_PAGE_SIZE configuration parameter, which is 1000 by default. Setting this to 0 or None will remove the maximum limit. An API consumer can then pass ?limit=0 to retrieve all matching objects with a single request.

Disabling the page size limit introduces a potential for very resource-intensive requests, since one API request can effectively retrieve an entire table from the database.

Interacting with Objects

Retrieving Multiple Objects

To query NetBox for a list of objects, make a GET request to the model’s list endpoint. Objects are listed under the response object’s results parameter.

Retrieving a Single Object

To query NetBox for a single object, make a GET request to the model’s detail endpoint specifying its unique numeric ID.

Note that the trailing slash is required. Omitting this will return a 302 redirect.

Creating a New Object

To create a new object, make a POST request to the model’s list endpoint with JSON data pertaining to the object being created. Note that a REST API token is required for all write operations; see the authentication documentation for more information. Also be sure to set the Content-Type HTTP header to application/json .

Creating Multiple Objects

To create multiple instances of a model using a single request, make a POST request to the model’s list endpoint with a list of JSON objects representing each instance to be created. If successful, the response will contain a list of the newly created instances. The example below illustrates the creation of three new sites.

Updating an Object

To modify an object which has already been created, make a PATCH request to the model’s detail endpoint specifying its unique numeric ID. Include any data which you wish to update on the object. As with object creation, the Authorization and Content-Type headers must also be specified.

PUT versus PATCH

The NetBox REST API support the use of either PUT or PATCH to modify an existing object. The difference is that a PUT request requires the user to specify a complete representation of the object being modified, whereas a PATCH request need include only the attributes that are being updated. For most purposes, using PATCH is recommended.

Updating Multiple Objects

Multiple objects can be updated simultaneously by issuing a PUT or PATCH request to a model’s list endpoint with a list of dictionaries specifying the numeric ID of each object to be deleted and the attributes to be updated. For example, to update sites with IDs 10 and 11 to a status of «active», issue the following request:

Note that there is no requirement for the attributes to be identical among objects. For instance, it’s possible to update the status of one site along with the name of another in the same request.

The bulk update of objects is an all-or-none operation, meaning that if NetBox fails to successfully update any of the specified objects (e.g. due a validation error), the entire operation will be aborted and none of the objects will be updated.

Deleting an Object

To delete an object from NetBox, make a DELETE request to the model’s detail endpoint specifying its unique numeric ID. The Authorization header must be included to specify an authorization token, however this type of request does not support passing any data in the body.

Note that DELETE requests do not return any data: If successful, the API will return a 204 (No Content) response.

You can run curl with the verbose ( -v ) flag to inspect the HTTP response codes.

Deleting Multiple Objects

NetBox supports the simultaneous deletion of multiple objects of the same type by issuing a DELETE request to the model’s list endpoint with a list of dictionaries specifying the numeric ID of each object to be deleted. For example, to delete sites with IDs 10, 11, and 12, issue the following request:

Источник

Оцените статью