Showing posts with label Nagios. Show all posts

Add User in Nagios

by GarciaPL on Thursday, 22 August 2013

I just wrote a small script (written in Perl) which performs adding user to merlin database without doing it manually via web interface. In my server environment script works, but I can not guarantee you that it will work in yours environments ;)

Configuration of script :
- htpasswd_directory - directory of htpasswd file for example /opt/nagios/etc/
- htpasswd_file - name of htpasswd file used by Nagios for example htpasswd.users
- nagios_cgi_directory - main Nagios directory for example /opt/nagios/etc/
- nagios_cgi_cfg_file - name of main Nagios configuration file which stores users information for example cgi.cfg
- nagios_cgi_fields - name of user privileges to be added in cgi file for example authorized_for_all_services and authorized_for_all_hosts
- domain - if your company uses a domain name in users accounts for example @MICROSOFT.COM
- comma - it is obvious ;)
- password_algorithm (relative)
- password_user_merlin (relative)


This script is some kind of guide to develop your own script to adding faster users in nagios infrastructure ;)

#!/usr/bin/perl -w
######################################
# Info : Add User Nagios on st1monms2
# Version : 1.0
# Date : 7 luty 2012
# Author : Lukasz Ciesluk
# Help : http://pl.linkedin.com/in/lukaszciesluk/
######################################
#
# Run :
# chmod +x AddUserNagios_st1monms2.pl
# ./AddUserNagios_st1monms2.pl -h (for help)
# ./AddUserNagios_st1monms2.pl -u  --username_db  --password_db  --database 

use strict;
use warnings;
use Getopt::Long;
use DBI;
use Tie::File;

my $new_nagios_user = undef;
my $username_db = undef;
my $password_db = undef;
my $database = undef;
my $sql = undef;
my $dbh = undef;
my $help = undef;

my $htpasswd_directory = "/opt/nagios/etc/";
my $htpasswd_file = "htpasswd.users";
my $nagios_cgi_directory = "/opt/nagios/etc/";
my $nagios_cgi_cfg_file = "cgi.cfg";
my @nagios_cgi_fields = ( 'authorized_for_all_services', 'authorized_for_all_hosts', 'authorized_for_read_only' );

my $domain = "\@BANK.COM.PL";
my $comma = ",";
my $password_algorithm = "b64_sha1";
my $password_user_merlin = "4insgmC8hl++J1uTcPVCtfo2uX0=";

sub usage {
    print "$0 --u  --dbu  --dbp  --dbd \n";
}

sub connect_db_merlin {
 $dbh = DBI->connect("dbi:mysql:database=$database;"."host=localhost;port=3306", $username_db, $password_db) || die "Nie mozna sie polaczyc do bazy: $DBI::errstr";
}

sub duplicate_htpasswd {
 my ($nagios_user_create) = @_;
 if (-d $htpasswd_directory) {
  chdir($htpasswd_directory) or die "Can not change directory to the $htpasswd_directory!";
  
  my $cat_user = `cat $htpasswd_file | grep $nagios_user_create`;
  if (length($cat_user) > 0) {
   print "User has record in $htpasswd_file file which may mean that user can exists. Exit program\n";
   exit;
  }
  
  tie my @array, 'Tie::File', $htpasswd_file or die "Reading file $htpasswd_file finished with an error : $!\n";
  my $monkey_index = index($array[-1], '@');
  my $domain_substring = substr($array[-1], $monkey_index, length($array[-1]));
  my $new_user_string = $nagios_user_create.$domain_substring;
  print "Adding record to $htpasswd_file file : $new_user_string\n";
  open (FILE, ">>$htpasswd_file") || die "Error opening file $htpasswd_file : $!\n";
  print FILE "$new_user_string\n";
  close FILE;
 } else {
  print "Catalog $htpasswd_directory does not exist. Exit program\n";
  exit;
 }
}

sub duplicate_st1monms2_cgi {
 my ($nagios_user_create) = @_;
 if (-d $nagios_cgi_directory) {
  chdir($nagios_cgi_directory) or die "Can not change directory to the $nagios_cgi_directory!";
  
  my $cat_user = `cat $nagios_cgi_cfg_file | grep $nagios_user_create`;
  if (length($cat_user) > 0) {
   print "User has record in $htpasswd_file file which may mean that user can exists. Exit program\n";
   exit;
  }

  open ( FILE, "$nagios_cgi_cfg_file" ) || die "Error opening file $nagios_cgi_cfg_file : $!\n";
  my @lines = ;
  for my $linia (@lines) {
   foreach my $field (@nagios_cgi_fields) {
    if($linia =~ /$field/){
     $linia =~ s/^\s+//;
     $linia =~ s/\s+$//;
     $linia =~ s/^\s+//;
     $linia =~ s/\s+$//;
     
     my @add_user_authorizate = `sed -i.bak -e s/$linia/$linia$comma$nagios_user_create$domain/g $nagios_cgi_cfg_file`;
     print @add_user_authorizate;
     
     print "Granted $field privilege to user $nagios_user_create\n";
    }
   }
  }
  close (FILE);
 } else {
  print "Catalog $nagios_cgi_directory does not exist. Exit program\n";
  exit;
 }
}

sub restart_nagios {
 my @restart = `mon restart`;
 print @restart;
}

sub merlin_db_operations {
 my ($nagios_user_create) = @_;
 
 print "Checking if user $nagios_user_create$domain exists in database already\n";
 my $sthUserExists = $dbh->prepare('select count(*) as ilosc from users where username = ?') || die "Database Select User Error $DBI::errstr";
 $sthUserExists->bind_param(1, $nagios_user_create.$domain);
 $sthUserExists->execute();
 my $ifexists = $sthUserExists->fetchrow_hashref();
 
 if ($ifexists->{ilosc} > 0) {
  print "User $nagios_user_create$domain exists! Interrupt program!\n";
  $dbh->disconnect();
  exit;
 } else {
  print "User $nagios_user_create$domain does not exist in database. Continuing.\n";
 }

 my $sth = $dbh->prepare('select max(id) as maxid from users') || die "Database Select Max ID Error $DBI::errstr";
 $sth->execute();
 my $result = $sth->fetchrow_hashref();
 my $new_user_id = $result->{maxid} + 1;

 print "Please give name of user (realname)\n";
 my $realname = <>;
 chomp ($realname);
 print "Please give e-mail address of user (e-mail)\n";
 my $email = <>;
 chomp ($email);
 
 my $sthUserTable = $dbh->prepare('insert into users(id, realname, email, username, password_algo, password) VALUES (?, ?, ?, ?, ?, ?)');
 $sthUserTable->bind_param(1, $new_user_id);
 $sthUserTable->bind_param(2, $realname);
 $sthUserTable->bind_param(3, $email);
 $sthUserTable->bind_param(4, $nagios_user_create.$domain);
 $sthUserTable->bind_param(5, $password_algorithm);
 $sthUserTable->bind_param(6, $password_user_merlin);
 $sthUserTable->execute();
 
 print "Added to Users table a user (username) : $nagios_user_create$domain with ID = $new_user_id\n";
 print "Selected algorithm for password : $password_algorithm and password : $password_user_merlin\n";
 
 print "Adding roles for user\n";
 my $sthRolesUsersTable = $dbh->prepare('insert into roles_users(user_id, role_id) VALUES (?, 1)');
 $sthRolesUsersTable->bind_param(1, $new_user_id);
 $sthRolesUsersTable->execute();
 
 print "Please answer for user roles : \n";
 print "Add system_information role ? (0 - no, 1 - yes)\n";
 my $system_information = <>;
 chomp ($system_information);
 print "Add configuration_information role ? (0 - no, 1 - yes)\n";
 my $configuration_information = <>;
 chomp ($configuration_information);
 print "Add system_commands role ? (0 - no, 1 - yes)\n";
 my $system_commands = <>;
 chomp ($system_commands);
 print "Add all_services role ? (0 - no, 1 - yes)\n";
 my $all_services = <>;
 chomp ($all_services);
 print "Add all_hosts role ? (0 - no, 1 - yes)\n";
 my $all_hosts = <>;
 chomp ($all_hosts);
 print "Add all_service_commands role ? (0 - no, 1 - yes)\n";
 my $all_service_commands = <>;
 chomp ($all_service_commands);
 print "Add all_host_commands role ? (0 - no, 1 - yes)\n";
 my $all_host_commands = <>;
 chomp ($all_host_commands);
 
 print "Adding roles for user $nagios_user_create\n";
 my $sthUserAuthorizationTable = $dbh->prepare('insert into ninja_user_authorization(user_id, system_information, configuration_information, system_commands, all_services, all_hosts, all_service_commands, all_host_commands) 
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
 $sthUserAuthorizationTable->bind_param(1, $new_user_id);
 $sthUserAuthorizationTable->bind_param(2, $system_information);
 $sthUserAuthorizationTable->bind_param(3, $configuration_information);
 $sthUserAuthorizationTable->bind_param(4, $system_commands);
 $sthUserAuthorizationTable->bind_param(5, $all_services);
 $sthUserAuthorizationTable->bind_param(6, $all_hosts);
 $sthUserAuthorizationTable->bind_param(7, $all_service_commands);
 $sthUserAuthorizationTable->bind_param(8, $all_host_commands);
 $sthUserAuthorizationTable->execute();
}

sub help {
   print "\nAdd User Nagios\n";
   usage();
   print < \$help,
  'u=s'   => \$new_nagios_user,     'nagios_user:s'  => \$new_nagios_user,
  'dbu=s'   => \$username_db,               'username_db:s'    => \$username_db,
  'dbp=s'   => \$password_db,      'password_db:s'  => \$password_db,
  'dbd=s'   => \$database,       'database:s'   => \$database
    );

if ($help) { help(); exit; }
if (!defined($new_nagios_user))
 { print "Put new username nagios to create! (-h for help)\n"; usage(); exit;}
if (!defined($username_db) || !defined($password_db))
    { print "Put database login or password info! (-h for help)\n"; usage(); exit;}
if (!defined($database))
    { print "Put database name! (-h for help)\n"; usage(); exit;}
}

######### MAIN PROGRAM

check_input();

######### Connect to merlin database
print "Checking connection to database $database\n";
connect_db_merlin();

######### Duplicate user field on  in /opt/nagios/etc/htpasswd.users
print "Duplicate user entry in file $htpasswd_directory$htpasswd_file\n";
duplicate_htpasswd($new_nagios_user);

######### Adding authorization to file /opt/nagios/etc/cgi.cfg
print "Adding authorizations for new user to file $nagios_cgi_directory$nagios_cgi_cfg_file\n";
duplicate_st1monms2_cgi($new_nagios_user);

######### Restarting nagios
print "Restarting nagios... please wait\n";
restart_nagios();

######### Adding records to database
print "Adding records to database\n";
merlin_db_operations($new_nagios_user);

######### Disconnect from database
print "Disconnect from database\n";
$dbh->disconnect();

Reference : [1] Pastebin GarciaPL Add User Nagios [2] Nagios Docs [3] Diknowstech Blog How To Change Nagios Password

Review Instant Nagios Starter

by GarciaPL on Saturday, 10 August 2013

In the last days I received a very interesting offer to write down some words about book entitled "Instant Nagios Starter". I received this book from a publishing company called Packt.
First of all, I must to say that book is very helpful for all kind of IT specialists who would like to run Nagios in theirs companies or homes. It describes all major topics which you are going to face with while Nagios installation. I really would like to recommend this book. Very quick, rich content quide!


I would like to also share my review on Goodreads.com which is :

"If you are looking for well-written and the most smallest with rich content guide which help you to quick start Nagios system in your environment you are in the right place. Instant Nagios Starter is dedicated for administrators, developers and even IT enthusiasts. Arrangement of chapters is correct and logical which makes that understanding of Nagios is pretty easy."

Reference :  [1] Packtpub.com Instant Nagios Starter [2] Goodreads.com Instant Nagios Starter Review

Nagios verify configuration

by GarciaPL on Tuesday, 16 July 2013

If you would like to verify Nagios configuration just run this command :

/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg

Of course in your case the path to nagios.cfg may be different ;)


Reference :
[1] Nagios Verify Configuration

Send mail in Perl

by GarciaPL on Sunday, 7 July 2013

I would like to share with you a small script written in Perl which simply send an email. You can use it in your other scripts when you want to indicate an error while something goes wrong. Of course this small piece of code can be also used in Nagios scripts ;) Only imagination is the limit where this sending email function can be used.

sub sendEmail {
        my ($to, $from, $subject, $message) = @_;
        my $sendmail = '/usr/lib/sendmail';
        open(MAIL, "|$sendmail -oi -t");
        print MAIL "From: $from\n";
        print MAIL "To: $to\n";
        print MAIL "Subject: $subject\n\n";
        print MAIL "$message\n";
        close(MAIL);
}
 
sendEmail("receiveremail\@domain.com", "myemail\@domain.com", "Nagios Error", "Cannot receive NRPE output from host 10.100.5.6");

Reference : 
[1] Pastebin GarciaPL Send email in Perl

Nagios plugins support

by GarciaPL on Tuesday, 30 April 2013

Some of you may noticed that I made few posts about Nagios plugins which were made by me ;)

1) Monitor Cisco HSRP with SNMP
2) Nagios HP BladeSystem Ambient Temperature
3) CPUMem Cisco 2800 plugin Nagios Exchange

Second and third script you can of course find at Nagios Exchange.

I would like also to tell that if you have some bright or casual idea about new plugin for Nagios or your company needs to write some plugins and integrate them with existed Nagios infrastructure, please just write to me ;) I will help you of course in telecommute way ;) Contact information you will be able to find in About me section of this blog.

Nagios | The Industry Standard in IT Infrastructure Monitoring

CPUMem Cisco 2800 plugin Nagios Exchange

by GarciaPL on Friday, 1 March 2013


Next script to Nagios Exchange has arrived! This one will allow you to check CPU (in 5 min, 1 min and 5 sec period) and Memory (Free and Used Pool) of router Cisco 2800 Series

Nagios Exchange CPU Mem Cisco 2800

Nagios | The Industry Standard in IT Infrastructure Monitoring

Nagios HP BladeSystem Ambient Temperature

by GarciaPL on Saturday, 20 October 2012


I uploaded to my github (link in reference) a script which allow you to check average ambient temperature for all Bays stored in HP BladeSystem using it's Onboard Administrator from which I put below sample output.


VM-CPX-CPD-1> show server temp all

Device Bay #1 Temperature Information
Locale                              Status      Temp    Caution   Critical
----------------------------------- ------    --------  -------   --------
Ambient Zone     (Inlet Ambient   ) OK        18C/ 64F    42C       46C
System Zone      (System Board    ) OK        23C/ 73F    85C       90C
CPU Zone         (CPU 1           ) OK         7C/ 44F    75C       80C
CPU Zone         (CPU 2           ) OK        19C/ 66F    75C       80C
CPU Zone         (CPU 3           ) OK          N/A
CPU Zone         (CPU 4           ) OK          N/A
Memory Zone      (DIMMs 1         ) OK        30C/ 86F    87C       92C
Memory Zone      (DIMMs 2         ) OK        29C/ 84F    87C       92C
Memory Zone      (DIMMs 3         ) OK          N/A
Memory Zone      (DIMMs 4         ) OK          N/A
Memory Zone      (Mem 1 1-4 Zone  ) OK        34C/ 93F    85C       90C
Memory Zone      (Mem 1 5-8 Zone  ) OK        35C/ 95F    85C       90C
Memory Zone      (Mem 2 1-4 Zone  ) OK        30C/ 86F    85C       90C
Memory Zone      (Mem 2 5-8 Zone  ) OK        34C/ 93F    85C       90C
Memory Zone      (Mem 3 1-4 Zone  ) OK        23C/ 73F    85C       90C
Memory Zone      (Mem 3 5-8 Zone  ) OK        23C/ 73F    85C       90C
Memory Zone      (Mem 4 1-4 Zone  ) OK        22C/ 71F    85C       90C
Memory Zone      (Mem 4 5-8 Zone  ) OK        24C/ 75F    85C       90C
I/O Board Zone   (IOH 1           ) OK        64C/147F   100C      105C
I/O Board Zone   (IOH 2           ) OK        62C/143F   100C      105C
I/O Board Zone   (NIC Zone        ) OK        67C/152F    90C       95C
I/O Board Zone   (Mezz Zone       ) OK        60C/140F    90C       95C
System Zone      (Chassis Exit    ) OK        64C/147F   100C      105C
Storage Zone     (HDD Max         ) OK        35C/ 95F    60C       65C

Virtual Fan: 28%

Device Bay #2 Temperature Information
Locale                              Status      Temp    Caution   Critical
----------------------------------- ------    --------  -------   --------
Ambient Zone     (Inlet Ambient   ) OK        17C/ 62F    42C       46C
System Zone      (System Board    ) OK        23C/ 73F    85C       90C
CPU Zone         (CPU 1           ) OK         6C/ 42F    75C       80C
CPU Zone         (CPU 2           ) OK         5C/ 41F    75C       80C
CPU Zone         (CPU 3           ) OK          N/A
CPU Zone         (CPU 4           ) OK          N/A
Memory Zone      (DIMMs 1         ) OK        30C/ 86F    87C       92C
Memory Zone      (DIMMs 2         ) OK        27C/ 80F    87C       92C
Memory Zone      (DIMMs 3         ) OK          N/A
Memory Zone      (DIMMs 4         ) OK          N/A
Memory Zone      (Mem 1 1-4 Zone  ) OK        33C/ 91F    85C       90C
Memory Zone      (Mem 1 5-8 Zone  ) OK        35C/ 95F    85C       90C
Memory Zone      (Mem 2 1-4 Zone  ) OK        28C/ 82F    85C       90C
Memory Zone      (Mem 2 5-8 Zone  ) OK        32C/ 89F    85C       90C
Memory Zone      (Mem 3 1-4 Zone  ) OK        23C/ 73F    85C       90C
Memory Zone      (Mem 3 5-8 Zone  ) OK        23C/ 73F    85C       90C
Memory Zone      (Mem 4 1-4 Zone  ) OK        22C/ 71F    85C       90C
Memory Zone      (Mem 4 5-8 Zone  ) OK        22C/ 71F    85C       90C
I/O Board Zone   (IOH 1           ) OK        58C/136F   100C      105C
I/O Board Zone   (IOH 2           ) OK        44C/111F   100C      105C
I/O Board Zone   (NIC Zone        ) OK        62C/143F    90C       95C
I/O Board Zone   (Mezz Zone       ) OK        57C/134F    90C       95C
System Zone      (Chassis Exit    ) OK        63C/145F   100C      105C
Storage Zone     (HDD Max         ) OK        35C/ 95F    60C       65C

Virtual Fan: 27%

Parameters :


-H
print help message

-c CRITICAL
critical level for average temperature

-w WARNING
warning level for average temperature

-U USERNAME
username to HP Onboard Administrator

-P PASSWORD
password to HP Onboard Administrator

-m TEMPERATURE
minimum temperature 

-x TEMPERATURE
maximum temperature


Example usage :

./NagiosHPBladeSystemTemperature.php -U <userName> -P <Password> -c <criticalLevel> -w <warningLevel> -m <minTemperature> -x <maxTemperature>





Monitor Cisco HSRP with SNMP

by GarciaPL on Tuesday, 17 July 2012

Cisco

In this post I would like to present Perl script for Nagios that can check HSRP state of Cisco host(s) in network using SNMP protocol (only version 3) and return an output about error level (OK, Warning or Critical) related to Nagios.


Main table in MIB where all information related with HSRP state are stored is cHsrpGrpTable, where are many cHsrpGrpEntry objects which correspond with HSRP groups configured on router and each of them contains configuration and status related with this Cisco protocol.

Example snmpwalk over HSRP information in MIB :


SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.2.1.1 = STRING: "pr0jekt"
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.3.1.1 = Gauge32: 105
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.4.1.1 = INTEGER: 1
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.5.1.1 = Gauge32: 0
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.6.1.1 = INTEGER: 2
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.7.1.1 = Gauge32: 0
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.8.1.1 = Gauge32: 0
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.9.1.1 = Gauge32: 3000
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.10.1.1 = Gauge32: 10000
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.11.1.1 = IpAddress: 10.102.33.1
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.12.1.1 = INTEGER: 1
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.13.1.1 = IpAddress: 10.102.33.253
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.14.1.1 = IpAddress: 10.102.33.254
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.15.1.1 = INTEGER: 6
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.16.1.1 = Hex-STRING: 00 00 0C 07 AC 01
SNMPv2-SMI::enterprises.9.9.106.1.2.1.1.17.1.1 = INTEGER: 1



The properly way to examine HSRP state is iterate through SNMP interface ID and HSRP group ID (this in one before last and last one digit from above OID for example 1 and 1), but this script skip this step and only fetch information from cHsrpGrpStandbyState parameter ;) :



1: initial
2: learn 
3: listen 
4: speak 
5: standby 
6: active 



Additional functionality of this script is that it can inform Nagios about things that are happening with HSRP protocol of host(s) defined in command line.


Parameters :


-h --help
print this help message

-u --username=USERNAME
username e.g. test_user

-a --authprotocol=PROTOCOL
protocol for auth e.g. SHA

-A --authpassword=PASSWORD
password for auth

-x --privprotocol=PROTOCOL
protocol for auth e.g. DES

-X --privpassword=PASSWORD
password for auth

-H --hostname=HOST(s)
name or IP address of host(s)

-S --switch=SWITCH
name or IP address of switch



Example usage :

./HSRP.pl -u <userName> -a <authProtocol> -A <authPassword> -x <privProtocol> -X <privPassword> -H [<host1>,<host2>,<host3>,...] -S <switch1>




Nagios | The Industry Standard in IT Infrastructure Monitoring



Reference:
[1] Cisco HSRP Documentation
[2] Pierky blog

 [3]  Source GitHub

Nagios Can't locate utils.pm in @INC

by GarciaPL on Wednesday, 11 July 2012

Nagios


I am currently working on a plugin for Nagios and i was faced with small problem :(


Can't locate utils.pm in @INC (@INC contains: /usr/local/nagios/libexec /opt/nagios/perl/lib /usr/lib/perl5/5.10.0/x86_64-linux-thread-multi /usr/lib/perl5/5.10.0 /usr/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi /usr/lib/perl5/site_perl/5.10.0 /usr/lib/perl5/vendor_perl/5.10.0/x86_64-linux-thread-multi /usr/lib/perl5/vendor_perl/5.10.0 /usr/lib/perl5/vendor_perl .) at ./HSRPCheck.pl line 22.



The main reason due to this error is a wrong defined library in Perl script (or whatever other language) for check_snmp_int module. So, the solution of this problem is quite easy. You should just change in your script this line :


use lib "/usr/local/nagios/libexec" ;

to

use lib "/usr/lib/nagios/plugins" ;


and whala! Now it works ;)

PS. Also your Nagios can be installed in other directory, so just execute this one command in terminal :

locate /nagios/plugins

and if you get full path to directory which contains plugins just paste it to your script. (use lib 'Received Path')

Of course i will post my script related with this issue in the separate post ;-)



Nagios | The Industry Standard in IT Infrastructure Monitoring




Reference :