NETBOX — различия между версиями

Материал из megapuper
Перейти к: навигация, поиск
Строка 2: Строка 2:
  
  
'''PostgreSQL'''<br>
+
'''<color=blue>PostgreSQL</color>'''<br>
  
 
Ставим БД, в данном случае версия 17
 
Ставим БД, в данном случае версия 17

Версия 15:31, 15 марта 2026

Установим Netbox на Debian 13


<color=blue>PostgreSQL</color>

Ставим БД, в данном случае версия 17

apt install -y postgresql
sudo -u postgres psql


Создаём базу и пользователя

CREATE DATABASE netbox;
CREATE USER netbox WITH PASSWORD 'пароль';
ALTER DATABASE netbox OWNER TO netbox;
-- the next two commands are needed on PostgreSQL 15 and later
\connect netbox;
GRANT CREATE ON SCHEMA public TO netbox;


Проверяем подключение

root@netbox ~ # psql --username netbox --password --host localhost netbox
Password: 
psql (17.8 (Debian 17.8-1.pgdg13+1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off, ALPN: postgresql)
Type "help" for help.

netbox=> \conninfo
You are connected to database "netbox" as user "netbox" on host "localhost" (address "127.0.0.1") at port "5432".
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off, ALPN: postgresql)


Redis

Устанавливаем redis-сервер

apt install -y redis-server


Проверяем

# redis-server -v
Redis server v=8.0.2 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=3951f4e1c0288395
# redis-cli ping
PONG


Компоненты Netbox

Переходим к установке Netbox. Устанавливаемая версия 4.5 поддерживает Python 3.12 и выше


Ставим зависимости

apt install -y python3 python3-pip python3-venv python3-dev build-essential libxml2-dev libxslt1-dev libffi-dev libpq-dev libssl-dev zlib1g-dev


Проверяем версию Python после установки

python3 -V
Python 3.13.5


Определяемся с версией Netbox https://github.com/netbox-community/netbox/releases и скачиваем

wget https://github.com/netbox-community/netbox/archive/refs/tags/vX.Y.Z.tar.gz
tar -xzf vX.Y.Z.tar.gz -C /opt
ln -s /opt/netbox-X.Y.Z/ /opt/netbox

Рекомендуется устанавливать NetBox в каталог, названный в соответствии с номером его версии. Например, NetBox v4.5.0 следует установить в /opt/netbox-4.5.0, а симлинк из /opt/netbox/ будет указывать на это местоположение. Это позволяет устанавливать будущие версии параллельно, не прерывая текущую установку. При переходе на новую версию необходимо обновить только симлинк.


Создаём пользователя и даём ему права

adduser --system --group netbox
chown --recursive netbox /opt/netbox/netbox/media/
chown --recursive netbox /opt/netbox/netbox/reports/
chown --recursive netbox /opt/netbox/netbox/scripts/


Переходим к конфигурационному файлу

cd /opt/netbox/netbox/netbox/
cp configuration_example.py configuration.py


Готовим конфиг

Основное блоки

  • ALLOWED_HOSTS
  • API_TOKEN_PEPPERS
  • DATABASES
  • REDIS
  • SECRET_KEY


ALLOWED_HOSTS This is a list of the valid hostnames and IP addresses by which this server can be reached. You must specify at least one name or IP address. (Note that this does not restrict the locations from which NetBox may be accessed: It is merely for HTTP host header validation.)

ALLOWED_HOSTS = ['netbox.example.com', '192.0.2.123']

If you are not yet sure what the domain name and/or IP address of the NetBox installation will be, you can set this to a wildcard (asterisk) to allow all host values:

ALLOWED_HOSTS = ['*']

API_TOKEN_PEPPERS Define at least one random cryptographic pepper, identified by a numeric ID starting at 1. This will be used to generate SHA256 checksums for API tokens.

API_TOKEN_PEPPERS = {

   # DO NOT USE THIS EXAMPLE PEPPER IN PRODUCTION
   1: 'kp7ht*76fiQAhUi5dHfASLlYUE_S^gI^(7J^K5M!LfoH@vl&b_',

}

tip As with SECRET_KEY below, you can use the generate_secret_key.py script to generate a random pepper:

python3 ../generate_secret_key.py

DATABASES This parameter holds the PostgreSQL database configuration details. The default database must be defined; additional databases may be defined as needed e.g. by plugins.

A username and password must be defined for the default database. If the service is running on a remote host, update the HOST and PORT parameters accordingly. See the configuration documentation for more detail on individual parameters.

DATABASES = {

   'default': {
       'NAME': 'netbox',               # Database name
       'USER': 'netbox',               # PostgreSQL username
       'PASSWORD': 'J5brHrAXFLQSif0K', # PostgreSQL password
       'HOST': 'localhost',            # Database server
       'PORT': ,                     # Database port (leave blank for default)
       'CONN_MAX_AGE': 300,            # Max database connection age (seconds)
   }

}

REDIS Redis is an in-memory key-value store used by NetBox for caching and background task queuing. Redis typically requires minimal configuration; the values below should suffice for most installations. See the configuration documentation for more detail on individual parameters.

Note that NetBox requires the specification of two separate Redis databases: tasks and caching. These may both be provided by the same Redis service, however each should have a unique numeric database ID.

REDIS = {

   'tasks': {
       'HOST': 'localhost',      # Redis server
       'PORT': 6379,             # Redis port
       'PASSWORD': ,           # Redis password (optional)
       'DATABASE': 0,            # Database ID
       'SSL': False,             # Use SSL (optional)
   },
   'caching': {
       'HOST': 'localhost',
       'PORT': 6379,
       'PASSWORD': ,
       'DATABASE': 1,            # Unique ID for second database
       'SSL': False,
   }

}

SECRET_KEY This parameter must be assigned a randomly-generated key employed as a salt for hashing and related cryptographic functions. (Note, however, that it is never directly used in the encryption of secret data.) This key must be unique to this installation and is recommended to be at least 50 characters long. It should not be shared outside the local system.

A simple Python script named generate_secret_key.py is provided in the parent directory to assist in generating a suitable key:

python3 ../generate_secret_key.py


Spoiler


Запускаем установку Netbox

/opt/netbox/upgrade.sh


Запускаем виртуальное окружение и создаём суперпользователя

source /opt/netbox/venv/bin/activate

cd /opt/netbox/netbox
python3 manage.py createsuperuser


NetBox работает как WSGI-приложение за HTTP-сервером. В этой документации показано, как установить и настроить uWSGI для этой роли, однако доступны и другие WSGI-серверы, которые должны работать аналогично.

Запускаем виртуальное окружение, если вышли на прошлом шаге, и ставим pyuwsgi

source /opt/netbox/venv/bin/activate
pip3 install pyuwsgi


После установки добавим пакет в файл local_requirements.txt, чтобы обеспечить его повторную установку при последующих пересборках виртуальной среды:

echo 'pyuwsgi' >> /opt/netbox/local_requirements.txt


Копируем дефолтный конфиг, его вполне достаточно для работы

cp /opt/netbox/contrib/uwsgi.ini /opt/netbox/uwsgi.ini


Далее скопируем файлы systemd для управления uWSGI и фоновым рабочим процессом NetBox

cp -v /opt/netbox/contrib/*.service /etc/systemd/system/

Отредактируем файл netbox.service, удалив строку начинающуюся с ExecStart=/opt/netbox/venv/bin/gunicorn, и раскомментируем строку с ExecStart=/opt/netbox/venv/bin/uwsgi

 systemctl daemon-reload

Стартуем сервис и проверяем он запустился

systemctl enable --now netbox netbox-rq
systemctl status netbox.service


Для удобства поставим Nginx и добавим конфиг для Netbox

server {
        listen 80;
        server_name netboxold.iwad.ru;

location /static/ {
        alias /opt/netbox/netbox/static/;
    }

location / {
        # proxy_pass http://127.0.0.1:8001;
        # proxy_set_header X-Forwarded-Host $http_host;
        # proxy_set_header X-Real-IP $remote_addr;
        # proxy_set_header X-Forwarded-Proto $scheme;
        # comment the lines above and uncomment the lines below if using uWSGI
        include uwsgi_params;
        uwsgi_pass  127.0.0.1:8001;
        uwsgi_param Host $host;
        uwsgi_param X-Real-IP $remote_addr;
        uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for;
        uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto;

        access_log /var/log/nginx/netbox.access.log;
        error_log  /var/log/nginx/netbox.error.log;
       
        location = /favicon.ico {
            log_not_found off;
            access_log off;
               }
         location ~ /\.ht {
            deny all;
              }
    }
}


Установка завершена, заходим в браузер и смотрим картинки


LDAP authentication (optional)


Ставим нужные пакеты

apt install -y libldap2-dev libsasl2-dev libssl-dev


Запускаем виртуальное окружение, если вышли на прошлом шаге, и ставим django-auth-ldap

source /opt/netbox/venv/bin/activate
pip3 install django-auth-ldap


После установки добавим пакет в файл local_requirements.txt, чтобы обеспечить его повторную установку при последующих пересборках виртуальной среды:

echo 'django-auth-ldap' >> /opt/netbox/local_requirements.txt


Конфигурируем

First, enable the LDAP authentication backend in configuration.py. (Be sure to overwrite this definition if it is already set to RemoteUserBackend.)

REMOTE_AUTH_ENABLED = True
REMOTE_AUTH_BACKEND = 'netbox.authentication.LDAPBackend'


Далее создаём файл в той же директории, что и configuration.py (обычно /opt/netbox/netbox/netbox/), с именем ldap_config.py и определяем все необходимые параметры

import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, LDAPGroupQuery

  1. включение логирования
  2. import logging
  3. logger = logging.getLogger('django_auth_ldap')
  4. logger.addHandler(logging.StreamHandler())
  5. logger.setLevel(logging.DEBUG)
  1. Server URI

AUTH_LDAP_SERVER_URI = "ldap://ldap.iwad.ru"

  1. The following may be needed if you are binding to Active Directory.

AUTH_LDAP_CONNECTION_OPTIONS = {

   ldap.OPT_REFERRALS: 0

}

  1. Set the DN and password for the NetBox service account.

AUTH_LDAP_BIND_DN = "cn=admin,dc=iwad,dc=ru" AUTH_LDAP_BIND_PASSWORD = "kQN5UVz3jISa9LLvk2q5"

  1. AUTH_LDAP_BIND_DN = "cn=netbox,dc=iwad,dc=ru"
  2. AUTH_LDAP_BIND_PASSWORD = "FepfLVh8xjd9xnN7fZqv"


  1. Include this setting if you want to ignore certificate errors. This might be needed to accept a self-signed cert.
  2. Note that this is a NetBox-specific setting which sets:
  3. ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

LDAP_IGNORE_CERT_ERRORS = True

  1. Include this setting if you want to validate the LDAP server certificates against a CA certificate directory on your server
  2. Note that this is a NetBox-specific setting which sets:
  3. ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, LDAP_CA_CERT_DIR)

LDAP_CA_CERT_DIR = '/etc/ssl/certs'

  1. Include this setting if you want to validate the LDAP server certificates against your own CA.
  2. Note that this is a NetBox-specific setting which sets:
  3. ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, LDAP_CA_CERT_FILE)

LDAP_CA_CERT_FILE = '/path/to/example-CA.crt'


  1. User configuration

AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=iwad,dc=ru", ldap.SCOPE_SUBTREE,"(uid=%(user)s)") AUTH_LDAP_USER_DN_TEMPLATE = None AUTH_LDAP_USER_ATTR_MAP = {

   "first_name": "givenName",
   "last_name": "sn",
   "email": "mail"

}

AUTH_LDAP_GROUP_SEARCH = LDAPSearch("groups,dc=iwad,dc=ru", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)")

  1. Ограничение доступа только для группы netbox_users

AUTH_LDAP_REQUIRE_GROUP = "cn=netbox_users,ou=groups,dc=iwad,dc=ru"

AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_CACHE_TIMEOUT = 3600


Перезагружаем Netbox и проверяем авторизацию

systemctl restart netbox





Здесь тоже самое на англицком https://netboxlabs.com/docs/netbox/installation/