Friday, 30 August 2013

Create a simple Nagios plugin support graph (passive check)

First, to know this article, please read and practice active check in here.

Config passive check
Config with nagios core:
vi /usr/local/nagios/etc/nagios.cfg
accept_passive_service_checks option is set to 1 as well.



Manual passive check

Create a plugin like active check article but in define service add two lines:
active_checks_enabled 0
passive_checks_enabled 1


Restart nagios:
sudo -s
service nagios restart
This is the result:

 Click Submit passive check and fill it like this image:

 refresh nagios webpage and wait few seconds and view Status information:

Other way:
Structure:
[<timestamp>] PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<service_status>;<plugin_output>
Example:
sudo -s
CHECK="[`date +%s`] PROCESS_SERVICE_CHECK_RESULT;localhost2;Check cpu;0;Ok from commandline"
echo $CHECK >>/usr/local/nagios/var/rw/nagios.cmd



Passive check from remote host

Nagios server (ip: 192.168.0.221)
Install
sudo -s
apt-get install nsca
Edit nsca config:
vi /etc/nsca.cfg
Content to change (if different), can change password to anythink you like but must match client and server:
command_file=/usr/local/nagios/var/rw/nagios.cmd
password=aloha
decryption_method=1
nsca_group=nagios
nsca_user=nagios
Restart nsca
service nsca restart

Client (ip: 192.168.0.33)
Install:
sudo -s
apt-get install nsca-client
Config:
 vi /etc/send_nsca.cfg
change password and encryption_method like server

Check

echo -en "localhost2\tcheck cpu\t0\tCheck Ok from nsca\n" | send_nsca -c /etc/send_nsca.cfg -H 192.168.0.221
Result Ok, but nagios don't do any think.
1 data packet(s) sent to host successfully.
Debug: 

 vi /usr/local/nagios/var/nagios.log

[1377855543] EXTERNAL COMMAND: PROCESS_SERVICE_CHECK_RESULT;localhost2;check cpu;0;Check111 Ok from nsca
[1377855543] Warning: Passive check result was received for service 'check cpu' on host 'localhost2', but the service could not be found!
and this is the reason:
 echo -en "localhost2\tCheck cpu\t0\tCheck Ok from nsca\n" | send_nsca -c /etc/send_nsca.cfg -H 192.168.0.221
Wait for few seconds and data will be update in nagios.
You can see in active check article to see how to create graph.

Tuesday, 27 August 2013

Create a simple Nagios plugin support graph (active check)

In this article, I will post an example of a Nagios plugin support graph.
First, you must install Nagios core and pnp4nagios (I suggest you install like these article because other ways can make some differences).

This code is written by Python, will make random number and return result. You can do with any language can return the same result.


Create plugin

Code

#!/usr/bin/python
import os, sys, random

random = random.randrange(0, 120)

if random < 50:
        print "OK - %s%% cpu|'cpu'=%s%%" % (random, random)
        sys.exit(0)
elif random < 90 and random >= 50:
        print "WARNING - %s%% cpu|'cpu'=%s%%" % (random, random)
        sys.exit(1)
elif random <= 100 and random >= 90:
        print "CRITICAL - %s%% cpu|'cpu'=%s%%" % (random, random)
        sys.exit(2)
else:
        print "UKNOWN - %s%% cpu|'cpu'=%s%%" % (random, random)
        sys.exit(3)

Example result
OK - 47% cpu|'cpu'=47%


Create file

cd /home/
vi plugin.py  (  paste code in vi editor)

chmod 777 plugin.py

Check result
./plugin.py -> UKNOWN - 111% cpu|'cpu'=111%


Config in Nagios (local)
Create a host with service use our plugin
cd /usr/local/nagios/etc
vi test.cfg
paste this content

define host{
        use                     linux-server,host-pnp         ; Name of host template to use
                                                        ; This host definition will inherit all variables that are defined
                                                        ; in (or inherited by) the linux-server host template definition.
        host_name               localhost2
        alias                   localhost2
        address                 127.0.0.1
        }

define service{
        use                             local-service,service-pnp          ; Name of service template to use
        host_name                       localhost2
        service_description             Check cpu
        check_command                   check_cpu
        }

define command{
        command_name    check_cpu
        command_line    /home/plugin.py
        }

vi /usr/local/nagios/etc/nagios.cfg
and this line
cfg_file=/usr/local/nagios/etc/test.cfg


Check config error and restart
/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg

service nagios restart


Result
And this is the result:


Click to check cpu:

You can see Status information and Performance Data , this is the result of above red plugin result


Graph will be created from Performance Data with this struct: 'label'=value[UOM];[warn];[crit];[min];[max]

See more here: http://nagiosplug.sourceforge.net/developer-guidelines.html

Wait about half of hour or more, and this is my plugin graph :




Config from remote host, via nrpe:
Install in client (ip: 192.168.0.33)
apt-get install -y python nagios-nrpe-server

Disable nagios3 service
Because I use nagios from source (not nagios3 - dependences of nagios-nrpe-server), so, to disable (to get server lighter), we need:
update-rc.d nagios3 disable (for disable service startup with server)
service nagios3 stop (to stop running service)
update-rc.d nagios3 enable (for enable service startup)

Install and check
client:
create plugin.py at /home/plugin.py like above at client

Config
vi /etc/nagios/nrpe.cfg

add any monitor service or host can get infor at allowed_hosts:
allowed_hosts=127.0.0.1,192.168.0.222
add this plugin command:
command[check_cpu]=/home/plugin.py
Save config file and restart
service nagios-nrpe-server restart 


Install in server (ip: 192.168.0.222)
sudo apt-get install nagios-nrpe-plugin

Check nrpe
/usr/lib/nagios/plugins/check_nrpe -H 192.168.0.33 -c check_cpu
And this is the result:
WARNING - 69% cpu|'cpu'=69%

With this command, you can change command in above local config to check remote host.
In fact, we usually use command like:
/usr/lib/nagios/plugins/check_nrpe -H $HOSTADDRESS$ -c $ARG1$
and check_command like:
check_cpu!check_cpu
 with ip will be replaced in $HOSTADDRESS$ and check_cpu after ! will be replaced in $ARG1$.
Go to document of nagios to view more.

Tuesday, 20 August 2013

Check_MK, one of the best plugin for Nagios

Check_MK is a collection of extensions for the IT-Monitoring-Kernel of Nagios and together with this, and ideally also with PNP4Nagios and NagVis constitutes a complete IT-Monitoring-System. Check_MK is 100% Open-Source and is available under the terms of the GNU GPL.

View homepage to get full information:
http://mathias-kettner.com


First must install nagios: view here

After download and extract from :
http://mathias-kettner.com/check_mk_download.html



Install
Must install libapache2-mod-python first.

Go to extracted folder in terminal.
sudo -s
./setup.sh

Next next next and next.
setup progress will auto detect elements.


setup check_mk

Type y, Enter

Restart nagios and apache2 services
service nagios restart
service apache2 restart


This is the result (image from wiki):



Error when run

When I restart linux, having an error
"Livestatus problem: Cannot connect to  'unix:/usr/local/nagios/var/rw/live': [Errno 111] Connection refused"
This is because pemission, use commands:

chown nagios.nagcmd /usr/local/nagios/var/rw
chmod g+rwx /usr/local/nagios/var/rw
chmod g+s /usr/local/nagios/var/rw

Install graph plugin for Nagios (pnp4nagios)

This article will install pnp4nagios plugin for nagios install from source: see here

Go to web, download and extract source code:
http://sourceforge.net/projects/pnp4nagios/


SETUP

Go to superuser mode
sudo -s

install rrdtool and RRDs Perl Modules (dependences for pnp4nagios)
apt-get install libcgi-pm-perl librrds-perl libgd-gd2-perl libnagios-object-perl rrdtool

Download and extract (in present this is the lastest version)
cd ~/downloads (if not exists: mkdir downloads)
wget http://sourceforge.net/projects/pnp4nagios/files/PNP-0.6/pnp4nagios-0.6.21.tar.gz
tar -xzvf pnp4nagios-0.6.21.tar.gz

Compile and Install
cd pnp4nagios-0.6.21/
./configure
make all
make fullinstall

Restart nagios and apache2 services
service nagios restart
service apache2 restart


FIX ERRORS
go to 127.0.0.1/pnp4nagios
and see like this image:

pnp4nagios apache mod rewrite tientuts blog


Fix:
a2enmod rewrite
 /etc/init.d/apache2 restart (like service apache2 restart)
and do like info in below webpage:
Your environment passed all requirements. Remove or rename the /usr/local/pnp4nagios/share/install.php file now.
go to terminal: sudo nautilus -> go to this page and rename file


Config
Still go to terminal: sudo nautilus.

Go to /usr/local/nagios/etc/nagios.cfg,
Change default fields to this content:

process_performance_data=1
host_perfdata_file=/usr/local/pnp4nagios/var/host-perfdata
service_perfdata_file=/usr/local/pnp4nagios/var/service-perfdata
host_perfdata_file_template=DATATYPE::HOSTPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tHOSTPERFDATA::$HOSTPERFDATA$\tHOSTCHECKCOMMAND::$HOSTCHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$\tHOSTOUTPUT::$HOSTOUTPUT$
service_perfdata_file_template=DATATYPE::SERVICEPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tSERVICEDESC::$SERVICEDESC$\tSERVICEPERFDATA::$SERVICEPERFDATA$\tSERVICECHECKCOMMAND::$SERVICECHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$\tSERVICESTATE::$SERVICESTATE$\tSERVICESTATETYPE::$SERVICESTATETYPE$\tSERVICEOUTPUT::$SERVICEOUTPUT$
host_perfdata_file_mode=a
service_perfdata_file_mode=a
host_perfdata_file_processing_interval=15
service_perfdata_file_processing_interval=15
host_perfdata_file_processing_command=process-host-perfdata-file
service_perfdata_file_processing_command=process-service-perfdata-file

Go to /usr/local/nagios/etc/objects/commands.cfg, append the command definitions:
define command {
command_name    process-service-perfdata-file
command_line    /usr/local/pnp4nagios/libexec/process_perfdata.pl --bulk=/usr/local/pnp4nagios/var/service-perfdata
}

define command {
command_name    process-host-perfdata-file
command_line    /usr/local/pnp4nagios/libexec/process_perfdata.pl --bulk=/usr/local/pnp4nagios/var/host-perfdata
}
go to /usr/local/pnp4nagios/etc/ , rename rra.cfg-sample files to rra.cfg.


Append two entries to /usr/local/nagios/etc/objects/templates.cfg:

define host {
name            host-pnp
action_url      /pnp4nagios/index.php/graph?host=$HOSTNAME$&srv=_HOST_
register        0
}

define service {
name            service-pnp
action_url      /pnp4nagios/index.php/graph?host=$HOSTNAME$&srv=$SERVICEDESC$
register        0
}
Add above templates to any host or service you want like I change /usr/local/nagios/etc/objects/localhost.cfg
.......
define host{
        use                     linux-server,host-pnp         ; Name of host template to use
                            ; This host definition will inherit all variables that are defined
                            ; in (or inherited by) the linux-server host template definition.
        host_name               localhost
        alias                   localhost
        address                 127.0.0.1
        }

......
define service{
        use                             local-service,service-pnp          ; Name of service template to use
        host_name                       localhost
        service_description             PING
    check_command            check_ping!100.0,20%!500.0,60%
        }
........

Restart nagios and apache2 services like aboves and we will see graph icon in hosts and services was added template.
This is the result:

pnp4nagios graph icon tientuts blog


Friday, 16 August 2013

Tip to improve autocomplete unknow variables in python with pydev

See this article first.

Python use dynamic type, so IDE can unknow variable in some cases like if you want autocomplete string type:
a.
Ctrl+space and pydev don't show any thing.

I know some ways to solve:

Using assert and isinstance

import string

def fun1(a):
    a = string(a)
    a.

fun1("hello")

Cast the object/variable back to its type


import string

def fun1(a):
    a = string(a)
    a.

fun1("hello")




New on PyDev 2.8.0
http://pydev.org/manual_adv_type_hints.html

Example:
import string

def fun1(a):
    '@type a: string'
    a.

fun1("hello")



or you can autocomple If write two charactor, this will autocomplete in all classes

Thursday, 15 August 2013

Validate string with a regular expression

Regular expression is really an amazing function in string processing. In this article, I will introduce a popular case using regular expression to solve validate string with muli-conditions: validate password strength.

Requirements
  • program language must support regular expression with look lookahead assertion.

These are the rules
  • The password length must be greater than or equal to 7 characters
  • The password must contain one or more uppercase characters
  • The password must contain one or more lowercase characters
  • The password must contain at least one numeric character.

And this is the answer
(?=^.{7,}$)(?=.*\d)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$
You can see colors and very easy to know. The end to finish a regex (all of first statement is only condition, must have main body and check that end with end of line (with multiline mode) or end of string (with singleline mode).

Test online with


Wednesday, 14 August 2013

Install Nagios and monitor tools in Ubuntu (and other Linux distros) with setup file

Install Nagios is hard with newbie and install others tools make our must spend much time. But now, we can do it very easy with  OMD - The Open Monitoring Distribution

I will present how to install in ubuntu 13.04.


Note
  • Must change ubuntu to main repo (some other repo can make some dependence errors)

  • Must change
Iregion format tientuts blogspot

after change regional format, need logout or restart to apply.

Install and configure OMD

1. Download omd from http://omdistro.org/download or add repositories.
2. Go to terminal and update list packages:
sudo -s
apt-get update
3. Install omd file (or can install from repo with apt-get install ..)
dpkg -i <file_name>
4. Create first website:
omd create mysite
omd start

5. Go to website:
http://127.0.0.1/mysite
with username: omdadmin  and pass: omd
And go to omdistro.org , nagios and other tools website to read how to use them.

Note:
In ubuntu 13.04, having some error in check_mk user interface.I think install from source is better:
http://tientuts.blogspot.com/2013/08/install-nagios-in-ubuntu-1304-32bit.html

Tuesday, 13 August 2013

Install Nagios in ubuntu 13.04 32bit from source

Nagios core is an opensource system to monitor many things in network. Nagios offers monitoring and alerting services for servers, switches, applications, and services. It alerts the users when things go wrong and alerts them a second time when the problem has been resolved.
Because it free, opensource and easy to custom, many companies have applied it to monitor your system.
Today, I will present how to install nagios in ubuntu 13.04 32bit.

This article used information in Quickstart Installation Guides in nagios documents

Preconfigure
Must change regional format to English or will having errors in some plugin like check_mk:

regional format blogspot tientuts

Some package in my countries Ubuntu repo  don't support some packages like openssh-service. Please use main repo.
Change with command line, use: https://help.ubuntu.com/community/Locale

Setup
Go to superuser mode
sudo -s

Install dependencies
apt-get update
apt-get install build-essential apache2 php5-gd wget libgd2-xpm libgd2-xpm-dev libapache2-mod-php5 libssl-dev libapache2-mod-python -y

Create Account Information
/usr/sbin/useradd -m -s /bin/bash nagios
passwd nagios
/usr/sbin/groupadd nagcmd
/usr/sbin/usermod -a -G nagcmd nagios
/usr/sbin/usermod -a -G nagcmd www-data

Download and extract files

mkdir ~/downloads
cd ~/downloads
wget http://sourceforge.net/projects/nagios/files/nagios-3.x/nagios-3.5.0/nagios-3.5.0.tar.gz
wget http://sourceforge.net/projects/nagiosplug/files/nagiosplug/1.4.16/nagios-plugins-1.4.16.tar.gz
tar -xzvf nagios-3.5.0.tar.gz
tar -zxvf nagios-plugins-1.4.16.tar.gz

Compile and Install Nagios
cd nagios/
./configure --with-command-group=nagcmd --enable-event-broker
make all
make install
make install-init
make install-config
make install-commandmode

Configure the Web Interface
make install-webconf
htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin
/etc/init.d/apache2 reload

Compile and Install Nagios plugin
cd ~/downloads
cd nagios-plugins-1.4.16/
./configure --with-nagios-user=nagios --with-nagios-group=nagios
make


Error and fix (Important)

when make with new linux distro like ubuntu 13.04 or centos 6.4 (don't appear in ubuntu 12.04), I met this error, view image:

go to gl folder of nagios-plugin , go to stdio.h file (must make to get this file), search gets.
And you will see the line like this:
_GL_WARN_ON_USE (gets, "gets is a security hole - use fgets instead");
change gets to fgets.

Continue compile and Install Nagios plugin
cd ~/downloads/nagios-plugins-1.4.16/
make
make install

Start Nagios and set startup

ln -s /etc/init.d/nagios /etc/rcS.d/S99nagios
/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
/etc/init.d/nagios start

Login to the Web Interface

http://localhost/nagios/
or http://127.0.0.1/nagios/

username: nagiosadmin

Install ssh server
sudo apt-get install openssh-server
to ssh from other pc

Install more plugins
apt-get install nagios-plugins*

folder of plugins:
/usr/local/nagios/libexec (from source)
/usr/lib/nagios/plugins (from apt-get)

Friday, 9 August 2013

Read microsoft office documents in Linux

Default of distros of linux are open source offices like libreoffice, koffice, abioffice ... but all of them reading doc, docx, xls, xlsx ... files are not very well. Today, I will present some solutions better.


Kingsoft Office


Home page: http://wps-community.org/ or http://www.kingsoftstore.com

It is the office productivity suite having free and pro versions, but with only free version, I can read ms office formats much better than libreoffice (what I am using). Besides, It is small, can download for offline install, run fast and user interface very like ms office, you can use without any difficulty.


Skydriver

Skydriver is an free store service of microsoft office with 7gb online. And it support read ms office formats perfectly. However, when you edit documents, it has many limit when compare with MS office offline in window.


OthersTo get full of power of ms office, you can do other solutions like:
  • Install MS office in window in virtual machine (vmware, virtualbox ..)
  • Install MS office via crossover (wine). Crossover is shareware but support install MS office in linux good and easy.


Tuesday, 6 August 2013

IDEs for javascript

automaticallyWith javascript, I think coding with debug, Aptana (in Eclipse) and Netbean are two of best free IDEs. It support many features, but like Python, IDE support autocomplete but not as good as java or C# (see here).
In my window, Aptana has some error, when I debug in Firefox, Aptana website alway show and IE always fore close, i can't debug so I like Netbean more than Aptana.

Note: If you want create and edit html code like word (WYSIWYW function), you need use Dreamwear, Microsoft Expression Web or free like Kompozer. Netbean only support write code.

Netbean


This is an image of Netbean with javascript debugger.

When you install Netbean support HTML5 (HTML5 = HTML + CSS3+ Javascript with new tags and features), you can create a HTML5 project, go to Run menu -> Set project configuration -> Chrome with netbean intergration, Netbean will connect with chrome browser via an plugin (be installed automatically).


So, I think Netbean is the best free IDE for javascript. You can try HTML5 and others in project.



Sunday, 4 August 2013

IDE for Python

I used some IDEs for Python. When compared with Netbeans for java or visual studio for c# I has been used, none of them have the same power, but I will present the best IDEs I know.

Netbeans (6.x version + python plugin)

Python with Netbeans 7.x don't support autocomple good, only Netbeans 6.x (I use 6.9) support good for autocomple.
To download old version, go do https://netbeans.org/downloads/6.9/ , to install plugin in, go to tools -> plugin -> availables options and search python.
I think Netbeans 6.x with python plugin is a good free IDE for python.
It support autocomplete the best (in IDEs i know), support format code (the same with eclipse).
Because python is dynamic type language, when autocomplete a variable, It will guess type,example:
a ="hello"
a.
It will show all suggestions for string type.
If a is the first time type, It will show suggestions for all types and an option specify type of  to set type to autocomple. Really good.

Debug in Netbeans good, can breakpoint, run 1 line .. but don't support show var in editor or watch frame, only having a debug frame, must write code and enter to watch value when debug.

When you install new package for python, delete folder and re open Netbeans, Netbeans will re-scan pagakes and update autocomplete.
C:\Users\<user_name>\.netbeans\6.9\var\cache\gsf-index

Must make project to run code but can add many folder in many area to run many code.


Eclipse + Pydev

 

Although it's not really good in suggestion and code format function is not comprehensive but I think it is one of the best in free IDEs for Python. Maybe Python has dynamic type, so it is difficult to autocomplete methods/functions and others IDEs I used has the same problem (or stupider, except Netbeans)
Like, with this code, I can't autocomplete strip() method.

def fun1(s):
    return s.strip()

print fun1("   Hello")
But from pydev 2.8.0, we can do it. View here to overcome. Or you can type "st" (at least 2 character) and ctrl+space
It support good with navigate, debug, crossplatform ...
Must make project to compile and run code.


Pycharm community





A free version of Pycharm IDE, but it is really good, better than Netbean, better than pydev but indicate variable type or autocomplete unknown variable can't be set.
I set it is the same with pydev. 



Pyscripter




Like Pydev but having some advantages:
  • More nice
  • Can run a single file
  • Lighter 
Disadvantages:
  • Only for window
  • Don't support autoformat code


Sublime text

Beside, some colleagues like sublime text.
It is nice, autocomplete good (same pydev but smoother), can run single file, support split window...
But can't debug, auto-format code, can use free but not full free.


If you like professional IDEs (sharewares0, you can try Pycharm, Komodo ... I tried one time for each but autocomplete not good like Netbeans.

Friday, 2 August 2013

IDE in programming

IDE is abbreviated to Integrated Development Environment or Interactive Development Environment.
Many programmers like coding with a basic editor and compile with command line and debug with print values, but I'm a programmer like the convenience and performance, I am always looking for good IDEs to get the code faster and more simple fixes. This is really good for big projects.

The criteria of me for finding IDEs are:
  • Format code
  • Autocomplete code
  • Support debug
  • Support view document of functions, methods
  • preferably free
  • And other criteria like nice interface, keyboard shortcut, cross-platform ...
And after articles with tag IDE, I will share good IDEs (or text editor support code) I used.

Thursday, 1 August 2013

Python with big number

Python is a good programming language for processing big number. We don't need to care about type of value or add any library.


Example:


result = 1
for i in range (1, 140):
    result *= i
print result


And this is result: 96157231969410890041971956135297253988256079629956908500367081914696145479218112119985149618783441690577636407442564169301886059792163365100096999581219760002673769583579570682891939608962934200435638009856000000000000000000000000000000000


With java, many friend of me don't know type of value larger than long. However, java support BigInteger and Bigdecimal.

    public class JavaApplication1 {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            question2();
        }
     
        public static void question2() {

            BigInteger fact = BigInteger.valueOf(1);
            for (int i = 1; i <= 139; i++) {
                //fact = fact.multiply(BigInteger.valueOf(i));
                fact.multiply(BigInteger.valueOf(i));
            }
            System.out.println(fact);
        }
    }

And with javascript, a language with dynamic type like python


var result =1;
for(var i=1;i<140;i++){
    result =result*i;
}
document.write(result);


Result: 9.615723196941086e+238
We must find and add libraries  in google to add.

So python is very comfortable in calculator with big number.