CentOS8 + Naigos でシステム監視を行う方法

ソフトウエア

<景品表示法に基づく表記> 本サイトのコンテンツには、商品プロモーションが含まれている場合があります。

Nagiosを利用してシステム監視を行いたい!どうやって構築するの?

この疑問に回答します。

システム監視を行うにはNagiosを利用するのが便利です。滅多に構築する機会がないので改めてまとめていきます。

システム監視 Nagios とは

Nagios(ナギオス)とは、オープンソース統合監視ツールのことです。サーバー(リソース・サービス)、ネットワークなどの稼働状況を監視し、異常時に通知を行うことができます。

Nagios を含むリポジトリの追加

私は、CentSO8を最小パッケージでインストールを実施しています。Nagiosのパッケージを含むリポジトリがインストールされていないので、始めに必要なリポジトリの追加を行います。

# dnf -y install epel-release

Nagiosをインストール

Nagiosを動作させるには、Apache や phpなどをインストールする必要があります。事前に準備をおこなってください。

# dnf -y install nagios nagios-plugins-nrpe nagios-plugins-ping

Nagiosの設定

Nagios の設定ファイル(/etc/nagios/nagios.cfg)は、ほぼ初期設定のままで動作します。

Nagios アクセス制御の解除

Nagiosの初期設定は、アクセス制限が導入されているので解除します。

# vi /etc/nagios/cgi.conf
use_authentication=0 ← 「0」に変更

「use_authentication」パラメーターの設定変更を忘れると、Nagiosのサーバー一覧にエラーが表示されます。ご注意ください。

Nagiosアクセス制御によるエラー
Nagiosアクセス制御によるエラー
It appears as though you do not have permission to view information for any of the hosts you requested…
If you believe this is an error, check the HTTP server authentication requirements for accessing this CGI and check the authorization options in your CGI configuration file.

Apache アクセス制御の解除

Apacheの初期設定は、アクセス制限が導入されているので解除します。修正箇所が2カ所あるので、忘れずに両方ともコメントアウトしてください。

# vi /etc/httpd/conf.d/nagios.conf
<Directory "/usr/lib64/nagios/cgi-bin/">
   ~ 中略 ~
<IfVersion >= 2.3>
#         AuthName "Nagios Access" ← コメントアウト
#         AuthType Basic ← コメントアウト
#         AuthUserFile /etc/nagios/passwd ← コメントアウト
#         Require valid-user ← コメントアウト
</IfVersion>
   ~ 中略 ~
</Directory>
      
<Directory "/usr/share/nagios/html">
  ~ 中略 ~
<IfVersion >= 2.3>
#         AuthName "Nagios Access" ← コメントアウト
#         AuthType Basic ← コメントアウト
#         AuthUserFile /etc/nagios/passwd ← コメントアウト
#         Require valid-user ← コメントアウト
</IfVersion>
  ~ 中略 ~
</Directory>

設定を変更後にサービスを起動します。

# systemctl start nagios
# systemctl enable nagios
# systemctl reload httpd

ブラウザでサーバーにアクセスします。

http://(ホスト名 or IPアドレス)/nagios/

 

Nagiosの監視画面
Nagiosの監視画面

正常に動作すると Nagios のトップページが表示されます。

アラート通知のメール設定

初期設定では nagios@localhost にメール送信されるようになっていますので修正します。

# vi /etc/nagios/objects/contacts.cfg
define contact {
    email                   nagios@localhost ;  ← メールアドレスの変更
}
# systemctl reload nagios

アラート通知先をサービス毎に変更する場合は、こちらをご確認ください。

Nagiosに監視対象を追加

Nagios に監視対象を追加する準備

Nagiosの設定ファイルを変更します。監視対象を容易に管理するために専用のディレクトリを利用します。

# mkdir /etc/nagios/servers
# vi /etc/nagios/nagios.conf
cfg_dir=/etc/nagios/servers  ← コメント無効化

Ping死活監視

監視対象が増えると管理が大変なのでサーバー毎に設定ファイルを用意します。

check_pingのコマンドオプション

# /usr/lib64/nagios/plugins/check_ping  -h

Usage:
check_ping -H <host_address> -w <wrta>,<wpl>% -c <crta>,<cpl>%
[-p packets] [-t timeout] [-4|-6]

Options:
-h, –help
Print detailed help screen
-V, –version
Print version information
–extra-opts=[section][@file]
Read options from an ini file. See
https://www.nagios-plugins.org/doc/extra-opts.html
for usage and examples.
-4, –use-ipv4
Use IPv4 connection
-6, –use-ipv6
Use IPv6 connection
-H, –hostname=HOST
host to ping
-w, –warning=THRESHOLD
warning threshold pair
-c, –critical=THRESHOLD
critical threshold pair
-p, –packets=INTEGER
number of ICMP ECHO packets to send (Default: 5)
-s, –show-resolution
show name resolution in the plugin output (DNS & IP)
-L, –link
show HTML in the plugin output (obsoleted by urlize)
-t, –timeout=INTEGER:<timeout state>
Seconds before connection times out (default: 10)
Optional “:<timeout state>” can be a state integer (0,1,2,3) or a state STRING

監視対象のサーバーを登録

# vi /etc/nagios/servers/[ホスト名].cfg
# 監視対象のサーバー情報
define host {
    use                     linux-server
    host_name               [ホスト名]
    alias                   [ホスト名]
    address                 192.168.0.1
}
# 監視するサービス
define service {
    use                     generic-service
    host_name               [ホスト名]
    service_description     PING
    check_command           check_ping!200.0,20%!600.0,60%
}

HTTP・HTTPS監視

監視対象が増えると管理が大変なのでサーバー毎に設定ファイルを用意します。

check_httpのコマンドオプション

# /usr/lib64/nagios/plugins/check_http  -h

Usage:
check_http -H | -I [-u ] [-p ]
[-J ] [-K ]
[-w ] [-c ] [-t ] [-L] [-E] [-U] [-a auth]
[-b proxy_auth] [-f <ok|warning|critical|follow|sticky|stickyport>]
[-e ] [-d string] [-s string] [-l] [-r | -R ]
[-P string] [-m :] [-4|-6] [-N] [-M ]
[-A string] [-k string] [-S ] [–sni] [–verify-host]
[-C [,]] [-T ] [-j method]
NOTE: One or both of -H and -I must be specified

Options:
-h, –help
Print detailed help screen
-V, –version
Print version information
–extra-opts=[section][@file]
Read options from an ini file. See
https://www.nagios-plugins.org/doc/extra-opts.html
for usage and examples.
-H, –hostname=ADDRESS
Host name argument for servers using host headers (virtual host)
Append a port to include it in the header (eg: example.com:5000)
-I, –IP-address=ADDRESS
IP address or name (use numeric address if possible to bypass DNS lookup).
-p, –port=INTEGER
Port number (default: 80)
-4, –use-ipv4
Use IPv4 connection
-6, –use-ipv6
Use IPv6 connection
-S, –ssl=VERSION[+]
Connect via SSL. Port defaults to 443. VERSION is optional, and prevents
auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,
1.2 = TLSv1.2). With a ‘+’ suffix, newer versions are also accepted.
–sni
Enable SSL/TLS hostname extension support (SNI)
–verify-host
Verify SSL certificate is for the -H hostname (with –sni and -S)
-C, –certificate=INTEGER[,INTEGER]
Minimum number of days a certificate has to be valid. Port defaults to 443
(When this option is used the URL is not checked by default. You can use
–continue-after-certificate to override this behavior)
–continue-after-certificate
Allows the HTTP check to continue after performing the certificate check.
Does nothing unless -C is used.
-J, –client-cert=FILE
Name of file that contains the client certificate (PEM format)
to be used in establishing the SSL session
-K, –private-key=FILE
Name of file containing the private key (PEM format)
matching the client certificate
-e, –expect=STRING
Comma-delimited list of strings, at least one of them is expected in
the first (status) line of the server response (default: HTTP/1.)
If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)
-d, –header-string=STRING
String to expect in the response headers
-s, –string=STRING
String to expect in the content
-u, –uri=PATH
URI to GET or POST (default: /)
–url=PATH
(deprecated) URL to GET or POST (default: /)
-P, –post=STRING
URL encoded http POST data
-j, –method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)
Set HTTP method.
-N, –no-body
Don’t wait for document body: stop reading after headers.
(Note that this still does an HTTP GET or POST, not a HEAD.)
-M, –max-age=SECONDS
Warn if document is more than SECONDS old. the number can also be of
the form “10m” for minutes, “10h” for hours, or “10d” for days.
-T, –content-type=STRING
specify Content-Type header media type when POSTing

-l, –linespan
Allow regex to span newlines (must precede -r or -R)
-r, –regex, –ereg=STRING
Search page for regex STRING
-R, –eregi=STRING
Search page for case-insensitive regex STRING
–invert-regex
Return CRITICAL if found, OK if not

-a, –authorization=AUTH_PAIR
Username:password on sites with basic authentication
-b, –proxy-authorization=AUTH_PAIR
Username:password on proxy-servers with basic authentication
-A, –useragent=STRING
String to be sent in http header as “User Agent”
-k, –header=STRING
Any other tags to be sent in http header. Use multiple times for additional headers
-E, –extended-perfdata
Print additional performance data
-U, –show-url
Print URL in msg output in plain text
-L, –link
Wrap output in HTML link (obsoleted by urlize)
-f, –onredirect=<ok|warning|critical|follow|sticky|stickyport>
How to handle redirected pages. sticky is like follow but stick to the
specified IP address. stickyport also ensures port stays the same.
-m, –pagesize=INTEGER<:INTEGER>
Minimum page size required (bytes) : Maximum page size required (bytes)
-w, –warning=DOUBLE
Response time to result in warning status (seconds)
-c, –critical=DOUBLE
Response time to result in critical status (seconds)
-t, –timeout=INTEGER:
Seconds before connection times out (default: 10)
Optional “:” can be a state integer (0,1,2,3) or a state STRING
-v, –verbose
Show details for command-line debugging (Nagios may truncate output)

監視対象のサーバーを登録

デフォルトの監視条件だと、ステータスコードが「200」だとOKになります。

# vi /etc/nagios/servers/[ホスト名].cfg
# 監視対象のサーバー情報
define host {
    use                     linux-server
    host_name               [ホスト名]
    alias                   [ホスト名]
    address                 192.168.0.1
}
# 監視するサービス
define service {
    use                     generic-service
    host_name               [ホスト名]
    service_description     HTTP
    check_command           check_http
}

ページの内容も監視条件に追加

ステータスコードが「200」だけでなく、ページの内容をチェックする

「/etc/nagios/objects/commands.cfg」に修正を加えます。

# vi /etc/nagios/objects/commands.cfg
define command{
        command_name    check_http_string
        command_line    $USER1$/check_http -I $HOSTADDRESS$ -u $ARG1$ -s $ARG2$
}

引数に「-u $ARG1$ -s $ARG2$」を与えています。

# vi /etc/nagios/servers/[ホスト名].cfg
define service{
        use                  generic-service
        host_name            [ホスト名]
        service_description  http_checks
        check_command        check_http_string!/test.php/!status
}

引数は「!」を利用して引き渡します。

「-u」はuriを指定し、「-s」はページ内に含まれる文字列を指定します。

今回の場合は http://mydomain/test.php にアクセスしページ内に「status」という文字列が帰って来なければエラーと判断します。

HTTPSを監視

「/etc/nagios/objects/commands.cfg」に修正を加えます。

# vi /etc/nagios/objects/commands.cfg
define command{
        command_name    check_https
        command_line    $USER1$/check_http -I $HOSTADDRESS$ -S
}

監視対象を登録します。

# vi /etc/nagios/servers/[ホスト名].cfg
define service{
        use                  generic-service
        host_name            [ホスト名]
        service_description  HTTPS
        check_command        check_https
}

HTTPSを監視するには、「openssl」「openssl-devel」パッケージが必要です。ご注意ください。

何故か、apacheのログは「http」に記録されます。

ですが、正しくHTTPSで監視チェックを行っています

アクセスログを確認したところ、HTTPSはエージェント情報が記録されるようです。

=> /var/log/httpd/access_log <==
### HTTP 監視のログ
xxx.xxx.xxx.xxx - -  "GET /test.html HTTP/1.0" 200 5

### HTTPS 監視のログ
xxx.xxx.xxx.xxx - -  "GET /test.html HTTP/1.0" 200 5 "-" "check_http/v2.3.3 (nagios-plugins2.3.3)"

tcpdumpコマンドにて調査を行いました。

# tcpdump -i eno16777984 port 443
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eno16777984, link-type EN10MB (Ethernet), capture size 262144 bytes
[クライアントIP].50908 > [サーバーIP].https: Flags [S],   .....
[サーバーIP].https > [クライアントIP].50908: Flags [S.],  .....
[クライアントIP].50908 > [サーバーIP].https: Flags [.],  .....

HTTPS(443/tcp)で通信出来ていることを確認しました。

SMTP監視

監視対象が増えると管理が大変なのでサーバー毎に設定ファイルを用意します。

check_smtpのコマンドオプション

# /usr/lib64/nagios/plugins/check_smtp  -h

Usage:
check_smtp -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]
[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]
[-F fqdn] [-S] [-L] [-D warn days cert expire[,crit days cert expire]] [–sni] [-v]

Options:
-h, –help
Print detailed help screen
-V, –version
Print version information
–extra-opts=[section][@file]
Read options from an ini file. See
https://www.nagios-plugins.org/doc/extra-opts.html
for usage and examples.
-H, –hostname=ADDRESS
Host name, IP Address, or unix socket (must be an absolute path)
-p, –port=INTEGER
Port number (default: 25)
-4, –use-ipv4
Use IPv4 connection
-6, –use-ipv6
Use IPv6 connection
-e, –expect=STRING
String to expect in first line of server response (default: ‘220’)
-C, –command=STRING
SMTP command (may be used repeatedly)
-R, –response=STRING
Expected response to command (may be used repeatedly)
-f, –from=STRING
FROM-address to include in MAIL command, required by Exchange 2000
-F, –fqdn=STRING
FQDN used for HELO
-r, –proxy
Use PROXY protocol prefix for the connection.
-D, –certificate=INTEGER[,INTEGER]
Minimum number of days a certificate has to be valid.
-S, –starttls
Use STARTTLS for the connection.
–sni
Enable SSL/TLS hostname extension support (SNI)
-A, –authtype=STRING
SMTP AUTH type to check (default none, only LOGIN supported)
-U, –authuser=STRING
SMTP AUTH username
-P, –authpass=STRING
SMTP AUTH password
-L, –lmtp
Send LHLO instead of HELO/EHLO
-q, –ignore-quit-failure
Ignore failure when sending QUIT command to server
-w, –warning=DOUBLE
Response time to result in warning status (seconds)
-c, –critical=DOUBLE
Response time to result in critical status (seconds)
-t, –timeout=INTEGER:<timeout state>
Seconds before connection times out (default: 10)
Optional “:<timeout state>” can be a state integer (0,1,2,3) or a state STRING
-v, –verbose
Show details for command-line debugging (Nagios may truncate output)

監視対象のサーバーを登録

# vi /etc/nagios/servers/[ホスト名].cfg
# 監視対象のサーバー情報
define host {
    use                     linux-server
    host_name               [ホスト名]
    alias                   [ホスト名]
    address                 192.168.0.1
}
# 監視するサービス
define service {
    use                     generic-service
    host_name               [ホスト名]
    service_description     SMTP
    check_command           check_smtp
}

SSH監視

監視対象が増えると管理が大変なのでサーバー毎に設定ファイルを用意します。

# vi /etc/nagios/servers/[ホスト名].cfg

check_sshのコマンドオプション

# /usr/lib64/nagios/plugins/check_ssh  -h

Usage:
check_ssh [-4|-6] [-t <timeout>] [-r <remote version>] [-p <port>] <host>

Options:
-h, –help
Print detailed help screen
-V, –version
Print version information
–extra-opts=[section][@file]
Read options from an ini file. See
https://www.nagios-plugins.org/doc/extra-opts.html
for usage and examples.
-H, –hostname=ADDRESS
Host name, IP Address, or unix socket (must be an absolute path)
-p, –port=INTEGER
Port number (default: 22)
-4, –use-ipv4
Use IPv4 connection
-6, –use-ipv6
Use IPv6 connection
-t, –timeout=INTEGER:<timeout state>
Seconds before connection times out (default: 10)
Optional “:<timeout state>” can be a state integer (0,1,2,3) or a state STRING
-r, –remote-version=STRING
Alert if string doesn’t match expected server version (ex: OpenSSH_3.9p1)
-P, –remote-protocol=STRING
Alert if protocol doesn’t match expected protocol version (ex: 2.0)
-v, –verbose
Show details for command-line debugging (Nagios may truncate output)

監視対象のサーバーを登録

# 監視対象のサーバー情報
define host {
    use                     linux-server
    host_name               [ホスト名]
    alias                   [ホスト名]
    address                 192.168.0.1
}
# 監視するサービス
define service {
    use                     generic-service
    host_name               [ホスト名]
    service_description     SSH
    check_command           check_ssh
}

 

 

監視対象のサーバーを登録(リソース監視)

リソースのリモート監視(nrpe)の詳細はこちらをご確認ください。

Nagios 設定ファイルの文法チェック

Nagios 設定ファイルの文法をチェックします。

# nagios -v /etc/nagios/nagios.cfg

Nagios Core 4.4.5
Copyright (c) 2009-present Nagios Core Development Team and Community Contributors
Copyright (c) 1999-2009 Ethan Galstad
Last Modified: 2019-08-20
License: GPL

Website: https://www.nagios.org
Reading configuration data...
   Read main config file okay...
   Read object config files okay...

Running pre-flight check on configuration data...

Checking objects...
        Checked 9 services.
        Checked 2 hosts.
        Checked 1 host groups.
        Checked 0 service groups.
        Checked 1 contacts.
        Checked 1 contact groups.
        Checked 24 commands.
        Checked 5 time periods.
        Checked 0 host escalations.
        Checked 0 service escalations.
Checking for circular paths...
        Checked 2 hosts
        Checked 0 service dependencies
        Checked 0 host dependencies
        Checked 5 timeperiods
Checking global event handlers...
Checking obsessive compulsive processor commands...
Checking misc settings...

Total Warnings: 0 ← ここを確認
Total Errors:   0 ← ここを確認

Things look okay - No serious problems were detected during the pre-flight check

変更した設定をNagios サービスに反映させます。

# systemctl reload nagios

関連記事 Amazonで【Nagios統合監視リファレンス】をお得に買う方法

 

 

以上、「CentOS8 + Naigos でシステム監視を行う方法」という記事でした。