Wednesday, February 9, 2011

Manage ssh sessions

Hi All,

There is a small script that manages idle ssh connections on the basis of idle hour diff and idle minute difference . Script is very simple and self explanatory. Even though if there is any confusion you  can write me back.


#!/bin/bash
## Written By : jeet27.pawan@gmail.com
## last Updated: 0000-00-00

###### get Command line input ########
# arg1: idle connection hour diff                 #
# arg2: idle connection minute diff              #
#################################

if [ $# == 2 ]; then
idl_hr_diff=$1
idl_mt_diff=$2
elif [ $# == 1 ]; then
idl_hr_diff=$1
idl_mt_diff=0
else
echo "please enter at least one command line argument as idle time hour diff"
exit
fi

list=`ps -W | grep 'sh.exe' | awk '{print $1":"$7}'`;
month=`date | awk '{print $2}'`;
prevmonth=`date -d 'last month' '+%b'`;
#echo $month
hr=`date | awk '{print $4}' | cut -d ':' -f 1`;
mt=`date | awk '{print $4}' | cut -d ':' -f 2`;
#echo $list
for p in $list
do
{
pid=`echo $p| cut -d ':' -f 1`;
hour=`echo $p| cut -d ':' -f 2`;
#echo $hour
minute=`echo $p| cut -d ':' -f 3`;
#echo $minute
#echo $hr
#echo $mt
    if [[ "$month" == "$hour" ]]; then
    {
#        echo 1
        echo "Killing ssh session with pid :"$pid;
        /usr/bin/kill -f $pid;
    }
    elif [[ "$prevmonth" == "$hour" ]]; then
    {
#        echo 11
        $hour=0
        let hour_diff=$hr-$hour
        if [[ "$hour_diff" -gt "$idl_hr_diff" ]] ;then
        {
            echo "Killing ssh session with pid :"$pid;
            /usr/bin/kill -f $pid;
        }
        fi
    }
    else
    {
    let hour_diff=$hr-$hour
    let mid_night_hour_diff=$hour-$hr
#    echo "hello "$hour_diff
    let min_diff=$mt-$minute
#    echo "hi "$min_diff

        if [[ "$hour_diff" -ge "$idl_hr_diff" ]];then
            {   
            if [[ "$min_diff" -ge "$idl_mt_diff" ]]; then
            {
#            echo 2
            echo "Killing ssh session with pid :"$pid
            /usr/bin/kill -f $pid;
            }
            else
            {
#            echo 3
            echo "Ideal time less then threshold value. Skipping process with pid: "$pid
            }
            fi
            }
        else
            {
#            echo 4
            echo "Ideal time less then threshold value. Skipping process with pid: "$pid
            }
        fi
    }
    fi
}
done   

2 comments:

Anonymous said...

Hi
Thanks a lot for this post it helped me a lot....
thanx a lot! :)

Pawan Singh said...

Thanks for writing .. Keep visiting the blog for more updates..