#!/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
Linux防ssh暴力破解的shell脚本
于 2022-11-19 20:33:35 首次发布