#!/bin/sh
#
#    Copyright (c) 2003 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    File name:   snmpKillTelnet
#    Module name: fabos/src/snmp/src/snmpUtils.c
#
#    This script will terminate ALL/SPECIFIC telnet sessions on a switch.
#    ALL telnet sessions option will also  logout the user from console.
#
#    Usage: snmpKillTelnet <Switch Ip Addr>
#               { <switchInst> | <Remote Ip Addr> <Remote Port> }
#
#           <Switch Ip Addr> is ip addr in dot notation Ex: 10.32.227.10
#           <SwitchInst> On a Ulysses is 0 or 1.  On a Terminator is 0.
#           <Remote Ip Addr> is ip addr in dot notation Ex: 192.168.68.45
#           <Remote Port Number> is a numeric. Ex: 4567
#

export PATH=/fabos/sbin:/fabos/bin:/bin:/usr/bin:/sbin

#Error code 1
shFailed=1

#No Error
shSuccess=0

if [ $# -eq 2 ]; then
	switchIp=$1
	switchInst=switch$2

	pidList=`netstat -tnp | grep $switchIp:23 | grep ESTABLISHED |
             cut -s -d: -f3 | sed -e 's/ //g' | cut  -s -d/ -f1 |
             cut -s -dD -f2`

	#if the switch represents IPv4-mapped IPv6 address
	if test "$pidList" = ""
	then
		pidList=`netstat -tnp | grep $switchIp:23 | grep ESTABLISHED |
             cut -s -d: -f9 | sed -e 's/ //g' | cut  -s -d/ -f1 |
             cut -s -dD -f2`
	fi
	# Information for User
	wall All Telnet sessions on $switchInst will be logged out.

elif [ $# -eq 3 ]; then
	switchIp=$1
	remoteIp=$2
	remotePort=$3

	pidList=`netstat -tnp | grep $switchIp:23 | grep $remoteIp:$remotePort |
             grep ESTABLISHED | cut -s -d: -f3 | sed -e 's/ //g' |
             cut  -s -d/ -f1 | cut -s -dD -f2`

	#if the switch represents IPv4-mapped IPv6 address
    if test "$pidList" = ""
    then
        pidList=`netstat -tnp | grep $switchIp:23 | grep $remoteIp:$remotePort |	
				grep ESTABLISHED | cut -s -d: -f9 | sed -e 's/ //g' | 
				cut  -s -d/ -f1 | cut -s -dD -f2`
    fi
else
	#echo Invalid number of arguments: $# returning $shFailed
	exit $shFailed
fi

# Loop through all 'pid' entries of telnet sessions
for pid in $pidList
do
	if test "$pid" = ""
	then
		#echo "Error: Could not find any telnet session."
		exit $shFailed
	fi

	kill -9 $pid > /dev/null
done

#Logout the user from console ttyS0
switchTty=ttyS0

if [ $# -eq 2 ]; then
	for tty in `w -hs | sed -e 's/root/switch/g' | sed -e 's/factory/switch/g' |
				sed -e 's/admin/switch/g' | sed -e 's/user/switch/g' |
				grep $switchTty | sed -e 's/    / /g' | sed -e 's/   / /g' |
				sed -e 's/  / /g' | grep $switchInst | cut -d' ' -f2`
	do
		#Information for user.
		wall $switchTty on switch instance $switchInst will be logged out
		pid=`fuser /dev/$tty | sed -e "s,^/dev/[[:alnum:]/]*:[[:space:]]*,,g"`
		if test "$pid" = ""
		then
			#echo "Error: Could not find sh or rbash for" $tty"."
			exit $shFailed
		fi

		kill -9 $pid > /dev/null
	done
fi

exit $shSuccess
