Monitor Your Devices Using LibreNMS on CentOS 7

LibreNMS is a full-featured open source network monitoring system. It uses SNMP to obtain the data from different devices. A variety of devices are supported in LibreNMS such as Cisco, Linux, FreeBSD, Juniper, Brocade, Foundry, HP and many more. It supports multiple authentication mechanisms and supports two-factor authentication. It has a customizable alerting system which can alert the network admin via email, IRC or slack.

Prerequisites

  • A Vultr CentOS 7 server instance.
  • A sudo user.

For this tutorial, we will use nms.example.com as the domain name pointed towards the Vultr instance. Please make sure to replace all occurrences of the example domain name with the actual one.

Update your base system using the guide How to Update CentOS 7. Once your system has been updated, proceed to install the dependencies.

Install Nginx and PHP

The front end of LibreNMS is basically written in PHP, thus we will need to install a web server and PHP. In this tutorial, we will install Nginx along with PHP 7.2 to obtain maximum security and performance.

Install Nginx.

sudo yum -y install nginx

Start Nginx and enable it to start at boot automatically.

sudo systemctl start nginx
sudo systemctl enable nginx

Add and enable the Remi repository, as the default YUM repository contains an older version of PHP.

sudo rpm -Uvh http://rpms.remirepo.net/enterprise/remi-release-7.rpm
sudo yum -y install yum-utils
sudo yum-config-manager --enable remi-php72

Install PHP version 7.2 along with the modules required by LibreNMS.

sudo yum -y install php php-cli php-common php-curl php-fpm php-gd php-mcrypt php-mysql php-process php-snmp php-xml php-zip

Open the loaded configuration file by PHP in an editor.

sudo nano /etc/php.ini

Find the following lines, uncomment and change their value as shown.

;cgi.fix_pathinfo=1
memory_limit = 128M
;date.timezone =

Use these values instead, replace Asia/Kolkata with your local timezone.

cgi.fix_pathinfo=0
memory_limit = -1
date.timezone = Asia/Kolkata

You will also need to change the system timezone by running the following command.

sudo ln -sf /usr/share/zoneinfo/Asia/Kolkata /etc/localtime

Now open the PHP-FPM configuration file.

sudo nano /etc/php-fpm.d/www.conf

Find the following line.

listen = 127.0.0.1:9000

Replace it with the following line.

listen = /var/run/php-fpm/php-fpm.sock

By default, PHP-FPM is configured for Apache web server user. Change the user to nginx.

user = nginx
group = nginx

Further, uncomment the following lines.

listen.owner = nobody
listen.group = nobody

Save the file and exit from the editor. Restart PHP-FPM and enable it to start at boot time.

sudo systemctl restart php-fpm
sudo systemctl enable php-fpm

Set the appropriate ownership to the socket file.

sudo chown nginx:nginx /var/run/php-fpm/php-fpm.sock

Install MariaDB

MariaDB is a fork of MySQL. Add the MariaDB repository into your system. The default yum repository contains an older version of MariaDB.

echo "[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1" | sudo tee /etc/yum.repos.d/mariadb.repo

Install MariaDB.

sudo yum -y install mariadb mariadb-server

Now, open the MySQL configuration file.

sudo nano /etc/my.cnf

Add the following lines at the end of the block.

[mysqld]
innodb_file_per_table=1
sql-mode=""
lower_case_table_names=0

Restart MariaDB and enable it to automatically start at boot time.

sudo systemctl restart mariadb
sudo systemctl enable mariadb

Before configuring the database, you will need to secure MariaDB first.

sudo mysql_secure_installation

You will be asked for the current MariaDB root password. By default, there is no root password in a fresh MariaDB installation. Press the "Enter" key to proceed. Set a strong password for the root user of your MariaDB server and answer "Y" to all of the other questions that are asked. The questions asked are self-explanatory.

Log into the MySQL shell as root.

mysql -u root -p

Provide the password for the MariaDB root user to log in.

Run the following queries to create a database and a database user for the LibreNMS installation.

CREATE DATABASE librenms CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE USER 'librenms'@'localhost' IDENTIFIED BY 'StrongPassword';
GRANT ALL PRIVILEGES ON librenms.* TO 'librenms'@'localhost';
FLUSH PRIVILEGES;
EXIT;

You can replace the database name librenms and username librenms according to your choice. Please make sure to change StrongPassword to a very strong password.

Install LibreNMS

Apart from the dependencies above, LibreNMS needs few more dependencies. Install them by running.

sudo yum -y install cronie fping git ImageMagick jwhois mtr MySQL-python net-snmp net-snmp-utils nmap  python-memcached rrdtool

Add a new unprivileged user for LibreNMS application.

sudo useradd librenms -d /opt/librenms -M -r
sudo usermod -a -G librenms nginx

LibreNMS can be installed directly by cloning its Github repository.

cd /opt
sudo git clone https://github.com/librenms/librenms.git librenms

Fix the ownership.

sudo chown librenms:librenms -R /opt/librenms

LibreNMS relies on SNMP for many tasks. Since we have already installed SNMP, copy the example configuration file to its location.

sudo cp /opt/librenms/snmpd.conf.example /etc/snmp/snmpd.conf

Open the configuration file in the editor.

sudo nano /etc/snmp/snmpd.conf

Find this line.

com2sec readonly  default         RANDOMSTRINGGOESHERE

Edit the text RANDOMSTRINGGOESHERE and replace the community string with any string of your choice. For example.

com2sec readonly  default         my-org

Remember the string as it will be required later when we add the first SNMP device.

SNMP also needs information about the distribution version. Download and install the script to find the distribution version.

sudo curl -o /usr/bin/distro https://raw.githubusercontent.com/librenms/librenms-agent/master/snmp/distro
sudo chmod +x /usr/bin/distro

Start the SNMP daemon service and enable it to automatically start at boot time.

sudo systemctl enable snmpd
sudo systemctl restart snmpd

Now you will need to add some crontab entries to run the scheduled tasks. Create a new cron job file.

sudo nano /etc/cron.d/librenms

Populate the file with the following text.

33   */6  * * *   librenms    /opt/librenms/cronic /opt/librenms/discovery-wrapper.py 1
*/5  *    * * *   librenms    /opt/librenms/discovery.php -h new >> /dev/null 2>&1
*/5  *    * * *   librenms    /opt/librenms/cronic /opt/librenms/poller-wrapper.py 16
15   0    * * *   librenms    /opt/librenms/daily.sh >> /dev/null 2>&1
*    *    * * *   librenms    /opt/librenms/alerts.php >> /dev/null 2>&1
*/5  *    * * *   librenms    /opt/librenms/poll-billing.php >> /dev/null 2>&1
01   *    * * *   librenms    /opt/librenms/billing-calculate.php >> /dev/null 2>&1
*/5  *    * * *   librenms    /opt/librenms/check-services.php >> /dev/null 2>&1

Restart the cron daemon service.

sudo systemctl restart crond

Setup logrotate so that the log files are automatically refreshed over time.

sudo cp /opt/librenms/misc/librenms.logrotate /etc/logrotate.d/librenms

Finally, set the appropriate ownership and permissions.

sudo chown -R librenms:nginx /opt/librenms
sudo chmod g+w -R /opt/librenms
sudo setfacl -d -m g::rwx /opt/librenms/rrd /opt/librenms/logs
sudo setfacl -R -m g::rwx /opt/librenms/rrd /opt/librenms/logs

SSL and Nginx VHost configurations

Logins and other information sent through the web interface of LibreNMS are not secured if the connection is not encrypted with SSL. We will configure Nginx to use SSL generated with Let's Encrypt free SSL.

Install Certbot, which is the client application for Let's Encrypt CA.

sudo yum -y install certbot

Before you can request the certificates, you will need to allow port 80 and 443, or standard HTTP and HTTPS services through the firewall.

sudo firewall-cmd --zone=public --add-service=http --permanent
sudo firewall-cmd --zone=public --add-service=https --permanent
sudo firewall-cmd --reload

Note: To obtain certificates from Let's Encrypt CA, the domain for which the certificates are to be generated must be pointed towards the server. If not, make the necessary changes to the DNS records of the domain and wait for the DNS to propagate before making the certificate request again. Certbot checks the domain authority before providing the certificates.

Generate the SSL certificates:

sudo certbot certonly --webroot -w /usr/share/nginx/html -d nms.example.com

The generated certificates are likely to be stored in the /etc/letsencrypt/live/nms.example.com/ directory. The SSL certificate will be stored as fullchain.pem and private key will be stored as privkey.pem.

Let's Encrypt certificates expire in 90 days, hence it is recommended to set up auto-renewal for the certificates using a cron job.

Open the cron job file.

sudo crontab -e

Add the following line at the end of the file.

30 5 * * 1 /usr/bin/certbot renew --quiet

The above cron job will run every Monday at 5:30 AM local time. If the certificate is due for expiry, it will automatically be renewed.

Create a new virtual host.

sudo nano /etc/nginx/conf.d/nms.example.com.conf

Populate the file.

server {
    listen 80;
    server_name nms.example.com;
    return 301 https://$host$request_uri;
}
server {

    listen 443;
    server_name nms.example.com;

    ssl_certificate           /etc/letsencrypt/live/nms.example.com/fullchain.pem;
    ssl_certificate_key       /etc/letsencrypt/live/nms.example.com/privkey.pem;

    ssl on;
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;

    access_log    /opt/librenms/logs/librenms.nginx.access.log;
    root        /opt/librenms/html;
    index       index.php;

    charset utf-8;
    gzip on;
    gzip_types text/css application/javascript text/javascript application/x-javascript image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    location /api/v0 {
        try_files $uri $uri/ /api_v0.php?$query_string;
    }
    location ~ \.php {
        include fastcgi.conf;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
    }
    location ~ /\.ht {
        deny all;
    }
 }

Replace nms.example.com with your actual domain in the above configuration.

Restart Nginx.

sudo chown nginx:nginx /var/lib/php/session
sudo systemctl restart nginx

Installation using WebUI

To finish the installation, open https://nms.example.com on your favorite browser. You will see the requirements are satisfied. Provide your database details and create a new administrative account. Once installed, you will get a message to validate the installation. Click on the link and log in using the administrator account. You will see that everything except the "Poller" has an "Ok" status.

Monitor Your Devices Using LibreNMS on CentOS 7

Now, click on the link to add a device. On the "Add Device" interface, provide the hostname as the localhost and leave everything as it is. Provide your community string in community field. It must be the exact same string which you have provided in snmpd.conf during the configuration of SNMP.

Monitor Your Devices Using LibreNMS on CentOS 7

Once the device has been added, you can see the details by going to the "Devices" tab.

Monitor Your Devices Using LibreNMS on CentOS 7

Similarly, you can add more devices into the LibreNMS application for "around the clock" monitoring.


Инсталирайте Plesk на CentOS 7

Инсталирайте Plesk на CentOS 7

Използване на различна система? Plesk е собствен контролен панел за уеб хост, който позволява на потребителите да администрират своите лични и/или клиентски уебсайтове, бази данни

Как да инсталирате Squid Proxy на CentOS

Как да инсталирате Squid Proxy на CentOS

Squid е популярна, безплатна програма за Linux, която ви позволява да създадете уеб прокси за препращане. В това ръководство ще видите как да инсталирате Squid на CentOS, за да ви обърне

Как да инсталирате Lighttpd (LLMP стек) на CentOS 6

Как да инсталирате Lighttpd (LLMP стек) на CentOS 6

Въведение Lighttpd е форк на Apache, чиято цел е да бъде много по-малко ресурсоемка. Той е лек, откъдето идва и името му, и е доста лесен за използване. Инсталирайте

Конфигуриране на статична мрежа и IPv6 на CentOS 7

Конфигуриране на статична мрежа и IPv6 на CentOS 7

VULTR наскоро направи промени от своя страна и вече всичко трябва да работи добре от кутията с активиран NetworkManager. Ако желаете да деактивирате

Промяна на Icinga2 за използване на модел главен/клиент на CentOS 6 или CentOS 7

Промяна на Icinga2 за използване на модел главен/клиент на CentOS 6 или CentOS 7

Icinga2 е мощна система за наблюдение и когато се използва в модел главен-клиент, тя може да замени необходимостта от проверки на базата на NRPE. Главният клиент

Как да инсталирате Apache Cassandra 3.11.x на CentOS 7

Как да инсталирате Apache Cassandra 3.11.x на CentOS 7

Използване на различна система? Apache Cassandra е безплатна система за управление на база данни NoSQL с отворен код, която е проектирана да осигури мащабируемост, висока

Как да инсталирате Microweber на CentOS 7

Как да инсталирате Microweber на CentOS 7

Използване на различна система? Microweber е CMS и онлайн магазин с отворен код за плъзгане и пускане. Изходният код на Microweber се хоства на GitHub. Това ръководство ще ви покаже

Как да инсталирате Mattermost 4.1 на CentOS 7

Как да инсталирате Mattermost 4.1 на CentOS 7

Използване на различна система? Mattermost е самостоятелно хоствана алтернатива с отворен код на Slack SAAS услугата за съобщения. С други думи, с Mattermost, вие ca

Създаване на мрежа от сървъри на Minecraft с BungeeCord на Debian 8, Debian 9 или CentOS 7

Създаване на мрежа от сървъри на Minecraft с BungeeCord на Debian 8, Debian 9 или CentOS 7

Какво ви трябва Vultr VPS с поне 1 GB RAM. SSH достъп (с root/административни привилегии). Стъпка 1: Инсталиране на BungeeCord На първо място

Lets Encrypt на Plesk

Lets Encrypt на Plesk

Контролният панел на Plesk разполага с много приятна интеграция за Lets Encrypt. Lets Encrypt е един от единствените доставчици на SSL, които предоставят пълно сертификати

Позволява криптиране на cPanel

Позволява криптиране на cPanel

Lets Encrypt е сертифициращ орган, посветен на предоставянето на SSL сертификати безплатно. cPanel изгради чиста интеграция, така че вие ​​и вашият клиент

Как да инсталирате Concrete5 на CentOS 7

Как да инсталирате Concrete5 на CentOS 7

Използване на различна система? Concrete5 е CMS с отворен код, който предлага много отличителни и полезни функции за подпомагане на редакторите при лесното създаване на съдържание и

Как да инсталирате табло за преглед на CentOS 7

Как да инсталирате табло за преглед на CentOS 7

Използване на различна система? Review Board е безплатен инструмент с отворен код за преглед на изходен код, документация, изображения и много други. Това е уеб базиран софтуер

Настройте HTTP удостоверяване с Nginx на CentOS 7

Настройте HTTP удостоверяване с Nginx на CentOS 7

В това ръководство ще научите как да настроите HTTP удостоверяване за уеб сървър на Nginx, работещ на CentOS 7. Изисквания За да започнете, ще ви трябва

Как да инсталирате YOURLS на CentOS 7

Как да инсталирате YOURLS на CentOS 7

YOURLS (Your Own URL Shortener) е приложение за съкращаване на URL адреси и анализ на данни с отворен код. В тази статия ще разгледаме процеса на инсталиране

Как да инсталирате и конфигурирате ArangoDB на CentOS 7

Как да инсталирате и конфигурирате ArangoDB на CentOS 7

Използване на различна система? Въведение ArangoDB е NoSQL база данни с отворен код с гъвкав модел на данни за документи, графики и ключ-стойности. то е

Използване на Etckeeper за контрол на версиите на /etc

Използване на Etckeeper за контрол на версиите на /etc

Въведение Директорията /etc/ играе критична роля в начина, по който функционира една Linux система. Причината за това е, че почти всяка системна конфигурация

Защо трябва да използвате SSHFS? Как да монтирате отдалечена файлова система със SSHFS на CentOS 6

Защо трябва да използвате SSHFS? Как да монтирате отдалечена файлова система със SSHFS на CentOS 6

Много системни администратори управляват големи количества сървъри. Когато файловете трябва да бъдат достъпни на различни сървъри, влизането във всеки от тях поотделно ок

Настройване на сървър на Half Life 2 на CentOS 6

Настройване на сървър на Half Life 2 на CentOS 6

Този урок ще обхване процеса на инсталиране на сървър за игри Half Life 2 на CentOS 6 System. Стъпка 1: Инсталиране на предпоставките За да настроите ou

Как да инсталирате Laravel GitScrum на CentOS 7

Как да инсталирате Laravel GitScrum на CentOS 7

Laravel GitScrum или GitScrum е инструмент за производителност с отворен код, предназначен да помогне на екипите за разработка да внедрят методологията на Scrum по подобен начин.

Възходът на машините: Реални приложения на AI

Възходът на машините: Реални приложения на AI

Изкуственият интелект не е в бъдещето, тук е точно в настоящето. В този блог Прочетете как приложенията за изкуствен интелект са повлияли на различни сектори.

DDOS атаки: кратък преглед

DDOS атаки: кратък преглед

Вие също сте жертва на DDOS атаки и сте объркани относно методите за превенция? Прочетете тази статия, за да разрешите вашите запитвания.

Чудили ли сте се как хакерите печелят пари?

Чудили ли сте се как хакерите печелят пари?

Може би сте чували, че хакерите печелят много пари, но чудили ли сте се някога как печелят такива пари? нека обсъдим.

Революционни изобретения на Google, които ще улеснят живота ви.

Революционни изобретения на Google, които ще улеснят живота ви.

Искате ли да видите революционни изобретения на Google и как тези изобретения промениха живота на всяко човешко същество днес? След това прочетете в блога, за да видите изобретенията на Google.

Friday Essential: Какво се случи с колите, задвижвани от изкуствен интелект?

Friday Essential: Какво се случи с колите, задвижвани от изкуствен интелект?

Концепцията за самоуправляващи се автомобили да тръгват по пътищата с помощта на изкуствен интелект е мечта, която имаме от известно време. Но въпреки няколкото обещания, те не се виждат никъде. Прочетете този блог, за да научите повече…

Технологична сингулярност: далечно бъдеще на човешката цивилизация?

Технологична сингулярност: далечно бъдеще на човешката цивилизация?

Тъй като науката се развива с бързи темпове, поемайки много от нашите усилия, рискът да се подложим на необяснима сингулярност също нараства. Прочетете какво може да означава сингулярността за нас.

Еволюция на съхранението на данни – инфографика

Еволюция на съхранението на данни – инфографика

Методите за съхранение на данните може да се развиват от раждането на данните. Този блог обхваща развитието на съхранението на данни на базата на инфографика.

Функционалности на референтните архитектурни слоеве за големи данни

Функционалности на референтните архитектурни слоеве за големи данни

Прочетете блога, за да разберете различни слоеве в архитектурата на големи данни и техните функционалности по най-простия начин.

6 невероятни предимства от наличието на интелигентни домашни устройства в живота ни

6 невероятни предимства от наличието на интелигентни домашни устройства в живота ни

В този дигитално задвижван свят устройствата за интелигентен дом се превърнаха в решаваща част от живота. Ето няколко невероятни предимства на интелигентните домашни устройства за това как те правят живота ни струващ и по-опростен.

Актуализацията на допълнението на macOS Catalina 10.15.4 причинява повече проблеми, отколкото решава

Актуализацията на допълнението на macOS Catalina 10.15.4 причинява повече проблеми, отколкото решава

Наскоро Apple пусна macOS Catalina 10.15.4 допълнителна актуализация за отстраняване на проблеми, но изглежда, че актуализацията причинява повече проблеми, водещи до блокиране на mac машини. Прочетете тази статия, за да научите повече