实用脚本能自动限制SSH登录吗?

wen 实用脚本 3

本文目录导读:

实用脚本能自动限制SSH登录吗?

  1. 基于 fail2ban 的自动封禁脚本
  2. 自定义 IP 白名单/黑名单脚本
  3. 基于时间窗口的自动限制脚本
  4. 简化版一键限制脚本
  5. 使用建议

是的,实用脚本完全可以自动限制SSH登录,常用的方法包括:

基于 fail2ban 的自动封禁脚本

#!/bin/bash
# fail2ban 自动安装和配置脚本
# 安装 fail2ban
sudo apt-get update && sudo apt-get install -y fail2ban
# 配置 SSH 保护
cat > /etc/fail2ban/jail.local << 'EOF'
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
EOF
# 重启服务
sudo systemctl restart fail2ban
sudo systemctl enable fail2ban

自定义 IP 白名单/黑名单脚本

#!/bin/bash
# ssh_ip_restrict.sh - 自动限制SSH登录IP
ALLOWED_IPS=("192.168.1.0/24" "10.0.0.0/8")
BLOCKED_IPS=()
# 设置防火墙规则
setup_firewall() {
    # 清除现有规则
    sudo iptables -F INPUT
    # 允许已建立的连接
    sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    # 允许本地回环
    sudo iptables -A INPUT -i lo -j ACCEPT
    # 只允许特定IP访问SSH
    for ip in "${ALLOWED_IPS[@]}"; do
        sudo iptables -A INPUT -p tcp --dport 22 -s "$ip" -j ACCEPT
    done
    # 拒绝其他IP访问SSH
    sudo iptables -A INPUT -p tcp --dport 22 -j DROP
}
# 自动检测异常登录
detect_bruteforce() {
    tail -f /var/log/auth.log | while read line; do
        if echo "$line" | grep -q "Failed password"; then
            ip=$(echo "$line" | grep -oP 'from \K[\d.]+')
            count=$(grep -c "$ip" /var/log/auth.log)
            if [ "$count" -gt 5 ]; then
                echo "攻击检测: $ip 失败登录 $count 次"
                sudo iptables -A INPUT -s "$ip" -j DROP
                echo "$(date) - 封禁IP: $ip" >> /var/log/ssh_ban.log
            fi
        fi
    done
}
# 主函数
main() {
    case "$1" in
        start)
            setup_firewall
            detect_bruteforce &
            echo "SSH限制已启动"
            ;;
        stop)
            sudo iptables -F INPUT
            echo "SSH限制已停止"
            ;;
        status)
            sudo iptables -L INPUT -n --line-numbers
            ;;
        add_ip)
            sudo iptables -I INPUT -p tcp --dport 22 -s "$2" -j ACCEPT
            echo "已添加IP: $2"
            ;;
        *)
            echo "用法: $0 {start|stop|status|add_ip <IP>}"
            ;;
    esac
}
main "$@"

基于时间窗口的自动限制脚本

#!/bin/bash
# auto_ssh_limit.sh
LOG_FILE="/var/log/auth.log"
BAN_LOG="/var/log/ssh_banned.log"
BAN_DURATION=3600  # 封禁时长(秒)
MAX_ATTEMPTS=5     # 最大尝试次数
WINDOW=600         # 时间窗口(秒)
# 检查并封禁异常IP
check_and_ban() {
    # 获取最近失败的IP(窗口时间内)
    recent_ips=$(grep "Failed password" "$LOG_FILE" | \
                 awk -v window="$WINDOW" '{
                     time=strftime("%s", systime())
                     if (time - $0_time <= window) print $NF
                 }' | sort | uniq -c | sort -rn)
    echo "$recent_ips" | while read count ip; do
        if [ "$count" -ge "$MAX_ATTEMPTS" ]; then
            # 检查是否已封禁
            if ! sudo iptables -C INPUT -s "$ip" -j DROP 2>/dev/null; then
                sudo iptables -A INPUT -s "$ip" -j DROP
                echo "$(date) - 自动封禁IP: $ip (尝试$count次)" >> "$BAN_LOG"
                # 定时解封
                (sleep $BAN_DURATION && \
                 sudo iptables -D INPUT -s "$ip" -j DROP && \
                 echo "$(date) - 解封IP: $ip" >> "$BAN_LOG") &
            fi
        fi
    done
}
# 监控日志文件
monitor_logs() {
    tail -Fn0 "$LOG_FILE" | while read line; do
        if echo "$line" | grep -q "Failed password"; then
            check_and_ban
        fi
    done
}
# 主循环
while true; do
    monitor_logs
    sleep 10
done

简化版一键限制脚本

#!/bin/bash
# 一键限制SSH登录
echo "配置SSH安全策略..."
# 1. 禁用root登录
sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
# 2. 限制最大尝试次数
echo "MaxAuthTries 3" >> /etc/ssh/sshd_config
# 3. 仅允许密钥登录
echo "PasswordAuthentication no" >> /etc/ssh/sshd_config
echo "PubkeyAuthentication yes" >> /etc/ssh/sshd_config
# 4. 重启SSH服务
systemctl restart sshd
# 5. 配置防火墙
ufw allow from 192.168.1.0/24 to any port 22
ufw deny 22
ufw --force enable
echo "SSH安全配置完成!"

使用建议

  1. 推荐使用 fail2ban:功能全面,配置灵活,适合生产环境
  2. 自定义脚本适合特定需求:如只允许特定IP段
  3. 测试环境先测试:避免把自己封禁
  4. 保留备用访问:如带外管理(iDRAC/iLO)
  5. 定期检查日志:确保脚本正常工作

你可以根据实际需求选择合适的脚本,或组合使用多种方法实现更强的安全防护。

抱歉,评论功能暂时关闭!