Showing posts with label Perl. Show all posts

PerlJobs

by GarciaPL on Thursday, 31 March 2016

I would like to announce that new Android app has been released recently times by me. This time application is called PerlJobs. This application helps you as a Perl developer to find new job opportunities across the globe. Job offers are divided into sections : Standard, Mod, Catalyst, Mason, Telecommute and By Country. The main source of all jobs is website : https://jobs.perl.org

Finance Currency Convert

by GarciaPL on Tuesday, 17 February 2015

After my last trip do Budapest with my wife (I really recommend going to this town! It's wonderful! not only building, but also people are very very nice to tourists), I had a little forints. There is not such much of them, but recently I was checking what is the current currency rate of forint to exchange those money. It was no such difficult to do it, I just did request to Google like '9000 HUF to PLN'. Then idea came to me, that I can wrote some script in Perl which can do it for me and additionally inform via email when there is a good opportunity to exchange those money.

For sending emails I used very nice API called Mandrill [2]. For currency convert from HUF to PLN I used module called Finance::Currency::Convert::Yahoo [3].

#!/usr/bin/perl -w
use strict;
use POSIX;
use WebService::Mandrill;
use Finance::Currency::Convert::Yahoo;
 
$Finance::Currency::Convert::Yahoo::CHAT = 1;
$_ = Finance::Currency::Convert::Yahoo::convert(9430,'HUF','PLN');
 
if (defined($_)) {
   if (floor($_) gt 135) {
      print "Sell HUF : ".floor($_)."\n";
      send_email('receiver@gmail.com', 'Sell HUF', 'Right now there is the time to sell HUF');
   } else {
      print "Keep HUF\n";
   }
} else {
   print "Error\n";  
}
 
sub send_email {
 
        (my $to, my $subject, my $body) = @_;
 
        my $mandrill = WebService::Mandrill->new(
                debug   => 1,
                api_key => 'YOUR_API_TO_MANDRILL',
        );
 
        my $response = $mandrill->send(
                subject      => $subject,
                from_email   => "sender\@gmail.com",
                text         => $body,
                track_opens  => 1,
                track_clicks => 1,
                to => [
                    { email => $to }
                ],
        );
}




Reference : [1] Pastebin Source Code Finance Current Convert [2] Mandrill.com [3] CPAN Finance::Currency::Convert::Yahoo

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

HP Data Protector Reports

by GarciaPL on Wednesday, 21 August 2013

Many many years ago on the one of the intern I have created a small tool to create reports about backups of Oracle and File System in company using HP Data Protector. Below I put a printscreen of output file :

HP Data Protector Report


And the final script code to create HP Data Protector reports :

use Date::Calc;
use Spreadsheet::WriteExcel;
use Spreadsheet::WriteExcel::Utility;

sub help_syntax {
 print "\nHelp Syntax :\n\n";
 print "Backuped FileSystems and Oracle (default) -> perl script_name.pl\n";
 print "Backuped FileSystems and Oracle in .xls format -> perl script_name.pl --xls\n";
 print "Backuped FileSystems -> perl script_name.pl --FS\n";
 print "Backuped FileSystems in format .xls -> perl script_name.pl --FS --xls\n";
 print "Backuped Oracle -> perl script_name.pl --Oracle\n";
 print "Backuped Oracle in format .xls -> perl script_name.pl --Oracle --xls\n\n";
}

$boolean_only_FS=0;
$boolean_only_Oracle=0;
$boolean_only_xls=0;

if ( scalar(@ARGV) > 2 )
{
 print "Numer of arguments is incorrect (max 2)\n";
 &help_syntax;
 exit;
}

my $workbook;
my $worksheet;
my ($x,$y)=(0,0);
my $glowny_licznik=0;

sub xls_function {

 $workbook = Spreadsheet::WriteExcel->new('output.xls');
 $worksheet = $workbook->add_worksheet('Backups');
 $format = $workbook->add_format();
 $format->set_bold();
 $format->set_align('center');
 $format->set_fg_color('grey');
 $format->set_size(12);
 $format->set_color('black');
 $worksheet->set_column(0,0,20);
 $worksheet->set_column(1,1,30);
 $worksheet->set_column(2,2,7);
 $worksheet->set_column(3,3,40);
 $worksheet->set_column(4,4,13);
 $worksheet->set_column(5,5,15);
 $worksheet->set_column(6,6,18);
 $worksheet->write(0,0,"Session",$format);
 $worksheet->write(0,1,"Server",$format);
 $worksheet->write(0,2,"Type",$format);
 $worksheet->write(0,3,"Backuped filesystems",$format);
 $worksheet->write(0,4,"Time start",$format);
 $worksheet->write(0,5,"Duration",$format);
 $worksheet->write(0,6,"Data GB",$format);
}

@lista_argumentow;
foreach (@ARGV) {
 push(@lista_argumentow,$_);
}

if ( @lista_argumentow[0] eq "--help" || @lista_argumentow[0] eq "-help" || @lista_argumentow[0] eq "/h" || @lista_argumentow[0] eq "help" )
{
 &help_syntax;
 exit;
}
elsif ( @lista_argumentow[0] eq "--xls" and @lista_argumentow[1] eq "" )
{
 $boolean_only_xls=1;
 $boolean_only_FS=1;
 $boolean_only_Oracle=1;
 &xls_function;
}
elsif ( @lista_argumentow[0] eq "--FS" and @lista_argumentow[1] eq "--xls" )
{
 $boolean_only_xls=1;
 $boolean_only_FS=1;
 
 &xls_function;
}
elsif ( @lista_argumentow[0] eq "--Oracle" and @lista_argumentow[1] eq "--xls" )
{
 $boolean_only_xls=1;
 $boolean_only_Oracle=1;
 
 &xls_function;
}
elsif ( @lista_argumentow[0] eq "--FS" and @lista_argumentow[1] eq "" )
{
 $boolean_only_FS=1;
}
elsif ( @lista_argumentow[0] eq "--Oracle" and @lista_argumentow[1] eq "" )
{
 $boolean_only_Oracle=1;
}
elsif ( scalar(@ARGV) eq 0 )
{
 $boolean_only_Oracle=1;
 $boolean_only_FS=1;
}
else
{
 &help_syntax;
 exit;
}

###################################################################################

$omniback_path="D:/HP/OmniBack/bin";

chdir($omniback_path) or die "Cannot open path $omniback_path\n";

if (-e "omnirpt.exe" ) {
 print "Found omnirpt.exe\n";
}
else {
 print "File omnirpt.exe does not exist. Exit program.\n";
 exit;
}

$lista_sesji_command=`omnirpt.exe -report list_sessions -timeframe 24 24`;

open FILE, ">session_list.txt" or die $!; #print list of session for Oracle and FileSystem
print FILE $lista_sesji_command;
close FILE;
print "Created session list in file session_list.txt\n";

if (-e "session_list.txt")
{
open (CHECKBOOK, "output.txt');

$count = 0;
$count_oracle=0;

while ($record = ) {
  @tokens = split(/\s+/, $record);
  my $boolean = 0;
  $count_oracle=0;
  $count=$count+1;
  foreach my $token (@tokens) {
   if ( @tokens[2] ne "Oracle8" and $boolean_only_FS eq 1)
   {
    if ( $boolean eq 0 )
    {
     if( @tokens[15] ne "Errors" )
     {
      if( @tokens[15] ne "" )
      {
       print "\n----FileSystem----\n";
       print "Session : ",@tokens[2],"\n";
       print "Time start : ",@tokens[6],"\n";
       print "Duration : ",@tokens[8],"\n";
       print "Data GB : ",@tokens[9],"GB\n";
       print "SessionID : ",@tokens[15],"\n";
       
       $temp_session_ID=@tokens[15];
       $session_objects=`omnirpt.exe -report session_objects -session $temp_session_ID`;
       $licz=0;
       $temp_host;
       $temp_host2;
       $boolean_session=1;
       $flaga_rowne=1;
       $flaga_nierowne=1;
       
       @tokens_session_objects = split(/\s+/, $session_objects);
       foreach my $token_session (@tokens_session_objects) {
        $licz=$licz+1;
        $temp_host=@tokens_session_objects[$licz];
        
        if( $token_session =~ m/FileSystem/)
        {
          $glowny_licznik = $glowny_licznik + 1;
        
          if ( $boolean_session )
          {
           $temp_host2=$temp_host;
          }

          ####################################################################################       

          if ( $boolean_session )
          {
           print PLIK_WYNIKOWY @tokens[2]," ";   #Session (once)
           
           if ( $boolean_only_xls ) 
           {
            $worksheet->write($glowny_licznik,0,@tokens[2]);
           }
          }
          if ( $boolean_session )
          {
           print PLIK_WYNIKOWY " ",@tokens_session_objects[$licz]," ";  #host
           
           if ( $boolean_only_xls ) 
           {
            $worksheet->write($glowny_licznik,1,@tokens_session_objects[$licz]);
           }
          }
          else
          {
           print PLIK_WYNIKOWY "  ",@tokens_session_objects[$licz]," ";  #host
           
           if ( $boolean_only_xls ) 
           {
            $worksheet->write($glowny_licznik,1,@tokens_session_objects[$licz]);
           }
          }
          
          if ( @tokens_session_objects[$licz] eq $temp_host2 and $flaga_rowne == 1)  #hosts name are the same
          {
           if ( $boolean_session )
           {
            print PLIK_WYNIKOWY "FS","  ";  
            
            if ( $boolean_only_xls ) 
            {
             $worksheet->write($glowny_licznik,2,"FS");
            }
            
           }
          }
          if ( @tokens_session_objects[$licz] ne $temp_host2 and $flaga_nierowne == 1) #different host names
          {
           if ( $boolean_session )
           {
            print PLIK_WYNIKOWY "FS","  "; 
            
            if ( $boolean_only_xls ) 
            {
             $worksheet->write($glowny_licznik,2,"FS");
            }
           }
          }
          
          
          if ( $boolean_session )
          {
           print PLIK_WYNIKOWY @tokens_session_objects[$licz+1],"  "; #Backuped filesystems
           
           if ( $boolean_only_xls ) 
           {
            $worksheet->write($glowny_licznik,3,@tokens_session_objects[$licz+1]);
           }
          }
          else
          {
           print PLIK_WYNIKOWY @tokens_session_objects[$licz+1],"\n"; #Backuped filesystems
           
           if ( $boolean_only_xls ) 
           {
            $worksheet->write($glowny_licznik,3,@tokens_session_objects[$licz+1]);
           }
          }
          
          
          if ( @tokens_session_objects[$licz] eq $temp_host2 and $flaga_rowne == 1)  #host names are the same
          {
           if ( $boolean_session )
           {
            print PLIK_WYNIKOWY @tokens[6]," ";       #Time start (once)
            print PLIK_WYNIKOWY @tokens[8]," ";       #Duration (once)
            print PLIK_WYNIKOWY @tokens[9],"GB\n";       #Data GB (once)
            $boolean_session=0;
            
            if ( $boolean_only_xls ) 
            {
             $worksheet->write($glowny_licznik,4,@tokens[6]);
             $worksheet->write($glowny_licznik,5,@tokens[8]);
             $worksheet->write($glowny_licznik,6,"@tokens[9] GB");
            }
           }
          
           $flaga_rowne=0;
           $flaga_nierowne=1;
          }
          if ( @tokens_session_objects[$licz] ne $temp_host2 and $flaga_nierowne == 1) #different host names
          {
           if ( $boolean_session )
           {
            print PLIK_WYNIKOWY @tokens[6]," ";       #Time start (once)
            print PLIK_WYNIKOWY @tokens[8]," ";       #Duration (once)
            print PLIK_WYNIKOWY @tokens[9],"GB\n";       #Data GB (once)
            $boolean_session=0;
            
            if ( $boolean_only_xls ) 
            {
             $worksheet->write($glowny_licznik,4,@tokens[6]);
             $worksheet->write($glowny_licznik,5,@tokens[8]);
             $worksheet->write($glowny_licznik,6,"@tokens[9] GB");
            }
           }
           
           $flaga_nierowne=0;
           $flaga_rowne=1;
          }
          
          $temp_host=@tokens_session_objects[$licz];
          $temp_host2=@tokens_session_objects[$licz];
        }
       }
       print "\n";
       $boolean = 1;
      }
     }
    }
   }
   elsif ( $boolean_only_Oracle eq 1 ) #in the session found Oracle8
   {
    $temp_session_oracle=@tokens[16];     #sessionID
    $oracle=`omnidb.exe -session $temp_session_oracle`;
    @tokens_oracle8 = split(/\s+/, $oracle);
    my $boolean_check=1;

    foreach my $token_oracle (@tokens_oracle8) {

     if( $token_oracle =~ m/.dbf/ and $boolean_check eq 1) #one host - one SID
     {
      $glowny_licznik = $glowny_licznik + 1;
     
      $znak_mniejszosci=rindex($token_oracle,'<');
      $podkreslenie=rindex($token_oracle,'_');
      $SID_Bazy=substr($token_oracle,$znak_mniejszosci+1,$podkreslenie-$znak_mniejszosci-1);
 
      $dwukropek=index($token_oracle,':');
      $Host=substr($token_oracle,0,$dwukropek);

      print "\n----Oracle8----\n";
      print "Session : ",@tokens[3],"\n";
      print "Time start : ",@tokens[7],"\n";
      print "Duration : ",@tokens[9],"\n";
      print "Data GB : ",@tokens[10],"GB\n";
      print "SessionID : ",@tokens[16],"\n";
      print "SID Bazy : ",$SID_Bazy,"\n";
      
      #write to output file

      print PLIK_WYNIKOWY @tokens[3]," "; #Session
      print PLIK_WYNIKOWY $Host,"  ";  #Host 
      print PLIK_WYNIKOWY "Oracle","  "; #Oracle
      print PLIK_WYNIKOWY $SID_Bazy,"  ";  #Database SID
      print PLIK_WYNIKOWY @tokens[7]," "; #Time start
      print PLIK_WYNIKOWY @tokens[9]," "; #Duration
      print PLIK_WYNIKOWY @tokens[10],"GB\n"; #Data GB
      
      if ( $boolean_only_xls ) 
      {
       $worksheet->write($glowny_licznik,0,@tokens[3]);
       $worksheet->write($glowny_licznik,1,$Host);
       $worksheet->write($glowny_licznik,2,"Oracle");
       $worksheet->write($glowny_licznik,3,$SID_Bazy);
       $worksheet->write($glowny_licznik,4,@tokens[7]);
       $worksheet->write($glowny_licznik,5,@tokens[9]);
       $worksheet->write($glowny_licznik,6,"@tokens[10] GB");
      }
      
      $boolean_check=0;
     }
    
    }
    print "\n";
    last;
   }
  }
  $boolean = 1;
}
close(CHECKBOOK);
close(PLIK_WYNIKOWY);
}
else {
print "File session_list.txt does not exist";
}

if ( $boolean_only_xls eq 1 ) {
 $workbook->close();
}


Reference :  [1] Pastebin GarciaPL HP Data Protector [2] Wikipedia HP Data Protector [3] HP Data Protector Resources

Killing processes contain pattern

by GarciaPL on Saturday, 10 August 2013

I would like to share, in my opinion, quite helpful tool dedicated for Linux administrators for ending (or some of you would say "killing") processes which contain particular pattern. I prepared a dedicated script written in Perl which is very easy to help. If you would like to kill all processes contain word "chrome" just run like this one : ./KillProcesses.pl -p chrome. I also wrote a small program with infinity loop which can be used for testing purposes. It can be found using pattern LoopProcess.

KillProcesses.pl

#!/usr/bin/perl -w

use strict;
use warnings;
use Getopt::Long;
use Data::Dumper;

my $help;
my $process_pattern = undef;

sub kill_processes {
 if (defined($process_pattern)) {
  my @processeslist = `ps -ef | grep $process_pattern | grep -v grep | awk '{print \$2}'`;

  if ((@processeslist) and (scalar(@processeslist) > 1)) {
   print "\nKilling processes with PID like : \n";
   print @processeslist;
   my @killprocess = `kill -9 @processeslist`;
   print Dumper @killprocess;
  } else {
   print "\nCan not find processes contain a pattern '$process_pattern'\n";
  }
 } else {
  print "\nProcess name was not defined\n";
 }
}

sub usage {
    print "$0 -p \n";
}

sub help {
   print "\nKill All Processes along with pattern\n";
   usage();
   print < \$help,
  'p=s'  => \$process_pattern,   'pattern=s' => \$process_pattern
    );

if ($help) { help(); exit; }
if (!defined($process_pattern))
    { print "Put pattern of process! (-h for help)\n"; usage(); exit;}
}

######### MAIN PROGRAM

check_input();

######## KILL PROCESSES ALONG WITH PATTERN
print "\nSearching and ending processes contain a pattern '$process_pattern'";
kill_processes();


LoopProcess.pl

#!/usr/bin/perl -w

use strict;
use warnings;

while (1) {

}


Reference :  [1] GarciaPL Pastebin KillProcesses [2] GarciaPL Pastebin LoopProcess

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

Perl Check for Business Days with DateTime module

by GarciaPL on Thursday, 25 April 2013

Quick piece of code how to check if given date in DateTime module format is business day or not ;) I think that this function is very usefull for every kind of business application that you would like to write in the near future ;)

my @day_of_week = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday');

sub check_business_day {
 my ($name_of_day) = @_;
 if ( grep( /^$name_of_day$/, @day_of_week ) ) {
  return 1;
 } else {
  return 0;
 }
}

check_business_day($date_time->day_name());

Function returns 1 if given day name from $date_time variable is a business day, otherwise it return 0.

Reference :
[1] Source Pastebin.com

Perl check if directory exists

by GarciaPL on Tuesday, 7 August 2012


A quik and small tip in Perl which may sound funny, but it saved my life :D

if ( -d "/folder/path/" ) {
         print "Success! Directory exists!\n";
} else {
         print "Sad news... It is gone!\n";
}


Reference :
[1] Source Pastebin.com