结合 SSH 22 + 2222 备用端口 + 临时保护 + 长期守护 + 防火墙 的终极一行命令版本
✅ 功能说明
端口锁定:SSH 默认
22
端口不可被修改。防火墙允许:TCP 22 永远允许访问。
自动回滚:如果 SSH 异常,自动回滚最近备份。
30 分钟临时保护:从首次执行起的 30 分钟内特别保护,即便软件误改也会自动恢复。
长期守护:30 分钟后仍保持常规守护,保证长期 SSH 可靠。
开机自启:systemd 服务保证开机自动运行。
可直接复制执行的单行命令,包含 30 分钟临时保护 + 长期守护 + 22 端口锁定 + 防火墙允许 + 自动回滚,可以这样:
sudo bash -c "set +H; mkdir -p /root/ssh_protect_backups && cp /etc/ssh/sshd_config /root/ssh_protect_backups/sshd_config.bak_\$(date +%F_%H%M%S) && chattr +i /etc/ssh/sshd_config && nft add table inet sshprotect 2>/dev/null || true && nft add chain inet sshprotect input '{ type filter hook input priority 0 ; }' 2>/dev/null || true && nft add rule inet sshprotect input tcp dport 22 ct state new,established accept || ufw allow 22/tcp && \ echo '#!/bin/bash BACKUP_DIR=/root/ssh_protect_backups LOCK_FILE=/etc/ssh/sshd_config if [ ! -f /tmp/ssh_protect_end ]; then date -d \"+30 minutes\" +%s > /tmp/ssh_protect_end; fi CURRENT_TIME=\$(date +%s) if [ \$CURRENT_TIME -le \$(cat /tmp/ssh_protect_end) ]; then PROTECT_ACTIVE=1; else PROTECT_ACTIVE=0; fi if ! ss -tlnp | grep -q \":22.*sshd\"; then echo \"[SSH Monitor] sshd not running or port 22 missing, restoring backup...\"; chattr -i \$LOCK_FILE; cp \$BACKUP_DIR/sshd_config.bak_* \$LOCK_FILE; chattr +i \$LOCK_FILE; systemctl restart sshd; fi' > /usr/local/sbin/ssh_monitor.sh && chmod +x /usr/local/sbin/ssh_monitor.sh && \ echo '#!/bin/bash while true; do/usr/local/sbin/ssh_monitor.shsleep 60 done' > /usr/local/sbin/ssh_monitor_loop.sh && chmod +x /usr/local/sbin/ssh_monitor_loop.sh && \ echo '[Unit] Description=Enhanced SSH Monitor Service After=network.target [Service] Type=simple ExecStart=/usr/local/sbin/ssh_monitor_loop.sh Restart=always RestartSec=30 [Install] WantedBy=multi-user.target' > /etc/systemd/system/ssh-monitor.service && \ systemctl daemon-reload && systemctl enable --now ssh-monitor.service && systemctl restart sshd && echo '增强版 SSH 保护已启用,22 端口锁定、防火墙允许、30 分钟临时保护窗口+长期守护。'"