One place for hosting & domains

      Checkmk

      How To Monitor Server Health with Checkmk on Ubuntu 20.04


      The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      As a systems administrator, it’s best to know the current state of your infrastructure and services. Ideally, you want to notice failing disks or application downtimes before your users do. Monitoring tools like Checkmk can help administrators detect these issues and maintain healthy servers.

      Generally, monitoring software can track your servers’ hardware, uptime, and service statuses, and it can raise alerts when something goes wrong. In a real scenario, a monitoring system would alert you if any services go down. In a more robust one, the notifications would come shortly after any suspicious signs arose, such as increased memory usage or an abnormal amount of TCP connections.

      Many monitoring solutions offer varying degrees of complexity and feature sets, both free and commercial. In many cases, the installation, configuration, and management of these tools is difficult and time-consuming.

      Checkmk is a monitoring solution that is both robust and simpler to install. It is a self-contained software bundle that combines Nagios (a popular and open-source alerting service) with add-ons for gathering, monitoring, and graphing data. It also comes with Checkmk’s web interface — a comprehensive tool that addresses many of Nagios’s shortcomings. It offers a user-friendly dashboard, a full-featured notification system, and a repository of easy-to-install monitoring agents for many Linux distributions. If it weren’t for Checkmk’s web interface, we would have to use different views for various tasks. It wouldn’t be possible to configure all these features without resorting to extensive file modifications.

      In this guide, we will set up Checkmk on an Ubuntu 20.04 server and monitor two separate hosts. We will monitor the Ubuntu server itself and a separate CentOS 8 server, but we could use the same approach to add any number of additional hosts to our monitoring configuration.

      Prerequisites

      Step 1 — Installing Checkmk on Ubuntu

      In order to use our monitoring site, we first must install Checkmk on the Ubuntu server. This will give us all the tools we need. Checkmk provides official ready-to-use Ubuntu package files that we can use to install the software bundle.

      First, let’s update the packages list so that we have the most recent version of the repository listings:

      To browse the packages we can go to the package listing site. Ubuntu 20.04, among others, can be selected in the page menu.

      Now download the package:

      • wget https://download.checkmk.com/checkmk/1.6.0p20/check-mk-raw-1.6.0p20_0.focal_amd64.deb

      Then install the newly downloaded package:

      • sudo apt install -y ./check-mk-raw-1.6.0p20_0.focal_amd64.deb

      This command will install the Checkmk package along with all necessary dependencies, including the Apache web server that is used to provide web access to the monitoring interface.

      After the installation completes, we now can access the omd command. Try it out:

      This omd command will output the following:

      Output

      Usage (called as root): omd help Show general help . . . General Options: -V <version> set specific version, useful in combination with update/create omd COMMAND -h, --help show available options of COMMAND

      The omd command can manage all Checkmk instances on our server. It can start and stop all the monitoring services at once, and we will use it to create our Checkmk instance. First, however, we have to update our firewall settings to allow outside access to the default web ports.

      Step 2 — Adjusting the Firewall Settings

      Before we’ll be able to work with Checkmk, it’s necessary to allow outside access to the web server in the firewall configuration. Assuming that you followed the firewall configuration steps in the prerequisites, you’ll have a UFW firewall set up to restrict access to your server.

      During installation, Apache registers itself with UFW to provide an easy way to enable or disable access to Apache through the firewall.

      To allow access to Apache, use the following command:

      Now verify the changes:

      You’ll see that Apache is listed among the allowed services:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Apache ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Apache (v6) ALLOW Anywhere (v6)

      This will allow us to access the Checkmk web interface.

      In the next step, we’ll create the first Checkmk monitoring instance.

      Step 3 — Creating a Checkmk Monitoring Instance

      Checkmk uses the concept of instances, or individual installations, to isolate multiple Checkmk copies on a server. In most cases, only one copy of Checkmk is enough and that’s how we will configure the software in this guide.

      First we must give our new instance a name, and we will use monitoring throughout this text. To create the instance, type:

      • sudo omd create monitoring

      The omd tool will set up everything for us automatically. The command output will look similar to the following:

      Output

      Adding /opt/omd/sites/monitoring/tmp to /etc/fstab. Creating temporary filesystem /omd/sites/monitoring/tmp...OK Restarting Apache...OK Created new site monitoring with version 1.6.0p20.cre. The site can be started with omd start monitoring. The default web UI is available at http://your_ubuntu_server/monitoring/ The admin user for the web applications is cmkadmin with password: your-default-password (It can be changed with 'htpasswd -m ~/etc/htpasswd cmkadmin' as site user.) Please do a su - monitoring for administration of this site.

      In this output the URL address, default username, and password for accessing our monitoring interface are highlighted. The instance is now created, but it still needs to be started. To start the instance, type:

      • sudo omd start monitoring

      Now all the necessary tools and services will be started at once. At the end we’ll see an output verifying that all our services have started successfully:

      Output

      Starting mkeventd...OK Starting rrdcached...OK Starting npcd...OK Starting nagios...OK Starting apache...OK Initializing Crontab...OK

      The instance is up and running.

      To access the Checkmk instance, open http://your_ubuntu_server_ip/monitoring/ in the web browser. You will be prompted for a password. Use the default credentials printed beforehand on the screen; we will change these defaults later on.

      The Checkmk screen opens with a dashboard, which shows all our services and server statuses in lists, and it uses practical graphs resembling the Earth. Straight after installation these are empty, but we will shortly make it display statuses for our services and systems.

      Blank Checkmk dashboard

      In the next step, we will change the default password to secure the site using this interface.

      Step 4 — Changing Your Administrative Password

      During installation, Checkmk generates a random password for the cmkadmin administrative user. This password is meant to be changed upon installation, and as such it is often short and not very secure. We can change this via the web interface.

      First, open the Users page from the WATO - Configuration menu on the left. The list will show all users that currently have access to the Checkmk site. On a fresh installation it will list only two users. The first one, automation, is intended for use with automated tools; the second is the cmkadmin user we used to log in to the site.

      List of Checkmk users

      Click on the pencil icon next to the cmkadmin user to change its details, including the password.

      Edit form for Checkmk admin user

      Update the password, add an admin email, and make any other desired changes.

      After saving the changes we will be asked to log in again using our new credentials. Do so and return to the dashboard, where there is one more thing we must do to fully apply our new configuration.

      Once again open the Users page from the WATO - Configuration menu on the left. The orange button in the top left corner labeled as 1 Change tells us that we have made some changes to the configuration of Checkmk, and that we need to save and activate them. This will happen every time we change the configuration of our monitoring system, not only after editing a user’s credentials. To save and activate pending changes we have to click on this button and agree to activate the listed changes using the Activate affected option on the following screen.

      List of Checkmk users after modifications
      Activate configuration changes confirmation screen
      Successfully activated configuration changes

      After activating the changes the new user’s data is written to the configuration files and it will be used by all the system’s components. Checkmk automatically takes care of notifying individual monitoring system components, reloading them when necessary, and managing all the needed configuration files.

      The Checkmk installation is now ready for use. In the next step, we will add the first host to our monitoring system.

      Step 5 — Monitoring the First Host

      We are now ready to monitor the first host. To accomplish this, we will first install check-mk-agent on the Ubuntu server. Then, we’ll restrict access to the monitoring data using xinetd.

      The components installed with Checkmk are responsible for receiving, storing, and presenting monitoring information. They do not provide the information itself.

      To gather the actual data, we will use Checkmk agent. Designed specifically for the job, Checkmk agent can monitor all vital system components at once and report that information back to the Checkmk instance.

      Installing the agent

      The first host we will monitor will be your_ubuntu_server—the server on which we have installed the Checkmk instance itself.

      To begin, we must install the Checkmk agent. Packages for all major distributions, including Ubuntu, are available directly from the web interface. Open the Monitoring Agents page from the WATO - Configuration menu on the left. You will see the available agent downloads with the most popular packages under the first section labeled Packaged agents.

      List of available packaged monitoring agents

      The package check-mk-agent_1.6.0p20-1_all.deb is the one suited for Debian based distributions, including Ubuntu. Copy the download link for that package from the web browser and use that address to download the package:

      • wget http://your_ubuntu_server_ip/monitoring/check_mk/agents/check-mk-agent_1.6.0p20-1_all.deb

      After downloading, install the package:

      • apt install -y ./check-mk-agent_1.6.0p20-1_all.deb

      Now verify the agent installation:

      The command will output a very long text that looks like gibberish but combines all vital information about the system in one place:

      Output

      <<<check_mk>>> Version: 1.6.0p20 AgentOS: linux . . . <<<job>>> <<<local>>>

      It is the output from this command that Checkmk uses to gather status data from monitored hosts. Now, we’ll restrict access to the monitoring data with xinetd.

      Restricting Access to Monitoring Data Using xinetd

      By default, the data from check_mk_agent is served using xinetd, a mechanism that outputs data on a certain network port upon accessing it. This means that we can access the check_mk_agent by using telnet to port 6556 (the default port for Checkmk) from any other computer on the internet unless our firewall configuration disallows it.

      It is not a good security policy to publish vital information about servers to anyone on the internet. We should allow only hosts that run Checkmk and are under our supervision to access this data, so that only our monitoring system can gather it.

      If you have followed the initial server setup tutorial including the steps about setting up a firewall, then access to Checkmk agent is by default blocked. It is, however, a good practice to enforce these access restrictions directly in the service configuration and not rely only on the firewall to guard it.

      To restrict access to the agent data, we have to edit the configuration file at /etc/xinetd.d/check_mk. Open the configuration file in your favorite editor. To use nano, type:

      • sudo nano /etc/xinetd.d/check_mk

      Locate this section:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      #only_from      = 127.0.0.1 10.0.20.1 10.0.20.2
      . . .
      

      The only_from setting is responsible for restricting access to certain IP addresses. Because we are now working on monitoring the same server that Checkmk is running on, it is ok to allow only localhost to connect. Uncomment and update the configuration setting to:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      only_from      = 127.0.0.1
      . . .
      

      Save and exit the file.

      The xinetd daemon has to be restarted for changes to take place. Do so now:

      • sudo systemctl restart xinetd

      Now our agent is up and running and restricted to accept only local connections. We can proceed to configure monitoring for that host using Checkmk.

      Configuring Host in Checkmk Web Interface

      First, to add a new host to monitor we have to go to the Hosts menu in the WATO - Configuration menu on the left. From here click Create new host. We will be asked for some information about the host.

      Creating a new host in Checkmk

      The Hostname is the familiar name that Checkmk will use for the monitoring. It may be a fully-qualified domain name, but it is not necessary. In this example, we will name the host monitoring, just like the name of the Checkmk instance itself. Because monitoring is not resolvable to our IP address, we also have to provide the IP address of our server. And since we are monitoring the local host, the IP will simply be 127.0.0.1. Check the IPv4 Address box to enable the manual IP input and enter the value in the text field.

      The default configuration of the Data Sources section relies on Checkmk agent to provide monitoring data, which is fine. The Networking Segment setting is used to denote hosts on remote networks, which are characterized by a higher expected latency that is not a sign of malfunction. Since this is a local host, the default setting is fine as well.

      To save the host and configure which services will be monitored, click the Save & go to services button.

      List of available services to monitor

      Checkmk will do an automatic inventory. That means it will gather the output from the agent and decipher it to know what kinds of services it can monitor. All available services for monitoring will be on the list, including CPU load, memory usage, and free space on disks.

      To enable monitoring of all discovered services, we have to click the Monitor button under the Undecided services (currently not monitored) section. This will refresh the page, but now all services will be listed under the Monitored services section, informing us that they are indeed being monitored.

      As was the case when changing our user password, these new changes must be saved and activated before they go live. Press the 2 changes button and accept the changes using the Activate affected button. After that, the host monitoring will be up and running.

      Now you are ready to work with your server data. Take a look at the main dashboard using the Overview/Main Overview menu item on the left.

      Working with Monitoring Data

      Now let’s take a look at the main dashboard using the Overview/Main Overview menu item on the left:

      Monitoring dashboard with all services healthy

      The Earth sphere is now fully green and the table says that one host is up with no problems. We can see the full host list, which now consists of a single host, in the Hosts/All hosts view (using the menu on the left).

      List of hosts with all services healthy

      There we will see how many services are in good health (shown in green), how many are failing, and how many are pending to be checked. After clicking on the hostname we will be able to see the list of all services with their full statuses and their Perf-O-Meters. Perf-O-Meter shows the performance of a single service relative to what Checkmk considers to be good health.

      Details of a host service status

      All services that return graphable data display a graph icon next to their name. We can use that icon to get access to graphs associated with the service. Since the host monitoring is fresh, there is almost nothing on the graphs—but after some time the graphs will provide valuable information on how our service performance changes over time.

      Graphs depicting CPU load on the server

      When any of these services fails or recovers, the information will be shown on the dashboard. For failing services a red error will be shown, and the problem will also be visible on the Earth graph.

      Dashboard with one host having problems

      After recovery, everything will be shown in green as working properly, but the event log on the right will contain information about past failures.

      Dashboard with one host recovered after problems

      Now that we have explored the dashboard a little, let’s add a second host to our monitoring instance.

      Step 6 — Monitoring a Second CentOS Host

      Monitoring gets really useful when you have multiple hosts. We will now add a second server to our Checkmk instance, this time running CentOS 8.

      As with our Ubuntu server, installing Checkmk agent is necessary to gather monitoring data on CentOS. This time, however, we will need an rpm package from the Monitoring Agents page in the web interface, called check-mk-agent-1.6.0p20-1.noarch.rpm.

      First, however, we must install xinetd, which by default is not available on the CentOS installation. Xinetd, we will remember, is a daemon that is responsible for making the monitoring data provided by check_mk_agent available over the network.

      On your CentOS server, first install xinetd:

      • sudo dnf install -y xinetd

      Now we can download and install the monitoring agent package needed for our CentOS server:

      • sudo dnf install -y http://your_ubuntu_server_ip/monitoring/check_mk/agents/check-mk-agent-1.6.0p20-1.noarch.rpm

      Just like before, we can verify that the agent is working properly by executing check_mk_agent:

      The output will be similar to that from the Ubuntu server. Now we will restrict access to the agent.

      Restricting Access

      This time we will not be monitoring a local host, so xinetd must allow connections coming from the Ubuntu server, where Checkmk is installed, to gather the data. To allow that, first open your configuration file:

      • sudo vi /etc/xinetd.d/check_mk

      Here you will see the configuration for your check_mk service, specifying how Checkmk agent can be accessed through the xinetd daemon. Find the following two commented lines:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      #only_from      = 127.0.0.1 10.0.20.1 10.0.20.2
      . . .
      

      Now uncomment the second line and replace the local IP addresses with your_ubuntu_server_ip:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      only_from      = your_ubuntu_server_ip
      . . .
      

      Save and exit the file by typing :x and then ENTER. Restart the xinetd service using:

      • sudo systemctl restart xinetd

      If you have configured local firewall following the initial server setup tutorial, it is also necessary to adjust the firewall settings. Without doing so, connections to Checkmk agent won’t be allowed. To do so, execute:

      • sudo firewall-cmd --add-port=6556/tcp --permanent

      This would allow incoming TCP traffic to port 6556 which is used by Checkmk. The configuration will update after you reload the firewall:

      • sudo firewall-cmd --reload

      Note: You can learn how to fine tune the firewall settings by following the How To Set Up a Firewall Using firewalld on CentOS 8 guide.

      We can now proceed to configure Checkmk to monitor our CentOS 8 host.

      Configuring the New Host in Checkmk

      To add additional hosts to Checkmk, we use the Hosts menu just like before. This time we will name the host centos, configure its IP address, and choose WAN (high-latency) under the Networking Segment select box, since the host is on another network. If we skipped this and left it as local, Checkmk would soon alert us that the host is down, since it would expect it to respond to agent queries much quicker than is possible over the internet.

      Creating second host configuration screen

      Click Save & go to services, which will show services available for monitoring on the CentOS server. The list will be very similar to the one from the first host. Again, this time we also must click Monitor and then activate the changes using the orange button on the top left corner.

      After activating the changes, we can verify that the host is monitored on the All hosts page. Go there. Two hosts, monitoring and centos, will now be visible.

      List of hosts with two hosts being monitored

      You are now monitoring an Ubuntu server and a CentOS server with Checkmk. It is possible to monitor even more hosts. In fact, there is no upper limit other than server performance, which should not be a problem until your hosts number in the hundreds. Moreover, the procedure is the same for any other host. Checkmk agents in deb and rpm packages work on Ubuntu, CentOS, and the majority of other Linux distributions.

      Conclusion

      In this guide we set up two servers with two different Linux distributions: Ubuntu and CentOS. We then installed and configured Checkmk to monitor both servers, and explored Checkmk’s powerful web interface.

      Checkmk allows for the easy setup of a complete and versatile monitoring system, which packs all the hard work of manual configuration into an easy-to-use web interface full of options and features. With these tools it is possible to monitor multiple hosts; set up email, SMS, or push notifications for problems; set up additional checks for more services; monitor accessibility and performance, and so on.

      To learn more about Checkmk, make sure to visit the official documentation.



      Source link

      Überwachen des Serverzustands mit Checkmk unter Ubuntu 18.04


      Der Autor hat den Open Internet/Free Speech Fund dazu ausgewählt, eine Spende im Rahmen des Programms Write for DOnations zu erhalten.

      Einführung

      Als Systemadministrator ist es eine bewährte Vorgehensweise, den aktuellen Zustand Ihrer Infrastruktur und Diensten zu kennen. Im Idealfall möchten Sie ausfallende Festplatten oder Anwendungsausfälle möglichst vor den Benutzern erkennen. Überwachungs-Tools wie Checkmk helfen Administratoren, diese Probleme zu erkennen und für einwandfreien Serverbetrieb zu sorgen.

      Im Allgemeinen kann Überwachungssoftware die Hardware, die Betriebszeit und den Servicestatus Ihrer Server verfolgen und Warnmeldungen ausgeben, wenn ein Fehler auftritt. In einem sehr einfachen Szenario würden Sie von einem Überwachungssystem alarmiert, wenn Dienste ausfallen. In einem robusteren Szenario würden Sie kurz nach dem Auftreten verdächtiger Anzeichen benachrichtigt werden, z. B. bei erhöhter Speichernutzung oder einer ungewöhnlichen Anzahl von TCP-Verbindungen.

      Es gibt verschiedene kostenlose und kommerzielle Überwachungslösungen mit unterschiedlichen Komplexitätsgraden und Funktionalitäten. Häufig ist die Installation, Konfiguration und Verwaltung dieser Tools kompliziert und zeitaufwändig.

      Checkmk ist jedoch eine robuste und installationsfreundliche Überwachungslösung. Als in sich geschlossenes Softwarepaket kombiniert es Nagios (populärer Open-Source-Alarmierungsdienst) mit Add-Ons zur Erfassung, Überwachung und grafischen Darstellung von Daten. Außerdem ist eine Weboberfläche von Checkmk mit dabei: ein umfassendes Tool, das viele der von Nagios bekannten Mängel ausgleicht. Es bietet ein benutzerfreundliches Dashboard, ein voll funktionsfähiges Benachrichtigungssystem und ein Repository mit einfach zu installierenden Überwachungsagenten für viele Linux-Distributionen. Ohne die Checkmk Weboberfläche müssten wir für verschiedene Aufgaben verschiedene Ansichten verwenden. All diese Funktionen zu konfigurieren, wäre ohne umfangreiche Dateiänderungen nicht möglich.

      In diesem Leitfaden richten wir Checkmk auf einem Ubuntu 18.04 Server ein und überwachen zwei separate Hosts. Wir überwachen sowohl den Ubuntu-Server selbst als auch einen separaten CentOS 7-Server. Das gleiche Prinzip lässt sich anwenden, um eine beliebige Anzahl weiterer Hosts zu einer Überwachungskonfiguration hinzuzufügen.

      Voraussetzungen

      • Ein Ubuntu 18.04-Server mit einem regulären non-root user mit sudo-Berechtigungen. In diesem Tutorial zur Server-Ersteinrichtung erfahren Sie, wie Sie den Server richtig vorbereiten.
      • Ein CentoOS7 Server mit einem regulären non-root user mit sudo-Berechtigungen. In diesem Tutorial zur Server-Ersteinrichtung erfahren Sie, wie Sie den Server richtig vorbereiten.

      Schritt 1 — Installieren von Checkmk unter Ubuntu

      Um unsere Überwachungsseite nutzen zu können, müssen wir zunächst Checkmk auf dem Ubuntu-Server installieren. Dadurch erhalten wir alle benötigten Tools. Checkmk liefert offizielle, sofort einsatzbereite Ubuntu-Paketdateien zur Installation des Softwarepakets.

      Für die neueste Version der Repository-Listen aktualisieren wir als erstes die Paketeliste:

      Auf der Paketelistenseite können die Pakete durchsucht werden. Im Seitenmenü kann unter anderem Ubuntu 18.04 ausgewählt werden.

      Laden Sie jetzt das Paket herunter:

      • wget https://checkmk.com/support/1.6.0p8/check-mk-raw-1.6.0p8_0.bionic_amd64.deb

      Installieren Sie dann das neu heruntergeladene Paket:

      • sudo apt install -y ./check-mk-raw-1.6.0p8_0.bionic_amd64.deb

      Dieser Befehl installiert das Checkmk-Paket mit allen erforderlichen Abhängigkeiten, u. a. auch den Apache-Webserver, der für den Webzugriff auf die Überwachungsoberfläche verwendet wird.

      Nach Abschluss der Installation können wir auf den Befehl omd zugreifen. Versuchen Sie es:

      Der Befehl omd gibt Folgendes aus:

      Output

      Usage (called as root): omd help Show general help . . . General Options: -V <version> set specific version, useful in combination with update/create omd COMMAND -h, --help show available options of COMMAND

      Der Befehl omd kann alle Checkmk Instanzen auf unserem Server verwalten. Er kann alle Überwachungsdienste auf einmal starten und anhalten. Außerdem nutzen wir ihn zur Erstellung unserer Checkmk Instanz. Zuerst müssen wir allerdings die Firewall-Einstellungen aktualisieren, um den externen Zugriff auf Standard-Web-Ports zu ermöglichen.

      Schritt 2 — Anpassen der Firewall-Einstellungen

      Bevor wir mit Checkmk arbeiten können, muss der externe Zugriff auf den Webserver in der Firewall-Konfiguration erlaubt werden. Wenn Sie die einzelnen Schritte zur Konfiguration der Firewall in den Voraussetzungen befolgt haben, haben Sie eine UFW-Firewalleinrichtung, die den Serverzugriff einschränkt.

      Während der Installation registriert sich Apache bei UFW, damit der Apache-Zugriff ganz einfach über die Firewall aktiviert und deaktiviert werden kann.

      Verwenden Sie den folgenden Befehl, um den Zugriff auf Apache zu ermöglichen:

      Überprüfen Sie die Änderungen:

      Sie sehen, dass Apache unter den erlaubten Diensten genannt ist:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Apache ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Apache (v6) ALLOW Anywhere (v6)

      Das ermöglicht uns den Zugriff auf die Checkmk Weboberfläche.

      Im nächsten Schritt erstellen wir die erste Checkmk Überwachungsinstanz.

      Schritt 3 — Erstellen einer Checkmk Überwachungsinstanz

      Checkmk nutzt das Prinzip von Instanzen oder einzelnen Installationen, um verschiedene Checkmk-Kopien auf einem Server zu isolieren. In den meisten Fällen genügt eine Kopie von Checkmk, und so werden wir die Software auch in diesem Leitfaden konfigurieren.

      Zuerst müssen wir unserer neuen Instanz einen Namen geben. Wir verwenden in dem gesamten Text monitoring. Geben Sie Folgendes ein, um die Instanz zu erstellen:

      • sudo omd create monitoring

      Das Tool omd richtet alles automatisch für uns ein. Die Befehlsausgabe sieht etwa wie folgt aus:

      Output

      Adding /opt/omd/sites/monitoring/tmp to /etc/fstab. Creating temporary filesystem /omd/sites/monitoring/tmp...OK Restarting Apache...OK Created new site monitoring with version 1.6.0p8.cre. The site can be started with omd start monitoring. The default web UI is available at http://your_ubuntu_server/monitoring/ The admin user for the web applications is cmkadmin with password: your-default-password (It can be changed with 'htpasswd -m ~/etc/htpasswd cmkadmin' as site user.) Please do a su - monitoring for administration of this site.

      In dieser Ausgabe sind URL-Adresse, Standard-Benutzername und Passwort für den Zugriff auf unsere Überwachungsoberfläche hervorgehoben. Die Instanz ist jetzt erstellt, muss aber noch gestartet werden. Geben Sie Folgendes ein, um die Instanz zu starten:

      • sudo omd start monitoring

      Jetzt werden alle erforderlichen Tools und Dienste sofort gestartet. Am Ende sehen wir eine Ausgabe, die bestätigt, dass alle unsere Dienste erfolgreich gestartet wurden:

      Output

      Starting mkeventd...OK Starting rrdcached...OK Starting npcd...OK Starting nagios...OK Starting apache...OK Initializing Crontab...OK

      Die Instanz wird ausgeführt.

      Öffnen Sie http://your_ubuntu_server_ip/monitoring/ im Webbrowser, um auf die Checkmk-Instanz zuzugreifen. Sie werden zur Eingabe eines Passworts aufgefordert. Verwenden Sie die auf dem Bildschirm voreingestellten Standardanmeldeinformationen. Wir werden diese später ändern.

      Der Checkmk-Bildschirm öffnet sich mit einem Dashboard, auf dem der Status aller unserer Dienste und Server aufgelistet ist. Es bietet zudem praktische Diagramme, die der Erde ähneln. Direkt nach der Installation sind diese leer. Wir werden uns aber in Kürze den Status unserer Dienste und Systeme anzeigen lassen.

      Leeres Checkmk Dashboard

      Im nächsten Schritt ändern wir das Standard-Passwort, um die Seite über diese Oberfläche zu sichern.

      Schritt 4 — Ändern des Administratorpassworts

      Während der Installation generiert Checkmk ein Zufallspasswort für den administrativen Benutzer cmkadmin. Das Passwort ist meist kurz und nicht sicher und sollte nach der Installation geändert werden. Wir können es über die Weboberfläche ändern.

      Öffnen Sie zuerst die Seite Users im Menü WATO – Configuration links. Die Liste zeigt alle Benutzer, die derzeit Zugriff auf die Seite Checkmk haben. Bei einer neuen Installation sind es nur zwei Benutzer. Der erste, automation, ist für die Verwendung mit Automatisierungstools vorgesehen. Der zweite ist der Benutzer cmkadmin, mit dem wir uns auf der Seite anmelden.

      Liste der Checkmk-Benutzer

      Klicken Sie auf das Stift-Symbol neben dem cmkadmin-Benutzer, um die Benutzerangaben, einschließlich des Passworts zu ändern.

      Bearbeitungsformular für administrative Checkmk-Benutzer

      Aktualisieren Sie das Passwort, fügen Sie eine Administrator-E-Mailadresse ein und nehmen Sie alle weiteren gewünschten Änderungen vor.

      Nach Speichern der Änderungen werden wir aufgefordert, uns erneut mit den neuen Zugangsdaten anzumelden. Tun Sie das und kehren Sie dann zum Dashboard zurück, auf dem wir noch etwas ausführen müssen, um unsere neue Konfiguration vollständig anwenden zu können.

      Öffnen Sie erneut die Seite Users im Menü WATO – Configuration links. Die orange Schaltfläche oben links mit der Bezeichnung 1 Change zeigt uns an, dass wir einige Änderungen an der Konfiguration von Checkmk vorgenommen haben, die wir noch speichern und aktivieren müssen. Das geschieht jedes Mal, wenn wir die Konfiguration des Überwachungssystems ändern, nicht nur nach der Bearbeitung der Anmeldedaten eines Benutzers. Um ausstehende Änderungen zu speichern und zu aktivieren, müssen wir auf diese Schaltfläche klicken und zustimmen, die aufgeführten Änderungen mit der Option Activate affected auf dem folgenden Bildschirm zu aktivieren.

      Liste der Checkmk-Benutzer nach Änderungen Ansicht Aktivieren der Konfigurationsänderungen bestätigenErfolgreich aktivierte Konfigurationsänderungen

      Nachdem die Änderungen aktiviert sind, werden die Daten des neuen Benutzers in die Konfigurationsdateien geschrieben und von allen Systemkomponenten verwendet. Checkmk benachrichtigt automatisch die einzelnen Komponenten des Überwachungssystems, lädt sie bei Bedarf neu und verwaltet alle notwendigen Konfigurationsdateien.

      Die Checkmk Installation ist jetzt einsatzbereit. Im nächsten Schritt fügen wir unserem Überwachungssystem den ersten Host hinzu.

      Schritt 5 — Überwachen des ersten Hosts

      Wir sind jetzt bereit, den ersten Host zu überwachen. Hierzu installieren wir zunächst check-mk-agent auf dem Ubuntu-Server. Dann beschränken wir den Zugriff auf die Überwachungsdaten mit xinetd.

      Die mit Checkmk installierten Komponenten sind für Empfang, Speicherung und Darstellung von Überwachungsdaten verantwortlich. Sie liefern die Daten nicht selbst.

      Um die eigentlichen Daten zu sammeln, verwenden wir den Checkmk Agent. Der Checkmk Agent, der speziell für diese Aufgabe entwickelt wurde, ist in der Lage, alle wichtigen Systemkomponenten auf einmal zu überwachen und diese Informationen an die Checkmk-Instanz zurückzumelden.

      Installieren des Agenten

      Der erste Host, der überwacht wird, ist your_ubuntu_server, also der Server, auf dem wir die Checkmk-Instanz installiert haben. 

      Zunächst müssen wir den Checkmk Agent installieren. Pakete für alle wichtigen Distributionen, wie z. B. Ubuntu, sind direkt auf der Weboberfläche verfügbar. Öffnen Sie die Seite Monitoring Agents im Menü WATO – Configuration links. Sie sehen die verfügbaren Agent-Downloads mit den beliebtesten Paketen unter dem ersten Abschnitt Packaged agents.

      Liste der verfügbaren Überwachungsagenten-Pakete

      Das Paket check-mk-agent_1.6.0p8-1_all.deb ist geeignet für Debian-basierte Distributionen, einschließlich Ubuntu. Kopieren Sie den Download-Link für dieses Paket aus dem Webbrowser und laden Sie das Paket unter dieser Adresse herunter.

      • wget http://your_ubuntu_server_ip/monitoring/check_mk/agents/check-mk-agent_1.6.0p8-1_all.deb

      Installieren Sie das Paket nach dem Herunterladen:

      • apt install -y ./check-mk-agent_1.6.0p8-1_all.deb

      Überprüfen Sie, ob der Agent erfolgreich installiert wurde:

      Der Befehl gibt einen sehr langen Text aus, der unverständlich wirkt, aber alle wichtigen Informationen über das System kombiniert.

      Output

      <<<check_mk>>> Version: 1.6.0p8 AgentOS: linux . . . ["monitoring"] <<<job>>> <<<local>>>

      Checkmk nutzt die Ausgabe dieses Befehls, um die Statusdaten der überwachten Hosts zu sammeln. Mit xinetd beschränken wir den Zugriff auf die Überwachungsdaten.

      Zugriffsbeschränkungen auf Überwachungsdaten mit xinetd

      Standardmäßig werden die Daten von check_mk_agent mit Hilfe von xinetd bereitgestellt, einem Mechanismus, der Daten beim Zugriff auf einen bestimmten Netzwerk-Port ausgibt. Das bedeutet, dass wir auf check_mk_agent mit Hilfe von telnet auf Port 6556 (Standard-Port für Checkmk) von jedem Computer im Internet zugreifen können, sofern die Firewall-Konfiguration dies nicht untersagt.

      Wichtige Informationen über Server sollten aus Sicherheitsgründen nicht im Internet veröffentlicht werden. Wir sollten nur Hosts, die Checkmk ausführen und von uns überwacht werden, den Datenzugriff erlauben, damit nur unser Überwachungssystem diese sammeln kann.

      Wenn Sie dem Tutorial zur Server-Ersteinrichtung gefolgt sind, darunter den Schritten zur Einrichtung einer Firewall, ist der Zugriff auf den Checkmk Agent standardmäßig blockiert. Es ist jedoch empfehlenswert, diese Zugriffsbeschränkungen direkt in der Dienstkonfiguration vorzunehmen und sich bei deren Überwachung nicht allein auf die Firewall zu verlassen.

      Um den Zugriff auf die Agentendaten zu beschränken, müssen wir die Konfigurationsdatei unter /etc/xinetd.d/check_mk bearbeiten. Öffnen Sie die Konfigurationsdatei in einem beliebigen Editor. Um Nano zu verwenden, geben Sie Folgendes ein:

      • sudo nano /etc/xinetd.d/check_mk

      Suchen Sie nach diesem Abschnitt:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      #only_from      = 127.0.0.1 10.0.20.1 10.0.20.2
      . . .
      

      Die Einstellung only_from schränkt den Zugang auf bestimmte IP-Adressen ein. Da wir nun daran arbeiten, den gleichen Server zu überwachen, auf dem Checkmk ausgeführt wird, ist es in Ordnung, nur localhost das Verbinden zu erlauben. Entfernen Sie den Kommentar und aktualisieren Sie die Konfigurationseinstellung in:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      only_from      = 127.0.0.1
      . . .
      

      Speichern und schließen Sie die Datei.

      Der xinetd Daemon muss neu gestartet werden, damit die Änderungen übernommen werden. Tun Sie das jetzt:

      • sudo systemctl restart xinetd

      Der Agent wird nun ausgeführt und ist darauf beschränkt, nur lokale Verbindungen zu akzeptieren. Wir können jetzt die Überwachung für diesen Host mit Hilfe von Checkmk konfigurieren.

      Konfigurieren des Host auf der Checkmk Weboberfläche

      Um einen neuen zu überwachenden Host hinzuzufügen, gehen wir in das Menü Hosts im Menü WATO – Configuration links. Hier klicken Sie auf Create new host. Wir werden nach einigen Informationen über den Host gefragt.

      Erstellen eines neuen Hosts in Checkmk

      Der Hostname ist der bekannte Name, den Checkmk für die Überwachung verwenden wird. Es kann sich um einen vollwertigen Domänennamen handeln, muss aber nicht. In diesem Beispiel nennen wir den Host monitoring, genau wie der Name der Checkmk-Instanz selbst. Da monitoring auf unsere IP-Adresse nicht aufgelöst werden kann, müssen wir auch die IP-Adresse unseres Servers angeben. Und da der lokale Host überwacht wird, lautet die IP einfach 127.0.0.1. Markieren Sie das Feld IPv4 Address, um die manuelle IP-Eingabe zu aktivieren und geben Sie den Wert in das Textfeld ein.

      Die Standardkonfiguration des Abschnitts Data Sources benötigt Checkmk Agent, um die Überwachungsdaten bereitzustellen. Die Einstellung Segment Networking wird verwendet, um Hosts in Remote-Netzwerken zu kennzeichnen, die eine höhere erwartete Latenz haben, was keine Fehlfunktion darstellt. Da es sich um einen lokalen Host handelt, ist die Standardeinstellung auch hier in Ordnung.

      Um den Host zu speichern und zu konfigurieren, welche Dienste überwacht werden, klicken Sie auf die Schaltfläche Save & go to services.

      Liste der verfügbaren Dienste zur Überwachung

      Checkmk führt eine automatische Bestandsaufnahme durch. Das bedeutet, dass es die Ausgabe des Agenten sammelt und entschlüsselt, um festzustellen, welche Arten von Diensten überwacht werden können. Alle verfügbaren Dienste zur Überwachung finden sich in der Liste, einschließlich der CPU-Speichernutzung und des freien Festplattenspeicherplatzes.

      Um die Überwachung aller ermittelten Dienste zu aktivieren, müssen wir unter dem Abschnitt Undecided services (currently not monitored) auf die Schaltfläche Monitor klicken. Dadurch wird die Seite aktualisiert, aber alle Dienste werden im Abschnitt Monitored services aufgelistet. Das zeigt uns, dass sie tatsächlich überwacht werden.

      So wie bei der Änderung unseres Benutzerpassworts müssen diese neuen Änderungen gespeichert und aktiviert werden, bevor sie live gehen. Betätigen Sie die Schaltfläche 2 changes und nehmen Sie die Änderungen über die Schaltfläche Activate affected an. Danach wird die Host-Überwachung ausgeführt.

      Sie können nun mit den Serverdaten arbeiten. Sehen Sie sich das Haupt-Dashboard über den Menüpunkt Overview/Main Overview links an.

      Arbeiten mit Überwachungsdaten

      Sehen wir uns das Haupt-Dashboard über den Menüpunkt Overview/Main Overview links an:

      Überwachungs-Dashboard mit allen fehlerfreien Diensten

      Die Erdkugel ist komplett grün und die Tabelle zeigt an, dass ein Host problemlos funktioniert. Wir können (über das Menü links) die vollständige Host-Liste in der Ansicht Hosts/All hosts sehen, die jetzt einen einzelnen Host enthält.

      Liste der Hosts mit allen fehlerfreien Diensten

      Dort sehen wir, wie viele Dienste fehlerfrei funktionieren (grün dargestellt), wie viele gestört sind und wie viele noch zu überprüfen sind. Nachdem wir auf den Hostnamen geklickt haben, sehen wir die Liste aller Dienste mit ihrem vollständigen Status und ihren Perf-O-Meters. Perf-O-Meter zeigt die Leistung eines einzelnen Dienstes im Verhältnis zu dem, was Checkmk als guten Zustand betrachtet.

      Details eines Host-Dienstestatus

      Alle Dienste, die diagrammfähige Daten liefern, zeigen ein Diagrammsymbol neben ihrem Namen. Über dieses Symbol lassen sich die mit dem Dienst verknüpften Diagramme öffnen. Da die Host-Überwachung noch neu ist, zeigen die Diagramme noch fast nichts. Nach einiger Zeit liefern sie jedoch wertvolle Informationen darüber, wie sich unsere Dienstleistung verändert.

      Diagramme zur Darstellung der CPU-Last auf dem Server

      Wenn einer der Dienste ausfällt oder wiederhergestellt wird, wird diese Information im Dashboard angezeigt. Ausgefallene Dienste werden mit einer roten Fehleranzeige gekennzeichnet und sind auch im Erddiagramm sichtbar.

      Dashboard mit einem Host mit Problemen

      Nach erfolgreicher Wiederherstellung wechselt die Anzeige auf Grün für ordnungsgemäßen Betrieb. Das Ereignisprotokoll rechts zeigt jedoch alle vergangenen Störungen an.

      Dashboard mit einem Host, der nach den Problemen wiederhergestellt wurde

      Nachdem wir uns das Dashboard jetzt etwas genauer angesehen haben, fügen wir einen zweiten Host zu unserer Überwachungsinstanz hinzu.

      Schritt 6 — Überwachung eines zweiten CentOS Hosts

      Überwachung ist vor allem für mehrere Hosts sehr nützlich. Wir fügen zu unserer Checkmk-Instanz einen zweiten Server hinzu. Dieser läuft unter CentOS 7.

      Wie bei unserem Ubuntu-Server ist die Installation von Checkmk Agent erforderlich, um Überwachungsdaten auf CentOS zu sammeln. Dieses Mal benötigen wir jedoch ein rpm Paket von der Seite Monitoring Agents auf der Weboberfläche, das so genannte check-mk-agent-1.6.0p8-1.noarch.rpm.

      Zuerst müssen wir jedoch xinetd installieren, das standardmäßig nicht auf der CentOS Installation verfügbar ist. Wir erinnern uns: Xinetd ist ein Daemon, der dafür verantwortlich ist, die von check_mk_agent bereitgestellten Überwachungsdaten über das Netzwerk verfügbar zu machen.

      Auf Ihrem CentOS-Server installieren Sie zuerst xinetd:

      • sudo yum install -y xinetd

      Jetzt können wir das für unseren CentOS-Server benötigte Überwachungsagenten-Paket herunterladen und installieren:

      • sudo yum install -y http://your_ubuntu_server_ip/monitoring/check_mk/agents/check-mk-agent-1.6.0p8-1.noarch.rpm

      Wie zuvor können wir überprüfen, ob der Agent richtig funktioniert, indem wir check_mk_agent ausführen:

      Die Ausgabe ist ähnlich wie die vom Ubuntu-Server. Jetzt beschränken wir den Zugriff auf den Agenten.

      Zugriff einschränken

      Dieses Mal überwachen wir keinen lokalen Host. Deshalb muss xinetd Verbindungen vom Ubuntu-Server erlauben, auf dem Checkmk installiert ist, um Daten zu sammeln. Um das zu erlauben, öffnen Sie zunächst Ihre Konfigurationsdatei:

      • sudo vi /etc/xinetd.d/check_mk

      Hier sehen Sie die Konfiguration für Ihren check_mk Dienst, die spezifiziert, wie auf Checkmk Agent über den xinetd Daemon zugegriffen werden kann. Suchen Sie nach den folgenden zwei kommentierten Zeilen:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      #only_from      = 127.0.0.1 10.0.20.1 10.0.20.2
      . . .
      

      Entfernen Sie den Kommentar der zweiten Zeile und ersetzen Sie die lokalen IP-Adressen durch your_ubuntu_server_ip:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      only_from      = your_ubuntu_server_ip
      . . .
      

      Speichern und schließen Sie die Datei. indem Sie :x und dann ENTER eingeben. Starten Sie den xinetd Dienst neu mit:

      • sudo systemctl restart xinetd

      Wir können jetzt fortfahren, um Checkmk so zu konfigurieren, dass er unseren CentOS 7-Host überwacht.

      Konfigurieren des neuen Host in Checkmk

      Um zusätzliche Hosts zu Checkmk hinzuzufügen, nutzen wir das gleiche Hosts Menü wie zuvor. Dieses Mal nennen wir den Host centos, konfigurieren seine IP-Adresse und wählen WAN (high-latency) unter dem Auswahlfeld Networking Segment, da sich der Host in einem anderen Netzwerk befindet. Wenn wir den Punkt überspringen und ihn als lokal belassen würden, würde uns Checkmk bald darauf aufmerksam machen, dass der Host nicht funktioniert, da erwartet würde, dass er auf Agentenanfragen wesentlich schneller reagierte als über das Internet möglich.

      Bildschirm Erstellen einer zweiten Host-Konfiguration

      Klicken Sie auf Save & go to services, um die für die Überwachung auf dem CentOS-Server verfügbaren Dienste anzuzeigen. Die Liste ist der des ersten Hosts sehr ähnlich. Auch diesmal müssen wir auf Monitor klicken und die Änderungen mit der orangen Schaltfläche oben links aktivieren.

      Nach Aktivierung der Änderungen können wir überprüfen, dass der Host auf der Seite All hosts überwacht wird. Gehen Sie dorthin. Es sind jetzt zwei Hosts, monitoring und centos, sichtbar.

      Liste der Hosts mit zwei überwachten Hosts

      Sie überwachen nun einen Ubuntu-Server und einen CentOS-Server mit Checkmk. Es ist möglich, noch mehr Hosts zu überwachen. Die einzige Einschränkung ist die Serverleistung. Wenn es sich jedoch nicht um mehrere hundert Hosts handelt, sollte dies kein Problem darstellen. Das Verfahren ist für jeden weiteren Host identisch. Checkmk Agenten in deb und rpm Paketen arbeiten auf Ubuntu, CentOS und den meisten anderen Linux-Distributionen.

      Zusammenfassung

      In diesem Leitfaden haben wir Ihnen gezeigt, wie Sie zwei Server mit zwei verschiedenen Linux-Distributionen einrichten: Ubuntu und CentOS. Wir haben dann Checkmk zur Überwachung der Server installiert und konfiguriert und uns die leistungsfähige Weboberfläche von Checkmk näher angesehen.

      Checkmk ermöglicht das einfache Einrichten eines kompletten, vielseitigen Überwachungssystems, das den Aufwand der manuellen Konfiguration in eine einfach zu bedienende Weboberfläche mit vielen Optionen und Funktionen verwandelt. Mit diesen Tools können Sie mehrere Hosts überwachen, E-Mail-, SMS- oder Push-Benachrichtigungen für Probleme einrichten, zusätzliche Kontrollen für weitere Dienste einrichten, Erreichbarkeit und Leistung überwachen usw.

      Um mehr über Checkmk zu erfahren, sehen Sie sich auch die offizielle Dokumentation an.



      Source link

      Cómo monitorizar el estado del servidor con Checkmk en Ubuntu 18.04


      El autor seleccionó a Open Internet/Free Speech Fund para recibir una donación como parte del programa Write for DOnations.

      Introducción

      Cómo administrador del sistema, es una buena práctica conocer el estado actual de su infraestructura y servicios. Idealmente, querrá darse cuenta de los discos que fallan o los tiempos de inactividad de la aplicación antes de que lo hagan sus usuarios. Las herramientas de monitorización como Checkmk pueden ayudar a los administradores a detectar estos problemas y a mantener los servidores en perfecto estado.

      Generalmente, el software de monitorización puede realizar un seguimiento del hardware de sus servidores, el tiempo de actividad y los estados de servicio, y puede presentar alertas si algo va mal. En un escenario muy básico, un sistema de monitorización le alertaría si algún servicio falla. En uno más robusto, las notificaciones llegarían poco después de que surja cualquier señal sospechosa, como un mayor uso de la memoria o una cantidad anormal de conexiones TCP.

      Existen muchas soluciones de monitorización disponibles que ofrecen varios grados de complejidad y conjuntos de funciones, tanto gratuitas como comerciales. En muchos casos, la instalación, configuración y gestión de estas herramientas es difícil y requieren mucho tiempo.

      Checkmk, sin embargo, es una solución de monitorización robusta y sencilla de instalar. Es un paquete de software autónomo que combina Nagios (un servicio de alertas popular y de código abierto) con complementos para recopilar, monitorizar y realizar gráficos de los datos. También cuenta con la interfaz web de Checkmk, una herramienta integral que aborda muchas de las deficiencias de Nagio. Ofrece un panel de control fácil de usar, un sistema de notificaciones completo y un repositorio de agentes de monitorización fáciles de instalar para muchas distribuciones Linux. Si no fuese por la interfaz web de Checkmk, tendríamos que utilizar diferentes vistas para diferentes tareas y no sería posible configurar todas esas funciones sin recurrir a amplias modificaciones de archivos.

      En esta guía, configuraremos Checkmk en un servidor Ubuntu 18.04 y monitorizaremos dos hosts independientes. Monitorizaremos el servidor Ubuntu también como servidor CentOS 7 independiente, pero podríamos usar el mismo enfoque para añadir cualquier cantidad de hosts adicionales a nuestra configuración de monitorización.

      Requisitos previos

      Paso 1: Instalar Checkmk en Ubuntu

      Para usar nuestro sitio de monitorización, primero debemos instalar Checkmk en el servidor Ubuntu. Esto nos proporcionará las herramientas que necesitamos. Checkmk ofrece archivos de paquete Ubuntu listos para usar que podemos utilizar para instalar nuestro paquete de software.

      Primero, vamos a utilizar la lista de paquetes para tener la versión más reciente de los listados del repositorio:

      Para examinar los paquetes, podemos ir al sitio de listado de paquetes. En el menú de la página puede seleccionarse Ubuntu 18.04 entre otros.

      Ahora, descargue el paquete:

      • wget https://checkmk.com/support/1.6.0p8/check-mk-raw-1.6.0p8_0.bionic_amd64.deb

      A continuación, instale el paquete recién descargado:

      • sudo apt install -y ./check-mk-raw-1.6.0p8_0.bionic_amd64.deb

      Este comando instalará el paquete Checkmk junto con todas las dependencias necesarias, incluyendo el servidor web Apache que se usa para proporcionar acceso web a la interfaz de monitorización.

      Tras completarse la instalación, ahora podemos acceder al comando omd. Pruébelo:

      Este comando omd generará el siguiente resultado:

      Output

      Usage (called as root): omd help Show general help . . . General Options: -V <version> set specific version, useful in combination with update/create omd COMMAND -h, --help show available options of COMMAND

      El comando omd puede gestionar todas las instancias Checkmk en nuestro servidor. Puede iniciar y detener todos los servicios de monitorización a la vez, y podremos utilizarlo para crear nuestra instancia Checkmk. Primero, sin embargo, tenemos que actualizar los ajustes de nuestro firewall para permitir el acceso externo a los puertos web predeterminados.

      Paso 2: Configurar el firewall

      Antes de poder trabajar con Checkmk, es necesario permitir el acceso externo al servidor web en la configuración del firewall. Asumiendo que siguió los pasos de configuración del firewall en los requisitos previos, tendrá un firewall UFW configurado para restringir el acceso a su servidor.

      Durante la instalación, Apache se registra con UFW para proporcionar una forma sencilla de habilitar o deshabilitar el acceso a Apache a través del firewall.

      Para permitir el acceso a Apache, utilice el siguiente comando:

      Ahora, verifique los cambios:

      Verá que Apache está listado entre los servicios permitidos:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Apache ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Apache (v6) ALLOW Anywhere (v6)

      Esto nos permitirá acceder a la interfaz web de Checkmk.

      En el siguiente paso, crearemos la primera instancia de monitorización de Checkmk.

      Paso 3: Crear una instancia de monitorización de Checkmk

      Checkmk utiliza el concepto de instancias, o instalaciones individuales, para aislar múltiples copias de Checkmk en un servidor. En la mayoría de los casos, una única copia de Checkmk es suficiente y así es como configuraremos el software en esta guía.

      Primero, debemos proporcionar un nombre a nuestra nueva instancia, y usaremos monitoring en este texto Para crear la instancia, escriba:

      • sudo omd create monitoring

      La herramienta omd configurará todo automáticamente. El comando debe tener un aspecto similar al siguiente:

      Output

      Adding /opt/omd/sites/monitoring/tmp to /etc/fstab. Creating temporary filesystem /omd/sites/monitoring/tmp...OK Restarting Apache...OK Created new site monitoring with version 1.6.0p8.cre. The site can be started with omd start monitoring. The default web UI is available at http://your_ubuntu_server/monitoring/ The admin user for the web applications is cmkadmin with password: your-default-password (It can be changed with 'htpasswd -m ~/etc/htpasswd cmkadmin' as site user.) Please do a su - monitoring for administration of this site.

      En este resultado, se resaltarán la dirección URL, nombre predeterminado del usuario y contraseña para acceder a nuestra interfaz de monitorización. La instancia se crea ahora, pero aún debe iniciarse. Para iniciar la instancia, escriba:

      • sudo omd start monitoring

      Ahora, todas las herramientas y servicios necesarios se iniciarán a la vez. Al final, veremos un resultado que verifica que todos nuestros servicios se han iniciado correctamente:

      Output

      Starting mkeventd...OK Starting rrdcached...OK Starting npcd...OK Starting nagios...OK Starting apache...OK Initializing Crontab...OK

      La instancia está lista.

      Para acceder a la instancia Checkmk, abra http://your_ubuntu_server_ip/monitoring/ en el navegador web. Se le solicitará una contraseña. Utilice las credenciales predeterminadas impresas previamente en la pantalla; cambiaremos estos valores predeterminados más adelante.

      La pantalla de Checkmk se abre con un panel de control, que muestra todos nuestros servicios y los estados del servidor en listas, y utiliza gráficos prácticos que se parecen a la Tierra. Justo después de la instalación, estos están vacíos, pero pronto se mostrarán estados para nuestros servicios y sistemas.

      Panel de control en blanco de Checkmk

      En el siguiente paso, cambiaremos la contraseña predeterminada para proteger el sitio usando esta interfaz.

      Paso 4: Cambiar su contraseña administrativa

      Durante la instalación, Checkmk genera una contraseña aleatoria para el usuario administrativo cmkadmin. Esta contraseña debe cambiarse tras la instalación, y como tal, a menudo es corta y no muy segura. Podemos cambiar esto a través de la interfaz web.

      Primero, abra la página Users desde el menú WATO – Configuration a la izquierda. La lista mostrará todos los usuarios que actualmente tiene acceso al sitio de Checkmk. En una nueva instalación, listará solo dos usuarios. El primero, automation, está destinado a ser usado con herramientas automatizadas; el segundo es el usuario cmkadmin, que usamos para iniciar sesión en el sitio.

      Lista de usuarios Checkmk

      Haga clic en el icono de lápiz junto al usuario cmkadmin para cambiar sus detalles, incluyendo la contraseña.

      Formulario de edición para el usuario admin de Checkmk

      Actualice la contraseña, añada un correo electrónico de administrador y realice cualquier otro cambio que quiera.

      Tras guardar los cambios, nos solicitará que iniciemos sesión de nuevo con nuestras nuevas credenciales. Haga esto y vuelva al panel de control, donde hay una cosa más que debemos hacer para aplicar por completo nuestra nueva configuración.

      De nuevo, abra la página Users desde el menú WATO – Configuration a la izquierda. El botón naranja en la esquina superior derecha etiquetado como 1 Change nos indica que hemos realizado algunos cambios a la configuración de Checkmk, y que debemos guardarlos y activarlos. Esto sucederá cada vez que cambiemos la configuración de nuestro sistema de monitorización, no solo tras editar las credenciales del usuario. Para guardar y activar los cambios pendientes, debemos hacer clic en este botón y aceptar activar los cambios enumerados usando la opción Activate affected en la siguiente pantalla.

      Lista de usuarios de Checkmk tras las modificaciones Activar la pantalla de configuración en los cambios de configuración Cambios de configuración activados correctamente

      Tras activar los cambios los datos del nuevo usuario se escriben en los archivos de configuración serán usados por todos los componentes del sistema. Checkmk notifica automáticamente a los componentes individuales del sistema de monitorización, recargándolos cuando sea necesario y administrando todos los archivos de configuración necesarios.

      La instalación de Chekmk ahora está lista para usarse. En el siguiente paso, añadiremos el primer host a nuestro sistema de monitorización.

      Paso 5: Monitorizar el primer host

      Ahora estamos listos para monitorizar el primer host. Para conseguir esto, primero instalaremos check-mk-agent en el servidor Ubuntu. A continuación, restringiremos el acceso a los datos de monitorización usando xinetd.

      Los componentes instalados con Checkmk se encargan de recibir, almacenar y presentar la información de monitorización. No proporcionan información en sí mismos.

      Para recopilar datos reales, usaremos el agente de Checkmk. Diseñado específicamente para este trabajo, el agente de Checkmk es capaz de monitorizar todos los componentes vitales del sistema a la vez y de reportar esa información a la instancia de Checkmk.

      Instalar el agente

      El primer host que monitorizaremos será your_ubuntu_server, el servidor sobre el cual hemos instalado la instancia Checkmk.

      Para comenzar, debemos instalar el agente de Checkmk. Los paquetes para todas las distribuciones principales, incluyendo Ubuntu, están disponibles directamente desde la interfaz web. Abra la página Monitoring Agents desde el menú WATO – Configuration a la izquierda. Verá las descargas de agente disponibles con los paquetes más populares bajo la primera sección, etiquetada como Packaged agents.

      Lista de agentes de monitorización empaquetados disponibles

      El paquete check-mk-agent_1.6.0p8-18_all.ded es el adecuado para las distribuciones basadas en Debian, incluyendo Ubuntu. Copie el enlace de descarga para ese paquete desde el navegador web y utilice esa dirección para descargar el paquete.

      • wget http://your_ubuntu_server_ip/monitoring/check_mk/agents/check-mk-agent_1.6.0p8-1_all.deb

      Tras su descarga, instale el paquete:

      • apt install -y ./check-mk-agent_1.6.0p8-1_all.deb

      Ahora, verifique que el agente se ha instalado correctamente:

      El comando generará un texto muy largo que parece un texto sin sentido, pero combina toda la información vital sobre el sistema en un solo lugar.

      Output

      <<<check_mk>>> Version: 1.6.0p8 AgentOS: linux . . . ["monitoring"] <<<job>>> <<<local>>>

      Checkmk utiliza el resultado de este comando para recopilar datos de esto desde los hosts monitorizados. Ahora, restringiremos el acceso a los datos de monitorización usando xinetd.

      Restringir el acceso a los datos de monitorización utilizando xinetd

      Por defecto, los datos de check_mk_agent se presentan usando xinetd, un mecanismo que genera datos sobre un cierto puerto de red tras acceder a él. Esto significa que podemos acceder a chek_mk_agent usando telnet al puerto 6556 (el puerto predeterminado para Checkmk) desde cualquier otro equipo en Internet a menos que la configuración de nuestro firewall no lo permita.

      No es una buena política de seguridad publicar información vital sobre los servidores a nadie en Internet. Solo deberíamos permitir a los hosts que ejecuten Checkmk y estén bajo supervisión acceder a estos datos, de forma que solo nuestro sistema de monitorización pueda recopilarlos.

      Si siguió el tutorial de configuración inicial del servidor, incluyendo los pasos sobre cómo configurar un firewall, el acceso al agente Checkmk está bloqueado por defecto. Sin embargo, es una buena práctica aplicar estas restricciones de acceso directamente en la configuración del servicio, y no depender únicamente de un firewall para su protección.

      Para restringir el acceso a los datos del agente, tenemos que editar el archivo de configuración en /etc/xinetd.d/check_mk. Abra el archivo de configuración en su editor favorito. Para utilizar nano, escriba:

      • sudo nano /etc/xinetd.d/check_mk

      Localice esta sección:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      #only_from      = 127.0.0.1 10.0.20.1 10.0.20.2
      . . .
      

      El ajuste only_from se encarga de restringir el acceso a ciertas direcciones IP. Debido a que ahora estamos trabajando en monitorizar el mismo servidor sobre el que Checkmk se está ejecutando, está bien permitir que localhost se conecte. Elimine y actualice el ajuste de configuración a:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      only_from      = 127.0.0.1
      . . .
      

      Guarde el archivo y ciérrelo.

      El daemon xinetd debe reiniciarse para que los cambios surtan efecto. Hágalo ahora:

      • sudo systemctl restart xinetd

      Ahora, nuestro agente está en funcionamiento y restringido para aceptar solo las conexiones locales. Podemos proceder a configurar la monitorización para ese host usando Checkmk.

      Configurar el host en la interfaz web de Checkmk

      Primero, para añadir un nuevo host a monitorizar tenemos que ir al menú Hosts en el menú WATO – Configuration a la izquierda. Desde aquí, haga clic en Create new host. Se nos solicitará cierta información sobre el host.

      Creación de un nuevo host en Checkmk

      El Hostname es el nombre familiar que Checkmk usará para la monitorización. Puede ser un nombre de dominio completamente cualificado, pero no es necesario. En este ejemplo, llamaremos al host monitoring, igual que el nombre de la instancia Checkmk. Debido a que monitoring no se resuelve a nuestra dirección IP, también debemos proporcionar la dirección IP de nuestro servidor. Y ya que estamos monitorizando el host local, la IP será simplemente 127.0.0.1. Seleccione la casilla IPv4 Address para habilitar la entrada manual de la IP e introduzca el valor en el campo de texto.

      La configuración predeterminada de la sección Data Sources depende del agente Checkmk para proporcionar los datos de monitorización, lo que está bien. El ajuste Networking Segment se usa para indicar los hosts en las redes remotas, que se caracterizan por una mayor latencia esperada, lo cual no es una señal de mal funcionamiento. Ya que este es un host local, el ajuste predeterminado también está bien.

      Para guardar el host y configurar qué servicios se monitorizarán, haga clic en el botón Save & go to services.

      Lista de servicios disponibles para monitorizar

      Checkmk realizará un inventario automático. Eso significa que recopilará el resultado del agente y lo descifrará para saber qué tipos de servicios puede monitorizar. Todos los servicios disponibles para la monitorización estarán en la lista, incluyendo carga de CPU, uso de memoria y espacio libre en los discos.

      Para habilitar la monitorización de todos los servicios descubiertos, debemos hacer clic en el botón Monitor bajo la sección Undecided services (currently not monitored). Esto actualizará la página, pero ahora todos los servicios se listarán bajo la sección Monitored services, informándonos de que están siendo monitorizados.

      Igual que cuando cambiamos nuestra contraseña de usuario, estos nuevos cambios deben guardarse y activarse antes de que estén activos. Pulse el botón 2 changes y acepte lo cambios usando el botón Activate affected. Tras esto, la monitorización del host estará lista.

      Ahora está listo para trabajar con los datos de su servidor. Eche un vistazo al panel de control principal utilizando el elemento de menú Overview/Main Overview (Información/Información principal) a la izquierda.

      Trabajar con los datos de la monitorización

      Ahora, vamos a ver el panel de control principal usando el menú Overview/Main Overview a la izquierda:

      Panel de control de la monitorización con todos los servicios en buen estado

      La esfera de la Tierra está completamente verde y la tabla dice que un host está activo sin problemas. Podemos ver la lista completa de hosts, que ahora consta de un único host, en la vista Hosts/All hosts (usando el menú de la izquierda).

      Lista de los hosts con todos los servicios en buen estado

      Ahí veremos cuántos servicios están en buen estado (en verde), cuántos están fallando y cuántos deben comprobarse aún. Tras hacer clic en el nombre del host, podremos ver la lista de todos los servicios con sus estados completos y sus Perf-O-Meters. El Perf-O-Meter muestra el rendimiento de un único servicio en relación con lo que Checkmk considera que es un buen estado.

      Detalles del estado de un servicio de host

      Todos los servicios que devuelven datos que pueden ponerse en un gráfico mostrarán un icono de gráfico junto a su nombre. Podemos utilizar ese ícono para obtener acceso a los gráficos asociados con el servicio. Ya que la monitorización del host es nueva, los gráficos no tienen casi nada, pero, tras algún tiempo, los gráficos proporcionarán información valiosa sobre cómo cambia el rendimiento de nuestro servicio a lo largo del tiempo.

      Gráficos que representan la carga en la CPU del servidor

      Cuando cualquiera de estos servicios falle o se recupere, la información se mostrará en el panel de control. Para los servicios que fallan, se mostrará un error en rojo, y el problema también estará visible en el gráfico de la Tierra.

      Panel de control con un host con problemas

      Tras la recuperación, todo se mostrarán en verde, lo que indica un buen funcionamiento, pero el registro de eventos de la derecha contendrá información sobre fallos anteriores.

      Panel de control con un host recuperado tras presentar problemas

      Ahora que hemos explorado el panel de control, vamos a añadir un segundo host a nuestra instancia de monitorización.

      Paso 6: Monitorizar un segundo host CentOS

      La monitorización es realmente útil cuando tiene varios hosts. Ahora añadiremos un segundo servidor a nuestra instancia Checkmk, esta vez ejecutando CentOS 7.

      Al igual que con nuestro servidor Ubuntu, es necesario instalar el agente Checkmk para recopilar datos de monitorización en CentOS. Esta vez, sin embargo, necesitaremos un paquete rpm desde la página Monitoring Agentes en la interfaz web, llamado check-mk-agent-1.6.0p8-1.noarch.rpm.

      Primero, sin embargo, debemos instalar xinetd, que por defecto no está disponible en la instalación CentOS. Xinetd, como recordará, es un daemon responsable de poner a disposición sobre la red los datos de monitorización proporcionados por check_mk_agent.

      En su servidor CentOS, primero instale xinetd:

      • sudo yum install -y xinetd

      Ahora podemos descargar e instalar el paquete del agente de monitorización necesario para nuestro servidor CentOS:

      • sudo yum install -y http://your_ubuntu_server_ip/monitoring/check_mk/agents/check-mk-agent-1.6.0p8-1.noarch.rpm

      Igual que antes, podemos verificar que el agente funciona correctamente ejecutando check_mk_agent:

      El resultado será similar al del servidor Ubuntu. Ahora, restringiremos el acceso al agente.

      Restringir el acceso

      Esta vez no monitorizaremos un host local, de forma que xinetd debe permitir las conexiones que provienen del servidor Ubuntu, donde Checkmk está instalado, para recopilar los datos. Para permitir esto, primero abra su archivo de configuración:

      • sudo vi /etc/xinetd.d/check_mk

      Aquí verá la configuración para su servicio check_mk, especificando cómo se puede acceder al agente Checkmk a través del daemon xinetd. Busque las siguientes dos líneas comentadas:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      #only_from      = 127.0.0.1 10.0.20.1 10.0.20.2
      . . .
      

      Ahora, elimine la segunda línea y sustituya las direcciones IP locales con your_ubuntu_server_ip:

      /etc/xinetd.d/check_mk

      . . .
      # configure the IP address(es) of your Nagios server here:
      only_from      = your_ubuntu_server_ip
      . . .
      

      Guarde y salga del archivo escribiendo :x y luego ENTER. Reinicie el servicio xinetd usando:

      • sudo systemctl restart xinetd

      Ahora podemos configurar Checkmk para que monitorice nuestro host CentOS 7.

      Configurar un nuevo host en Checkmk

      Para añadir hosts adicionales a Checkmk, usamos el menú Hosts como hicimos antes. Esta vez, llamaremos al host centos, configuraremos su dirección IP, y seleccionaremos WAN (high-latency) bajo la casilla de selección Networking Segment, ya que el host está en otra red. Si omitimos esto y lo dejamos como local, Checkmk pronto nos alertará de que el host está desconectado, ya que esperaría que respondiese a las consultas del agente mucho más rápido de lo que es posible por Internet.

      Crear la pantalla de configuración del segundo host

      Haga clic en Save & go to services, lo que mostrará los servicios disponibles para monitorizar sobre el servidor CentOS. La lista será muy similar a la del primer host. De nuevo, esta vez debemos hacer clic en Monitor y, luego, activar los cambios utilizando el botón naranja en la esquina superior izquierda.

      Tras activar los cambios, podemos verificar que el host está siendo monitorizado en la página All hosts. Vaya allí. Ahora estarán visibles dos hosts, monitoring y centos.

      Lista de hosts con dos hosts monitorizados

      Ahora está monitorizando un servidor Ubuntu y un servidor CentOS con Checkmk. Es posible monitorizar aún más hosts. De hecho, no hay un límite aparte del rendimiento del servidor, que no debería ser un problema hasta que su número de hosts sea de cientos. Además, el procedimiento es el mismo para cualquier otro host. Los agentes Checkmk en los paquetes deb y rpm funcionan en Ubuntu, CentOS y en la mayoría de las otras distribuciones Linux.

      Conclusión

      En esta guía hemos configurado dos servidores con dos distribuciones Linux diferentes: Ubuntu y CentOS. A continuación, instalamos y configuramos Checkmk para monitorizar ambos servidores, y exploramos la potente interfaz web de Checkmk.

      Checkmk permite configurar fácilmente un sistema de monitorización completo y versátil, que empaqueta todo el difícil trabajo de la configuración manual en una interfaz web fácil de usar con múltiples opciones y funciones. Con estas herramientas es posible monitorizar múltiples hosts; configurar correo electrónico, SMS o notificaciones push cuando se produzcan problemas; configurar comprobaciones adicionales para más servicios; monitorizar la accesibilidad y el rendimiento, etcétera.

      Para obtener más información sobre Checkmk, asegúrese de visitar la documentación oficial.



      Source link