ICINGA + pnp4nagios installation



Icinga web with pnp4nagios
PNP is an addon for the Nagios Network Monitoring System. PNP provides easy to use, easy to configure RRDTools based performance charts feeded by the performance data output of the Nagios Plugins.


Setting up icinga using repository:-
OS used in this env = CentOS release 6.5 X64bit

1. Install CentOS 6.4 minimal version

2. Prepare your system
# yum groupinstall Development tools
# yum install vim mc
3. Add EPEL and Remi repositories
# wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
# rpm -ivh epel-release-6-8.noarch.rpm
#wget http://dl.iuscommunity.org/pub/ius/stable/CentOS/6/x86_64/ius-release-1.0-13.ius.centos6.noarch.rpm
#rpm -Uvh ius-release*.rpm
4. Check your repolist[the under lined repos should be present]

5. Installing packages
#yum install php php-cli php-pear php-xmlrpc php-xsl php-pdo php-soap php-gd php-ldap php-mysql
# yum install icinga icinga-gui icinga-doc icinga-idoutils-libdbi-mysql               or    yum install icinga*
# yum install nagios-plugins-all
# yum install mysql-server mysql-client libdbi libdbi-dbd-mysql libdbi-devel icinga-idoutils-libdbi-mysql libdbi-drivers
6. Database setup
 # mysql -u root -p
 mysql> CREATE DATABASE icinga_web;
        GRANT USAGE ON *.* TO 'icinga_web'@'localhost' IDENTIFIED BY 'icinga_web' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0;
        GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX ON icinga_web.* TO 'icinga_web'@'localhost';
        quit;

#echo "CREATE DATABASE icinga; \
GRANT USAGE ON *.* TO 'icinga'@'localhost' \
  IDENTIFIED BY 'icinga' \
  WITH MAX_QUERIES_PER_HOUR 0 \
  MAX_CONNECTIONS_PER_HOUR 0 \
  MAX_UPDATES_PER_HOUR 0; \
GRANT SELECT , INSERT , UPDATE , DELETE, DROP, CREATE VIEW \
  ON icinga.* TO 'icinga'@'localhost'; \
FLUSH PRIVILEGES;" \
| mysql -uroot -p

                               
7. Import the schema
mysql -u root -p   icinga_web < /usr/share/doc/icinga-web-1.7.2/schema/mysql.sql
mysql -u root -p icinga < /usr/share/doc/icinga-idoutils-libdbi-mysql-1.8.4/db/mysql/mysql.sql

chkconfig ido2db on
chkconfig icinga on
chkconfig httpd on
service ido2db start
service icinga start
service httpd start


8. Test classic Web GUI
Set a SHA encrypted administrator password for Basic Authentication
htpasswd -s /etc/icinga/passwd icingaadmin

Icinga- Web
Test New Web GUI
Open the URL https://ICINGA_SERVER_IP/icinga-web and login with user “root” and password “password”
Set the Timezone
Proper time setting is required to make the scheduled check commands work.
Set the variable TIMEZONE to your timezone, e.g. "Europe/Berlin"
export TIMEZONE="Europe/Berlin"
sed -i "s|^[ ;]*date.timezone *=.*|date.timezone='$TIMEZONE'|" /etc/php.ini
Example 2
ln -s /usr/share/zoneinfo/Canada/Central /etc/localtime
[root@VM156 ~]# date
Mon Sep 22 03:29:14 CDT 2014
[]#vim /etc/php.ini
 [Date]                  #line number 943
date.timezone = "Canada/Central"                      ##line number 946
Install pnp4nagios
Install the required packages:
# yum install rrdtool rrdtool-devel rrdtool-perl openssl-devel gcc php-rrdtool php-gd php php-pdo php-common perl-Time-HiRes
# yum install wget
Download pnp4nagios source
# wget -c 
http://sourceforge.net/projects/pnp4nagios/files/PNP-0.6/pnp4nagios-0.6.21.tar.gz
# tar -xvzf pnp4nagios-0.6.21.tar.gz
# cd pnpnagios-0.6.21
Compile and install pnp4nagios for Icinga user:
# ./configure --with-nagios-user=icinga --with-nagios-group=icinga
# make all
# make install
# make install-webconf
# make install-config
# make install-init

Configure pnp4nagios for Icinga Core:
# vim /etc/icinga/icinga.cfg
................
#process_performance_data=0
process_performance_data=1
.................
broker_module=/usr/local/pnp4nagios/lib/npcdmod.o config_file=/usr/local/pnp4nagios/etc/npcd.cfg
..................

Add new command for check configuration files of the Icinga:
# alias icicheck='/usr/bin/icinga -v /etc/icinga/icinga.cfg'
Integration Icinga htpasswd file in pnp4nagios:
# vim /etc/httpd/conf.d/pnp4nagios.conf    [check the highlighted values]
AuthName "Nagios Access"                   #line number 12
AuthType Basic
AuthUserFile /etc/icinga/passwd

Restart following services:
# service httpd restart
# /etc/init.d/npcd start && chkconfig npcd on
# icicheck
# /etc/init.d/icinga restart
Please check correct installation of pnp4nagios.
Go to web http://<server name>/pnp4nagios/
If you see in the end web page following "Your environment passed all requirements." so you must remove or rename the /usr/local/pnp4nagios/share/install.php file
# mv /usr/local/pnp4nagios/share/install.php /usr/local/pnp4nagios/share/install.php.testfile
Configure main config file of the pnp4nagios:
# cd /usr/local/pnp4nagios/etc/
# mv rra.cfg-sample rra.cfg
# vim npcd.cfg

user = icinga
group = icinga
log_type = file
log_level = -1
load_threshold = 10.0

After that check icinga configuration
# icicheck
Total Warnings: 0
Total Errors: 0
# vim config.php
# Link back to Nagios or Thruk
#
$conf['nagios_base'] = "/icinga/cgi-bin";

Please, overwrite all settings for perfdata:
# vim /etc/icinga/icinga.cfg
#host_perfdata_file=/tmp/host-perfdata
#service_perfdata_file=/tmp/service-perfdata
host_perfdata_file=/usr/local/pnp4nagios/var/host-perfdata
service_perfdata_file=/usr/local/pnp4nagios/var/service-perfdata
#host_perfdata_file_template=[HOSTPERFDATA]\t$TIMET$\t$HOSTNAME$\t$HOSTEXECUTIONTIME$\t$HOSTOUTPUT$\t$HOSTPERFDATA$
#service_perfdata_file_template=[SERVICEPERFDATA]\t$TIMET$\t$HOSTNAME$\t$SERVICEDESC$\t$SERVICEEXECUTIONTIME$\t$SERVICELATENCY$\t$SERVICEOUTPUT$\t$SERVICEPERFDATA$
host_perfdata_file_template=DATATYPE::HOSTPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tHOSTPERFDATA::$HOSTPERFDATA$\tHOSTCHECKCOMMAND::$HOSTCHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$
service_perfdata_file_template=DATATYPE::SERVICEPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tSERVICEDESC::$SERVICEDESC$\tSERVICEPERFDATA::$SERVICEPERFDATA$\tSERVICECHECKCOMMAND::$SERVICECHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$\tSERVICESTATE::$SERVICESTATE$\tSERVICESTATETYPE::$SERVICESTATETYPE$
#host_perfdata_file_mode=a
#service_perfdata_file_mode=a
host_perfdata_file_mode=a
service_perfdata_file_mode=a
#host_perfdata_file_processing_interval=0
#service_perfdata_file_processing_interval=0
host_perfdata_file_processing_interval=30
service_perfdata_file_processing_interval=30
#host_perfdata_file_processing_command=process-host-perfdata-file
#service_perfdata_file_processing_command=process-service-perfdata-file
host_perfdata_file_processing_command=process-host-perfdata-file
service_perfdata_file_processing_command=process-service-perfdata-file

After that check icinga configuration
# icicheck
Total Warnings: 0
Total Errors: 0
Either edit or append. A sample is provided within /usr/local/pnp4nagios/etc/misccommands.cfg:
# cp /usr/local/pnp4nagios/etc/misccommands.cfg-sample /etc/icinga/misccommands.cfg
# vi /etc/icinga/misccommands.cfg
and uncomment following strings
define command {
command_name process-service-perfdata-file
command_line /bin/mv /usr/local/pnp4nagios/var/service-perfdata /usr/local/pnp4nagios/var/spool/service-perfdata.$TIMET$
}
define command {
command_name process-host-perfdata-file
command_line /bin/mv /usr/local/pnp4nagios/var/host-perfdata /usr/local/pnp4nagios/var/spool/host-perfdata.$TIMET$
}
After that check icinga configuration
# icicheck
Total Warnings: 0
Total Errors: 0
# /etc/init.d/httpd restart
# /etc/init.d/icinga reload
Check for perfdata
# ls -la /usr/local/pnp4nagios/var/perfdata/localhost
In this directory you must see files: .rrd+.xml
Useful tools
Clear web cache
#/usr/bin/icinga-web-clearcache

Reference:-
https://wiki.icinga.org/display/howtos/Setting+up+Icinga+Web+on+RHEL

zpanel virtual domains

step 1 : create the subdomain in the control panel domain > sub-domain create ( then restart Apache server )
SSH command : sudo service apache2 restart

step 2: go to DNS manager , create record under A , for webmail ( you should wait for this to activate … luckily couple of hours https://www.whatsmydns.net use this site to check the reach)
step 3 : edit your virtual hosts ,

SSH Command : vi /etc/zpanel/configs/apache/httpd-vhosts.conf

# DOMAIN: webmail.my-domain.com
<virtualhost *:80>
ServerName webmail.my-domain.com
ServerAlias webmail.my-domain.com
ServerAdmin zadmin@localhost
DocumentRoot "/etc/zpanel/panel/etc/apps/webmail"
 
</virtualhost>
 
# END DOMAIN: webmail.my-domain.com


now restart Apache again. 
 

pro ftp apache virtual host

Well, we decided to consider this question on example of proftpd. I could not  say that this is very useful FTP sever, but its configuration syntax is very apache-like, so it is very easy to undertsand how system works and configure it. My post regarding configuration of Apache virtual hosts could be useful for understanding of concepts.
Fisrt of all we assume that:
  • proftpd is running
  • webspace (folder with web site) is already created
  • assume that we adding webpace /srv/www/vhosts/itvictories to proftpd
Main config of proftpd is /etc/proftpd.conf. Syntax is like in Apache's config and we now just have to declare new virtual host for proftpd. It also could be done in main config file, as well as in one, which is connected with include directive.
First of all you have to create to entities:
  • user, which will be responcible for webspace and will have ftp access to its folder
  • group, which will contain all ftp users
It could be done with standard linux commands, but please pay attention to creation of a new user:
useradd ftp-vhost-itvictories -s /bin/false

passwd useradd

groupadd ftp-users
Option "-s /bin/false" in useradd command will disable remote login (with shell) capability for user. Aftewards, open file /etc/group with your favourite editor and edit user ftp-vhost-itvictories to group ftp-users
Group creation is not mandatory at all, but help you to structurize your infrastracture.
Somehow grant write permissions to created user. E.g. in a following way:
chown -R ftp-vhost-itvictories /srv/www/vhosts/itvictories

chmod -R u+w /srv/www/vhosts/itvictories
Now we came to point to declare virtual host in /etc/proftpd.conf or some included file. Add below section to your config:
<VirtualHost itvictories.com>
DefaultRoot /srv/www/vhosts/itvictories
<Limit LOGIN>
Order allow,deny
AllowUser ftp-vhost-itvictories
DenyAll
</Limit>
</VirtualHost>
This will grant permissions for use ftp-vhost-itvictories to access directory /srv/www/vhosts/itvictories in chrooted mode. So user will be unable to reach any other directory at the server.
Now restart your proftpd and your webspace will be available over ftp.

E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable) [duplicate]

sudo rm /var/cache/debconf/*.dat


A solution to this locking problem is detailed in the wiki:
fuser -v /var/cache/debconf/config.dat
Will show you what process is holding the lock then you simply need to note down the PID and kill it like so:
sudo kill PID
sudo kill -9 PID  # if the first doesn't work

postfix queue file write error message size limit

If you get an error like:
Aug 21 12:41:03 webb4 postfix/sendmail[11234]: fatal: web1_user(12967): queue file write error

in your mail log, then the vale for message_size_limit in postfix main.cf is too low. Edit postfix main.cf:

vi /etc/postfix/main.cf
and set the message size limit to a higher value. E.g.
message_size_limit = 900000000
and restart postfix:

/etc/init.d/postfix restart

If there is no message_size_limit set in main.cf, just add the line.

The configuration option is "message_size_limit" and by default is set to 10240000 bytes which is roughly 10MB. You can see what setting your postfix install is currently using by issuing the following command:

postconf | grep message_size_limit

Just doing "postconf" on its own will show all the options so using grep on "message_size_limit" filters the output to just the setting we want. For the default setting, you'll see this:
message_size_limit = 10240000
To change the setting to some other value, open the main.cf file in your favourite text editor (it's often at a location like /etc/postfix/main.cf) and either edit or add the following line, depending if it's already in the file or not.
message_size_limit = 20480000
In the above example I've changed it to ~20MB.
Then reload postfix like so:
service postfix reload

Recommended:
postconf | grep message_size_limit
postconf -e message_size_limit=20480000             
service postfix reload

Something to note: many emails use base64 (there is 8bitmime but support is far from universal). So the space taken up by the attatchment in the email will be about a third bigger than the total size of the attatchments. Then you have to consider the rest of the mail.
So if you want to receive 20MB files you need to set the message size limit to around 27MB.


lsof command

Who are browsing my home/office web server?
lsof -r 2 -n -P -c nginx -a -i TCP@IPAddress:80

Feel free to replace port 80 with other ports such as 21 (FTP), 22(SSH), 443 (HTTPS) and so on to get the same info. The -c options set the user name (see man page http://www.manpager.com/linux/man8/lsof.8.html for more info on all options) :
lsof -r 2 -n -P -c vsftpd -a -i TCP@IPAddress:21
lsof -r 2 -n -P -c sshd -a -i TCP@IPAddress:22


netstat -punt | grep ":80"

http://www.manpager.com/linux/man8/lsof.8.html

8 Linux TR Command Examples

tr is an UNIX utility for translating, or deleting, or squeezing repeated characters. It will read from STDIN and write to STDOUT.
tr stands for translate.

Syntax

The syntax of tr command is:
$ tr [OPTION] SET1 [SET2]

Translation

If both the SET1 and SET2 are specified and ‘-d’ OPTION is not specified, then tr command will replace each characters in SET1 with each character in same position in SET2.

1. Convert lower case to upper case

The following tr command is used to convert the lower case to upper case
$ tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
thegeekstuff
THEGEEKSTUFF
The following command will also convert lower case to upper case
$ tr [:lower:] [:upper:]
thegeekstuff
THEGEEKSTUFF
You can also use ranges in tr. The following command uses ranges to convert lower to upper case.
$ tr a-z A-Z
thegeekstuff
THEGEEKSTUFF

2. Translate braces into parenthesis

You can also translate from and to a file. In this example we will translate braces in a file with parenthesis.
$ tr '{}' '()' < inputfile > outputfile
The above command will read each character from “inputfile”, translate if it is a brace, and write the output in “outputfile”.

3. Translate white-space to tabs

The following command will translate all the white-space to tabs
$ echo "This is for testing" | tr [:space:] '\t'
This is for testing

4. Squeeze repetition of characters using -s

In Example 3, we see how to translate space with tabs. But if there are two are more spaces present continuously, then the previous command will translate each spaces to a tab as follows.
$ echo "This   is   for testing" | tr [:space:] '\t'
This   is   for testing
We can use -s option to squeeze the repetition of characters.
$ echo "This   is   for testing" | tr -s [:space:] '\t'
This is for testing
Similarly you can convert multiple continuous spaces with a single space
$ echo "This  is  for testing" | tr -s [:space:] ' '
This is for testing

5. Delete specified characters using -d option

tr can also be used to remove particular characters using -d option.
$ echo "the geek stuff" | tr -d 't'
he geek suff
To remove all the digits from the string, use
$ echo "my username is 432234" | tr -d [:digit:]
my username is
Also, if you like to delete lines from file, you can use sed d command.

6. Complement the sets using -c option

You can complement the SET1 using -c option. For example, to remove all characters except digits, you can use the following.
$ echo "my username is 432234" | tr -cd [:digit:]
432234

7. Remove all non-printable character from a file

The following command can be used to remove all non-printable characters from a file.
$ tr -cd [:print:] < file.txt

8. Join all the lines in a file into a single line

The below command will translate all newlines into spaces and make the result as a single line.
$ tr -s '\n' ' ' < file.txt

send mail with python script to notify disk usage part 1

Reference:
http://rajivpandit.wordpress.com/2013/09/19/how-to-send-email-by-python/
https://docs.python.org/2/library/email-examples.html
                                                                                                           

[root@server1 ~]# pwd
/root
[root@server1 ~]# cat disk.txt
Filesystem      Size  Used Avail Use% Mounted on
/dev/simfs      400G  1.4G  399G   1% /
none            4.0G  4.0K  4.0G   1% /dev
none            4.0G   48K  4.0G   1% /dev/shm



[root@server1 ~]# vim mailer.py

#!/usr/bin/python
import os
import smtplib
import email.Utils
# Import the email modules we'll need
from email.mime.text import MIMEText
fp = open('disk.txt', 'rb')
msg = MIMEText(fp.read())
to = "norbuurgen@gmail.com"
FROM = "urgen@localhost.com"
server = smtplib.SMTP('localhost')
server.sendmail(FROM, [to], msg.as_string())
server.quit()


= = = = = = = = = = = ===   = = === =      === = = =   =
Following are the two ways to send email notifications by python

“””
This Script Will Send Email Using Internal Email System
In this no need any authentication or password required to send Email
Python Version 2.6
“””
from email.mime.text import MIMEText
import email.Utils
import smtplib

emailList = ["recepient1@gmail.com", "recepient2@gmail.com"] # this is List of Email Ids

for emailID in emailList:
try:
print “Sending email to … “, emailID

FROM = “email@gmail.com”
TO = emailID
message = “This Email is send by Python\n Python is Great !!!”
msg = MIMEText(message)
msg["Subject"] = “Email Notification by Python”
msg["Message-id"] = email.Utils.make_msgid()
msg["From"] = FROM
msg["To"] = TO
host = “smtp.gmail.com”
server = smtplib.SMTP(host)
server.sendmail(FROM, TO, msg.as_string())
server.quit()
print “Email Send”

except Exception, e:
print e





“””
This Script Will Send Email Using Gmail
This Required Username and password
Python Version 2.6
“””
from email.mime.text import MIMEText
from datetime import date
import smtplib

SMTP_SERVER = “smtp.gmail.com”
SMTP_PORT = 587
SMTP_USERNAME = “email@gmail.com”
SMTP_PASSWORD = “password”

EMAIL_TO = ["recepient1@gmail.com", "recepient2@gmail.com"]
EMAIL_FROM = “email@gmail.com”
EMAIL_SUBJECT = “Demo Email : “

DATE_FORMAT = “%d/%m/%Y”
EMAIL_SPACE = “, “

DATA=’This is the content of the email.’

def send_email():
msg = MIMEText(DATA)
msg['Subject'] = EMAIL_SUBJECT + ” %s” % (date.today().strftime(DATE_FORMAT))
msg['To'] = EMAIL_SPACE.join(EMAIL_TO)
msg['From'] = EMAIL_FROM
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.starttls()
mail.login(SMTP_USERNAME, SMTP_PASSWORD)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
print “Email Send”

if __name__==’__main__':
send_email()


# # # # # # Send mysql status report  # # # # # # #
[root@server1 ~]# vim check.py

import smtplib
from email.mime.text import MIMEText
sql_found = False
io_found = False
with open("status.txt") as logfile:
  for line in logfile:
    if not io_found and "kSlave_IO_Running: Yes" in line:
        print "match1",line
        io_found = True
    if not sql_found and "Slave_SQL_Running: Yes" in line:
        print "match2",line
        sql_found = True

if not sql_found or not io_found:
    msg=MIMEText("Warning!! Mysql Replicatoin Stopped")
    fromaddr="root@DBausit.com"
    toaddr="norbuurgen@gmail.com"
    server = smtplib.SMTP('localhost')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, [toaddr], msg.as_string())
    server.quit()
else:
    print "mysql running OK"

Ansible part 1

##############Ansible ###############
play book is composed of 1 or more plays in a list
The goal of a play is to map a group of hosts to some well defined roles, represented by things ansible calls tasks. At a basic level, a task is nothing more than a call to an ansible module, which you should have learned about in earlier chapters.


---
- hosts: webservers
  remote_user: root
  tasks:
  - name: create the new user
    yum: pkg=httpd state=latest
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify:
    - restart apache
  - name: ensure apache is running
    service: name=httpd state=started
  handlers:
    - name: restart apache
      service: name=httpd state=restarted

ansible 192.168.140.20 -a "/usr/bin/yum install libselinux-python"

pip install passlib

python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('nepal12')"
$6$rounds=100000$KYpBC3u43XAxBJNg$7Gh04HYw3wySag8uYqeRghh0L.MtLhVTzNMEe5vr71CFWLSarvHGwrV4I.vStCXzwdPYScZFOHrfrxvl9wzMK1

copy and paste the result like below
ansible all -m user -a 'name=foo password=$6$rounds=100000$40KA9Y5UUFMh/6xC$/rUKR9Qqu7S56nQm9bV91izUA8ExDIb5rxg73QYeyHO.uGiN/9tgfgfdycsj74F36Lz6E1ZvcZf.Bz4wzwxQk0'


Play book for creating user , group with id 777 , add new user to group , copy file from local ansible server to remote client , add new user to sudoers file , install nrpe in client

---
- name: Hello World!
  gather_facts: False
  hosts: all
  vars:
      password: '$6$rounds=100000$3b69WiNTWemboVhu$IGTjv.FvMEDVzXRHEey9ddmuxKhAFL8BBL8unvCos9fcTPQkxkIEEHs1QWraTejPai5ytcq7Hs3Y3ZJ3qmRHv.'
  user: root
  tasks:
   - action: group name=demogroup1 gid=777 state=present
   - action: user name=nplinkuser1 password={{password}}
   - action: user name=nplinkuser1 groups=demogroup1 append=yes
   - copy: src=/asia dest=/
   - lineinfile: "dest=/etc/sudoers state=present regexp='^nplinkuser1' line='nplinkuser1 ALL=(ALL)  ALL'"
   - yum: name=nrpe state=latest