April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  

Categories

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  

shell script for ssh session

#!/bin/bash
# max_number_of_ssh_client 
max_number_of_ssh_client=3
# lsof is essential
if [[ ! -x `which lsof` ]]; then
    yum install lsof -y
    RETVAL=$?
    if [[ "$RETVAL" -ne "0" ]]; then
        echo "ERROR: can NOT use lsof command, please check your internet connection or install lsof by manual! "
        exit $RETVAL
    fi
else
    # TODO
    # for awk, grep, etc
    echo "SUCCESS: This shell script will knock out extra ssh connection "
fi
# a main worker
# loop
while : ; do
    ssh_port=`netstat -anopt | grep sshd | awk '{print $4}' awk -F ':' '{print $2}' grep -v ^$ | uniq `
    ssh_clients=`lsof -i:$ssh_port | grep \> | awk '{print $9}' awk -F ':' '{print $(NF-1)}' uniq awk -F '>' '{print $2}'`
    for ssh_client in $ssh_clients; do
        number_of_ssh_client=`lsof -i:$ssh_port | grep $ssh_client | wc -l`
        if [[ $number_of_ssh_client -gt $max_number_of_ssh_client ]]; then
            number_pts=`w -hs | grep $ssh_client | awk '{print $2}' awk -F '/' '{print $2}' awk 'BEGIN {max=0} {if ($1>max) max=$1 fi} END {print max}'`
            # TODO
            # another solution maybe exist
            # kill extra logins
            pkill -kill -t pts/$number_pts
            if [[ $? -eq 0 ]]; then
                echo "SUCCESS: extra connections  $ssh_client@pts/$number_pts has been knocked out! "
            else
                echo "WARNNING: can NOT knock out extra connections! "
            fi
        else
            # TODO
            # too many INFO displayed
            echo "INFO: number of ssh connections is NORMAL! "
            # sleep 1
            sleep 1
        fi
    done
done

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>