ReplaceKey/README.md
2026-03-05 19:40:30 +08:00

59 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# setup_server_security.sh
一键为 Ubuntu/Debian 服务器配置 SSH 公钥认证并部署 fail2ban 入侵防御。
## 功能
- 自动扫描同目录下的 `.pub` 公钥文件,支持单选或全选
- 通过指纹去重,避免重复写入 `authorized_keys`
- 安装并配置 fail2banSSH 登录失败 3 次永久封禁
- 任意步骤失败自动回滚至备份状态
- **不修改 `sshd_config`**,不禁用密码登录,不重启 sshd
## 系统要求
- Ubuntu 18.04+ 或 Debian 10+
- root 权限(`sudo`
## 使用方法
**1. 将脚本和公钥上传到同一目录**
```bash
scp setup_server_security.sh mykey.pub user@server:~/
```
**2. 登录服务器后执行**
```bash
sudo bash setup_server_security.sh
```
目录下只有一个 `.pub` 文件时自动选择;多个文件时交互选择。
## fail2ban 配置参数
| 参数 | 值 | 说明 |
|---|---|---|
| `bantime` | `-1` | 永久封禁 |
| `maxretry` | `3` | 最大失败次数 |
| `findtime` | `10m` | 计数窗口 |
| `ignoreip` | `127.0.0.1/8 ::1` | 本地回环不封禁 |
## 执行后验证
```bash
fail2ban-client get sshd bantime # 应输出 -1
fail2ban-client get sshd maxretry # 应输出 3
cat /root/.ssh/authorized_keys
```
## 备份与回滚
每次运行在 `/root/security_setup_backup_<时间戳>/` 自动备份:
- `/etc/ssh/sshd_config`
- `/etc/fail2ban/jail.local`
任意步骤出错时脚本自动从该目录恢复原始文件。备份目录不会自动删除,需手动清理。