原创作品,允许转载,转载时请务必以超链接形式标明文章
原始出处 、作者信息和本声明。否则将追究法律责任。
http://dgd2010.blog.51cto.com/1539422/1670233
-
用户按键,特别是快捷键(如Ctrl+D,Ctrl+C或Ctrl+\等的处理)
-
pts的数值可能会shell脚本中的最大值,除非新登录的用户的pts数值只增加不减少
-
PAM安全模块也许有更好的解决方案(shell脚本肯定不是最佳方案)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
#!/bin/bash
# This shell script will knock out extra ssh connection
# 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
|