SSH调整默认端口,使用脚本配置ssh蜜罐,ssh蜜罐内开放的端口被探测时则封禁ip

1、ssh_guard.sh内容

#!/bin/bash

WHITELIST="/etc/ssh_guard_whitelist.txt"
LOG="/tmp/ssh_guard.log"
THRESHOLD=5         # 同一IP每10秒内超过5个连接行为即认为可疑
BAN_TIME=3600       # 封禁时间(秒)

declare -A ip_count
declare -A banned_ips

echo "[INFO] SSH Guard started at $(date)"

# 实时监听 TCP 22 端口的数据包
tcpdump -nn -l -i any tcp port 22 2>/dev/null | while read line; do
    ip=$(echo "$line" | awk '{print $3}' | cut -d. -f1-4)

    # 跳过空值
    [[ -z "$ip" ]] && continue

    # 跳过白名单
    if grep -q "^$ip$" "$WHITELIST"; then
        continue
    fi

    # 计数
    ip_count[$ip]=$(( ${ip_count[$ip]:-0} + 1 ))

    if [[ ${ip_count[$ip]} -gt $THRESHOLD ]]; then
        if [[ -z "${banned_ips[$ip]}" ]]; then
            echo "[BAN] $ip exceeded threshold - banning"
            iptables -A INPUT -s "$ip" -p tcp --dport 22 -j DROP
            echo "$(date): BANNED $ip" >> "$LOG"
            banned_ips[$ip]=$(date +%s)

            # 启动后台进程解除封禁
            (
                sleep $BAN_TIME
                iptables -D INPUT -s "$ip" -p tcp --dport 22 -j DROP
                unset banned_ips[$ip]
                echo "$(date): UNBANNED $ip" >> "$LOG"
            ) &
        fi
    fi

    # 每10秒清理旧数据
    (
        sleep 10
        ip_count[$ip]=0
    ) &
done

2、创建/tmp/ssh_guard.log、/etc/ssh_guard_whitelist.txt文件,白名单内每行一个ip

touch /tmp/ssh_guard.log
touch /etc/ssh_guard_whitelist.txt
chmod +w /tmp/ssh_guard.log

3、创建ssh_guard服务

vi /etc/systemd/system/ssh_guard.service


[Unit]
Description=SSH Port 22 Guard

[Service]
ExecStart=/root/ssh_guard.sh
Restart=always

[Install]
WantedBy=multi-user.target

查看状态

systemctl enabls ssh_guard
systemctl start ssh_guard
systemctl enable ssh_guard

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注