首页 > 系统服务 > 详细

shell脚本之拒绝非法用户远程

时间:2018-04-30 17:00:36      阅读:221      评论:0      收藏:0      [点我收藏+]

拒绝远程非法用户用过ssh暴力登陆服务器。一旦输入密码错误四次,直接拒绝主机IP登陆。

脚本如下:

#!/bin/bash
#auto deny ssh error ip
#author is lingshu
#2018-04-30
###########################

#definiens file path
SSH_LOG=/var/log/secure
DENY_LIST=/var/log/deny.ip
IPTABLES=/etc/sysconfig/iptables
#查看日志文件的最后一千行,如果发现有输错密码被拒绝四次以上的主机。就抓取被拒绝的IP地址。
IP_LIST=`tail -n 1000 /var/log/secure | grep "Failed password" |awk ‘{print $11}‘|uniq -c |awk ‘$1>4{print $2}‘`

#将拒绝循环写入iptables配置文件
for i in $IP_LIST
do
    #定义规则模板
    RULE="-A INPUT -s $i -m state --state NEW -m tcp -p tcp --dport 22 -j DROP"
    #看主机IP是否已经被拒绝过。避免重复写入拒绝规则。
    cat $IPTABLES | grep $RULE &>/dev/null

    if [ $? -ne 0 ];then
        #如果没有写过就引用模板添加规则
        sed -i "/lo/a $RULE" $IPTABLES #!!!用sed替换变量,需要用双引号!!! 这点一定要注意!!!
        #重启iptables,使规则生效
        service iptables restart
    else
        #如果已经写过规则,就打印一条提示信息。
        echo "deny rule existing..."
    fi
done

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

附:改变文件编码

iconv -f utf8 -t gb2312 denyip.sh -o win.denyip.sh    将编码格式从utf8更改为GB2312,并生成新文件

shell脚本之拒绝非法用户远程

原文:https://www.cnblogs.com/lingshu/p/8973902.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!