使用hosts.deny拒绝ssh试探连接
主要是为了考虑到在公网打开ssh后,不断有人试探连接,自动实现拒绝。
#!/bin/bash
#赵云
#自动监控ssh试探登陆,将其添加在/etc/hosts.deny实现拒绝
#设置尝试次数,尝试操作3次,就实现拒绝连接
number=3
#设置运行间隔时间,单位秒
sleep=1
#设置锁定试探IP地址时间,单位秒
locktime=15
lockfile=/tmp/lock-ipadd
touch $lockfile
while true
do
#执行锁定检查
for badip in `lastb |awk '{print $3}' |grep -v ^$ |grep -v [A-Z] |sort |uniq -c |awk -vn="$number" '$1 > n {print $2}' `
time=`date +%s`
bip=`echo $badip |head -n $i |tail -n1`
echo $bip |grep [0-9] &>/dev/null
if [ $? -eq 0 ] ; then
grep $bip $lockfile &>/dev/null
if [ $? -eq 1 ] ; then
echo $bip.$time >>$lockfile
fi
grep $bip /etc/hosts.deny &>/dev/null
[ ! $? -eq 0 ] && (echo "SSHD:$bip" >>/etc/hosts.deny; logger "lock ip address $bip ")
cat /var/log/btmp >> /var/log/btmp.bak
>/var/log/btmp
fi
done
#解除锁定操作
nowtime=`date +%s`
rows=`wc -l $lockfile |awk '{print $1}' `
for (( i=1;i<=rows;i++))
line=`cat -n $lockfile |head -n $i |tail -n1 |awk -F. '{print $5" "$1}' |awk -vt="$nowtime" '{print t-$1" "$2}' |awk -vt="$locktime" '$1>t {print $2}'`
echo $line |grep [0-9] &>/dev/null
if [ $? -eq 0 ] ; then
unlockip=`cat -n $lockfile |column -t | grep ^$line |awk '{print $2}' | awk -F. '{print $1"."$2"."$3"."$4}'`
sed -i "/SSHD:$unlockip/d" /etc/hosts.deny
logger "unlock ip address $unlockip "
sed -i "/$unlockip/d" $lockfile
fi
sleep $sleep
日志查看
tail /var/log/messages
Apr 6 19:49:58 localhost sess: lock ip address 192.168.0.31
Apr 6 19:50:47 localhost sess: unlock ip address 192.168.0.31
Apr 6 19:51:02 localhost sess: unlock ip address 192.168.0.56