Tuesday, March 15, 2011

BASH script for generating complex password


Description:
This script can be used to generate complex password with predefined password length.

Script:
#!/bin/bash
#Filename : randompass.sh

#Sets the length of the password the script will generate
echo -n "Enter the password length that you require : "
read MAXSIZE

# Holds valid password characters. I choose alpha-numeric + the shift-number keyboard keys
# I put escape chars on all the non alpha-numeric characters just for precaution
array1=(
w e r t y u p a s d f h j k z x c v b m Q W E R T Y U P A D
F H J K L Z X C V B N M 2 3 4 7 8 ! @ $ % \# \& \* \= \- \+ \?
)
# Used in conjunction with modulus to keep random numbers in range of the array size
MODNUM=${#array1[*]}
# Keeps track of the number characters in the password we have generated
pwd_len=0
while [ $pwd_len -lt $MAXSIZE ]
do
  index=$(($RANDOM%$MODNUM))
  password="${password}${array1[$index]}"
  ((pwd_len++))
done
echo $password

Sample Execution: 
[root@sysllm01 create_password]# sh random_pass.sh
Enter the password length that you require : 10
D34EXL*3@$
[root@sysllm01 create_password]#

Cool stuff right :) 

Wednesday, March 2, 2011

Perl script for Querying Oracle DB


Description: 
This script can be used as an template to query Oracle Database using the Sid, Port, Oracle DB username and Password. You can customize the SQL Query which I used in this script. This script basically checks the completion of RMAN backup activity done by Database Administrators.

Requirements:
Oracle SID
Port Number
Oracle username & Password


----------------------------------------------------------------------------------------------------------
#!/usr/bin/perl

use DBI;

my $oracle_sid = 'emcprod';
my $oracle_port = '1530';
my $oracle_user = 'oracleuser';
my $oracle_password = 'XXXXXXX';
my $bkptime;
my $bkpstatus;
my $yesterday = `date --date='1 day ago' +%d-%m-%Y`;
chomp($yesterday);

sub RmanDBStatusCheck($$);

# Create a temporary log file to log and track all the changes
$logFile = GetTime(1)."\_"."$userName"."\.log";
print "Logging all output to $logFile\n";

# Open the log file
open(LOGFILE,">$logFile") || die (print "Cannot create logfile $logFile \n");
Log ("Running verion $version of $program",0,LOGFILE);


RmanDBStatusCheck("oralsb40",LOGFILE);

sub RmanDBStatusCheck($$)
{
        my $hostname=$_[0];
        my $outputDestination=$_[1];
        my $dbh = DBI->connect("dbi:Oracle:host=$hostname;port=$oracle_port;sid=$oracle_sid", $oracle_user, $oracle_password)
                or die "Unable to initialize DB connection : " . DBI->errstr;

        Log("==================================================",0,$outputDestination);
  my $sql_query="select to_char(END_TIME , 'dd-mon-yyyy@hh24:mi:ss') "Date and Time",status from V$RMAN_BACKUP_JOB_DETAILS where start_time > (sysdate);";
               my $sth = $dbh->prepare("$sql_query") or die "Couldnot query Oracle Database" . $dbh->errstr;
               $sth->execute() or die "Couldnot execute query on Oracle Database" . $sth->errstr;
                        while ( my @column = $sth->fetchrow_array() ) {
                        $bkpday = $column[0];
                        $bkpstatus = $column[1];
                        print "Printing Arrage/DB Value=@column\n";
                        }
                        $sth->finish;
                        $dbh->disconnect;
                        if(($bkpday eq "$yesterday") && ($bkpstatus eq 'COMPLETED'))
                        {
                          Log("RMAN DBA activity completed",0,$outputDestination);
                          return(0);
                        }
                        elsif (($bkpday eq "$yesterday") && ($bkpstatus eq 'FAILED'))
                        {
                          Log("RMAN DBA activity failed",0,$outputDestination);
                          return(1);
                        }
                        else
                        {
                        Log("RMAN DBA activity is still in progress",0,$outputDestination);
                        return(2);
                        }

}

sub Log($$$)
{
    my $text = $_[0];
    my $exitStatus = $_[1];
    my $outputDestination = $_[2];
    my $time = GetTime(0);
    if ($exitStatus == 1)
    {
        my $time = GetTime(0);
        print "[$time] - $text\n";
                print "[$time] - Exiting..!\n";
        exit;
    }
    print $outputDestination "[$time] - $text\n";
    print "[$time] - $text\n";
}

sub GetTime($)
{
    # Get the locatime
    my ($Second, $Minute, $Hour, $Day, $Month, $Year) = (localtime)[0,1,2,3,4,5];

    # Add padding as required
    $Year = $Year+1900;
    $Month = $Month+1;

    # Format into a nice string
    my $Time = "$Month-$Day-$Year $Hour:$Minute:$Second";

    # Spit it out
    if ($_[0] == 1)
    {
        $Time = "$Month-$Day-$Year\_$Hour\_$Minute\_$Second";
        return $Time;
    }
    return $Time;
}

A template for chkconfig script


This script can be used as a Template for developing a customized service script, which can be controlled using 'chkconfig' and 'service' command. In this script, I have converted an application ('admin') startup/stop/restart/check status procedure into a chkconfig script. This 'admin' application is a JBoss application which uses JDK version 1.6.0_14.

______________________________________________________________________
#!/bin/bash
#
# chkconfig: 2345 9 91
# description: Admin application
#

# Source function library.
if [ -x /etc/rc.d/init.d/functions ]; then
   . /etc/rc.d/init.d/functions
fi

PROG=`basename $0`

# Initializing Return value
RETVAL=0

# Defining Application start script path
START_APP_PATH='/home/jboss/startChain.sh'

# Defining JDK path
JDK_PATH='/usr/java/jdk1.6.0_14/bin/java'

# Unique string for Jboss process
UNIQUE_STRG='Dprogram.name=run.sh'

# Defining the pid file for this jboss instance
JBOSSPID=`ps -eaf | grep java | grep "$UNIQUE_STRG" | grep -v grep  | awk '{print $2}'`

#define the lock file for this jboss instance
JBOSSLOCK="/var/lock/subsys/${PROG}"

# Current time
CURRENT_TIME=`date '+%m-%d-%y %k:%M'`

# Set the defaults.
LOGFILE=/var/log/${PROG}/${PROG}-`date '+%m-%d-%y'`.log

start ()
{
        echo -n "Checking the current application status........."
        status
        if [ "$?" = 0 ]; then
        echo -e "Attempting to start Admin Application\n"
        touch $JBOSSLOCK
        . $START_APP_PATH
        RETVAL=$?
        if [ "$RETVAL" == "0" ]; then
                sleep 10
                JBOSSPID=`ps -eaf | grep java | grep "$UNIQUE_STRG" | grep -v grep  | awk '{print $2}'`
                echo "Admin application successfully started with JBOSS PID: $JBOSSPID" && echo
                echo "$CURRENT_TIME: Admin application started" >> $LOGFILE
        else
                echo "Couldn't start Admin application, Please check it manually" && echo
                echo "$CURRENT_TIME: Couldn't start Admin application." >> $LOGFILE
        fi
        else
                echo "$CURRENT_TIME: Admin application already running. Exiting the script...!" >> $LOGFILE
                echo "Admin application already running. Exiting the script...!" && exit 0
    fi
}

stop ()
{
        echo -n "Checking the current application status........."
        status
        if [ "$?" = "1" ]; then
        JBOSSPID=`ps -eaf | grep java | grep "$UNIQUE_STRG" | grep -v grep  | awk '{print $2}'`
        echo -e "Attempting to stop Admin application with JBOSS PID: $JBOSSPID\n"
        kill -15 "$JBOSSPID"
        sleep 2
        CNT=1
          while true; do
                JBOSS_PROC_CNT=`ps -ef | grep -c "$JBOSSPID"`
                if [ "$JBOSS_PROC_CNT" == "0" ]; then
                        echo && echo "Admin Application has been stopped" && echo
                        rm -rf /var/lock/subsys/admin
                        echo "$CURRENT_TIME: Admin application has been stopped." >> $LOGFILE
                        JBOSSPID=''
                        return 0
                fi
                CNT=`expr $CNT + 1`
                if [ $CNT -gt 28 ]; then
                        echo "Couldn't stop Admin Application. Please check it manually." && echo
                        echo "$CURRENT_TIME: Couldn't stop Admin Application. Please check it manually." >> $LOGFILE
                        return 0
                fi
                sleep 1
                echo -n "."
          done
        fi
}

status ()
{
        if [ -z "$JBOSSPID" ] && [ "$JBOSSPID" = '' ]; then
                echo "Admin application isn't running" && echo
                return 0
        else
                echo "Admin application is running with JBOSS PID: $JBOSSPID" && echo
                return 1
        fi
}

restart ()
{
        status
        if [ "$?" = 0 ]; then
                start
        else
                # Stoping the Application
                stop
                #Restarting Application
                start
        fi
}


case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart)
        echo "Restarting Admin application" && echo
        restart
        ;;

    *)
        echo "Usage: $PROG {start|stop|status|restart}"
        exit 1

esac

exit $RETVAL


SAMPLE EXECUTION
[root@hostxyz-t3 tmp]# chkconfig --list | grep admin
admin           0:off   1:off   2:on    3:on    4:on    5:on    6:off
[root@hostxyz-t3 tmp]# su - jboss
[jboss@hostxyz-t3 ~]$ sudo /sbin/service admin status
Admin application is running with JBOSS PID: 15912

[jboss@hostxyz-t3 ~]$ sudo /sbin/service admin stop
Checking the current application status.........Admin application is running with JBOSS PID: 15912

Attempting to stop Admin application with JBOSS PID: 15912

..........
Admin Application has been stopped

[jboss@hostxyz-t3 ~]$ sudo /sbin/service admin status
Admin application isn't running

[jboss@hostxyz-t3 ~]$ sudo /sbin/service admin start
Checking the current application status.........Admin application isn't running

Attempting to start Admin Application

Admin application successfully started with JBOSS PID: 12719

[jboss@hostxyz-t3 ~]$ sudo /sbin/service admin status
Admin application is running with JBOSS PID: 12719

[jboss@hostxyz-t3 ~]$ sudo /sbin/service admin restart
Restarting Admin application

Admin application is running with JBOSS PID: 12719

Checking the current application status.........Admin application is running with JBOSS PID: 12719

Attempting to stop Admin application with JBOSS PID: 12719

.
Admin Application has been stopped

Checking the current application status.........Admin application isn't running

Attempting to start Admin Application

Admin application successfully started with JBOSS PID: 12909

[jboss@hostxyz-t3 ~]$

BASH script for doing MD5 checksums

Description: 
This script can be used for doing MD5 checksums on files which are copied/downloaded from FTP server or on files which are restored from Backup tapes to ensure the integrity. This script takes Source path as command-line parameter and upon completion it prints the result on the terminal.

Syntax:  
# scripname.sh  <Source path> 


Sample execution:
[root@oralsb11-new ]# /opt/do_checksum.sh /smbnas/oralsb11
MD5 Checksum testing passed for all the files
[root@oralsb11-new ]#

[root@oralsb11-new tmp]# cat capture_success
./dbfile_IHOTPERF_744220566_255_1.rman: OK
./dbfile_IHOTPERF_744220566_256_1.rman: OK
./dbfile_IHOTPERF_744220566_257_1.rman: OK
./dbfile_IHOTPERF_744221122_258_1.rman: OK
./dbfile_IHOTPERF_744221187_259_1.rman: OK
./dbfile_IHOTPERF_744221293_260_1.rman: OK
./dbfile_IHOTPERF_744221578_261_1.rman: OK
./dbfile_IHOTPERF_744221744_262_1.rman: OK
./dbfile_IHOTPERF_744221829_263_1.rman: OK
./dbfile_IHOTPERF_744222035_264_1.rman: OK
./dbfile_IHOTPERF_744222150_265_1.rman: OK
./dbfile_IHOTPERF_744222176_266_1.rman: OK
./dbfile_IHOTPERF_744222501_267_1.rman: OK
./dbfile_IHOTPERF_744222509_268_1.rman: OK
./dbfile_IHOTPERF_744222674_269_1.rman: OK
./dbfile_IHOTPERF_744222959_270_1.rman: OK
./dbfile_IHOTPERF_744223025_271_1.rman: OK
./dbfile_IHOTPERF_744223171_272_1.rman: OK
./initihotperf.ora: OK
./orapwihotperf: OK
[root@oralsb11-new tmp]# cat capture_failure
[root@oralsb11-new tmp]#
__________________________________________________________________
SCRIPT


#!/bin/bash
# Description: This script is for doing MD5 checksum checks on files on Linux server.
SRC_DIR=$1
RESULT_FILE=/tmp/checksums_result.txt
FAILURE=/tmp/capture_failure
SUCCESS=/tmp/capture_success
cd $SRC_DIR
find ./ -type f -exec md5sum {} \; > /tmp/checksums.txt
md5sum -c < /tmp/checksums.txt > $RESULT_FILE
cat $RESULT_FILE |  grep -v " OK$" > $FAILURE
cat $RESULT_FILE |  grep OK > $SUCCESS
rm -rf $RESULT_FILE
cat $FAILURE | grep OK
if [ "$?" != "1" ]; then
echo "Some of the files not passed the MD5 Checksum testing" && echo
cat $FAILURE
exit 0
else
echo "MD5 Checksum testing passed for all the files"
exit 0
fi
__________________________________________________________________

Popular Posts

About Me

My photo
The intent of this blog is to share my work experience and spread some smart solutions on Linux to System Administrators. I'm hoping the solutions shared in this Blog would be helpful and come as a handy for Viewers. Brief about me: I have 18+ years work experience in System and Cloud Administration domain, primarily works on VMware Cloud Products (vSphere, vCloud Director, vRealize Automation, NSX Adv. Load Balancer, vROps).