Linux防ssh暴力破解的shell脚本

#!/bin/bash
# 添加到定时任务
# crontab -e
# 每1分钟检查一次
# */1 * * * * check-secure-ssh.sh &>/dev/null &
# by alone
# 服务器安全日志
secure_log_file='/var/log/secure'
# 防御文件(centos7及以下才有该文件以上版本可选择iptables)
defen_file='/etc/hosts.deny'
# ssh端口
ssh_port='22'
# 统计ip(数组)
attack_ip=(`tail -100 ${secure_log_file} | grep -i "failed" | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | awk '{ip[$1]++}END{for (i in ip) if(ip[i]>10)print i}'`)

if [[ -z ${attack_ip} ]];
then
    exit 0
fi

use_hosts_deny () {
    for ip_addrs in ${attack_ip[*]}
    do
        /usr/bin/grep -w $ip_addrs ${defen_file} &>/dev/null
        if [ $? -ne 0 ];
        then
            /usr/bin/echo "sshd:$ip_addrs:deny" >> ${defen_file}
        fi
    done
}

use_iptables () {
    for ip_addrs in ${attack_ip[*]}
    do
        /usr/sbin/iptables -nL | /usr/bin/grep -w $ip_addrs &>/dev/null
        if [[ $? -ne 0 ]]; then
        	/usr/sbin/iptables -I INPUT -s ${ip_addrs} -p tcp --dport ${ssh_port} -j DROP
        fi
    done
}

# 支持拉黑网段更安全
use_hosts_DenyIpSegment () {
    # 过滤ip生成网段加入IpCut数组
    IpCut=()
    for ip in ${attack_ip[*]}
    do
        IpCut+=(`printf "$ip\n" |sed -r 's/(^[0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)(.*)/\1\.\2\.*\.*/g'`)
    done

    for ip_addrs in ${IpCut[*]}
    do
        if [ `/usr/bin/grep -wc ${ip_addrs} ${defen_file}` -eq 0 ];
        then
            /usr/bin/echo "sshd:$ip_addrs:deny" >> ${defen_file}
        fi
    done
}

use_hosts_deny

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值