AdityaKumar41/serverguard-oss
GitHub: AdityaKumar41/serverguard-oss
一款基于 Python 的自主服务器安全守护进程,实时监控日志检测暴力破解等威胁,并利用 AI 提供威胁分析与告警。
Stars: 1 | Forks: 0

### 自主服务器守护者
**检测威胁。获取警报。自我改进。全天候保护您的服务器。**
[](https://github.com/serverguard-oss/serverguard/actions)
[](https://pypi.org/project/serverguard/)
[](https://python.org)
[](LICENSE)
[](SECURITY.md)
[安装](#install) · [设置](#quick-start) · [命令](#commands) · [AI 功能](#ai-features) · [通知](#notifications) · [安全](#security-architecture) · [贡献](#contributing)
ServerGuard 是一个**由 Python 驱动的自主服务器守护者** —— 单个 CLI 工具即可实时监控您的 Linux 服务器,检测 SSH 暴力破解攻击(以及其他威胁),向 Telegram/Discord/Slack/Email 发送即时警报,利用 AI 解释并分析每一次威胁的上下文,并在运行过程中悄无声息地根据经验优化自身的检测阈值。
60 秒即可完成设置。永久运行。
```
$ sgd --config ~/.serverguard/config.toml
2026-06-22T20:15:37 INFO Daemon started — watching 1 log source(s)
2026-06-22T20:15:37 WARNING [security.ssh_bruteforce] 203.0.113.10
→ 5 failed SSH attempts in 60s — ALERT SENT
→ Telegram: 🔴 SSH brute-force detected
📍 IP Location: Shanghai, China (Alibaba Cloud)
🤖 AI Analysis: Automated credential stuffing attack from known hosting
range. Recommend: ufw deny from 203.0.113.10 to any port 22
```
## 为什么选择 ServerGuard?
| | ServerGuard | fail2ban | 手动监控 |
|---|---|---|---|
| 一键设置 | ✅ `sg setup` | ❌ 配置复杂 | ❌ |
| AI 威胁摘要 | ✅ | ❌ | ❌ |
| 每个警报的 IP 地理定位 | ✅ | ❌ | ❌ |
| 自我改进的阈值 | ✅ | ❌ | ❌ |
| Telegram / Discord / Slack | ✅ | ❌ | ❌ |
| 防篡改审计日志 | ✅ | ❌ | ❌ |
| 向 AI 询问关于您服务器的问题 | ✅ `sg ask` | ❌ | ❌ |
| 热插拔 AI 提供商 | ✅ `sg model` | ❌ | ❌ |
| 强化的 systemd unit | ✅ | ⚠️ | ❌ |
## 安装
**一行命令:**
```
curl -fsSL https://raw.githubusercontent.com/serverguard-oss/serverguard/main/scripts/install.sh | bash
```
**或通过 pipx(推荐):**
```
pipx install serverguard
```
**或通过 pip:**
```
pip install serverguard
```
需要 Python 3.11+。适用于 Ubuntu、Debian、RHEL/CentOS、Fedora 和 macOS。
## 快速开始
### 第 1 步 — 运行设置向导
```
sg setup
```
向导将引导您完成:
1. **AI 模型提供商** — OpenAI、Anthropic、OpenRouter、Ollama(本地/免费)或跳过
2. **通知渠道** — Telegram、Discord、Slack、Webhook、Email(可添加多个)
3. **日志来源** — 从您的系统中自动检测(如 `/var/log/auth.log` 等)
4. **实例名称** — 您的服务器在警报中显示的名称
所有配置都会保存到 `~/.serverguard/config.toml`。API 密钥保存在 `~/.serverguard/.env` 中(绝不放在 TOML 中)。
### 第 2 步 — 启动守护进程
```
sgd --config ~/.serverguard/config.toml
```
### 第 3 步 — 检查状态
```
sg status --config ~/.serverguard/config.toml
sg events --config ~/.serverguard/config.toml
```
### 第 4 步 — 作为系统服务运行
```
sudo cp packaging/serverguard.service /etc/systemd/system/
sudo systemctl enable --now serverguard
```
## 命令
### 核心
| 命令 | 描述 |
|---|---|
| `sg setup` | 交互式设置向导(AI + 通知 + 日志源) |
| `sg status --config
` | 显示守护进程状态、配置和近期事件计数 |
| `sg events --config ` | 列出事件,按时间倒序排列,带有颜色编码的严重程度 |
| `sgd --config ` | 启动监控守护进程 |
| `sgd --config --replay` | 重放现有日志内容(用于测试/演示) |
### AI
| 命令 | 描述 |
|---|---|
| `sg ask --config "question"` | 向 AI 询问任何关于服务器安全的问题 |
| `sg model` | 交互式 AI 提供商切换器 |
| `sg model set openai gpt-4o` | 非交互式设置提供商 |
| `sg model set ollama llama3.2` | 切换到本地 Ollama(免费,无需 API 密钥) |
| `sg model list` | 列出所有支持的提供商和模型 |
### 安全
| 命令 | 描述 |
|---|---|
| `sg audit verify --config ` | 验证防篡改审计链的完整性 |
| `sg --version` | 打印版本号 |
## AI 功能
ServerGuard 在每一个层级都集成了 AI —— 这不是噱头,而是为了让服务器安全变得真正易于理解。
### 1. 即时威胁摘要
每一个安全事件都会获得由 AI 生成的通俗解释:
```
🤖 AI Analysis: Automated credential stuffing attack from known cloud
hosting range. No successful logins observed. Recommended action:
ufw deny from 203.0.113.10 to any port 22
```
### 2. IP 地理定位与信誉
每个攻击者 IP 都会自动进行信息 enrichment:
```
🌍 IP Location: Shanghai, China (Alibaba Cloud)
⚠️ Hosting provider (common bot origin)
```
### 3. 自学习循环
在积累了 10 个相同类型的事件后,ServerGuard 会:
- 使用 AI 分析模式
- 建议收紧检测阈值
- 将建议保存到 `~/.serverguard/data/learned_suggestions.json`
- 将其记录为 `learning.suggestion` 事件
### 4. AI 问答 (`sg ask`)
用自然语言询问有关您服务器安全历史的任何问题:
```
sg ask --config ~/.serverguard/config.toml "Am I under attack right now?"
sg ask --config ~/.serverguard/config.toml "Which IP has hit me the most?"
sg ask --config ~/.serverguard/config.toml "Should I block the 203.0.113.0/24 range?"
```
### 支持的 AI 提供商
| 提供商 | 模型 | 设置 |
|---|---|---|
| **OpenAI** | GPT-4o, GPT-4o-mini | `OPENAI_API_KEY` |
| **Anthropic** | Claude 3.5 Sonnet, Claude 3 Haiku | `ANTHROPIC_API_KEY` |
| **OpenRouter** | 200+ 模型(一个密钥) | `OPENROUTER_API_KEY` |
| **Ollama** | llama3.2, mistral, gemma3(本地,免费) | 无需设置 |
随时切换提供商而无需重启:`sg model set ollama llama3.2`
## 通知
在运行 `sg setup` 时进行配置,或者手动添加到 `config.toml` 中。
### Telegram(推荐)
在手机上即时获取警报。还支持 bot 命令(`/status`、`/events`、`/ask`)。
```
# 1. 创建 bot: 消息 @BotFather → /newbot → 复制 token
# 2. 设置 env vars (在 ~/.serverguard/.env 中):
SERVERGUARD_TELEGRAM_BOT_TOKEN=123456:ABC-DEF...
SERVERGUARD_TELEGRAM_CHAT_ID=-100123456789
```
```
# 在 config.toml 中:
[[notifiers]]
type = "telegram"
enabled = true
```
**Telegram 警报示例如下:**
```
🔴 ServerGuard Alert
Type: security.ssh_bruteforce
Severity: WARNING
Subject: 203.0.113.10
Time: 2026-06-22T20:15:37
5 failed SSH attempts from 203.0.113.10 within 60s
🤖 AI Analysis: Automated attack from cloud VPS...
🌍 IP Location: Shanghai, China (Alibaba Cloud)
```
### Discord
```
SERVERGUARD_DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
```
### Slack
```
SERVERGUARD_SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
```
### Email (SMTP)
```
SERVERGUARD_SMTP_HOST=smtp.gmail.com
SERVERGUARD_SMTP_PORT=587
SERVERGUARD_SMTP_USER=alerts@example.com
SERVERGUARD_SMTP_PASSWORD=your-app-password
SERVERGUARD_SMTP_TO=ops@example.com
```
### 自定义 Webhook(HMAC 签名)
```
SERVERGUARD_WEBHOOK_URL=https://your-service.com/hook
SERVERGUARD_WEBHOOK_SECRET=your-signing-secret # optional
```
## 检测器
| 检测器 | 状态 | 描述 |
|---|---|---|
| `ssh_bruteforce` | ✅ v0.0.1 | 滑动窗口 SSH 登录失败计数器 |
| `port_scan` | 🔜 v0.1.0 | 快速端口扫描检测 |
| `anomaly_baseline` | 🔜 v0.2.0 | AI 驱动的滚动异常评分 |
## 安全架构
ServerGuard 采用纵深防御策略。它像保护您的服务器一样激烈地保护自身。
| 层级 | 实现方式 |
|---|---|
| **输入过滤** | 所有日志行限制在 4 KiB 内,去除空字节,删除控制字符 |
| **速率限制** | 10,000 行/秒/来源 上限 — 防止因日志洪水导致 CPU/RAM 耗尽 |
| **防篡改审计** | SHA-256 哈希链 `audit_chain` 表 — 通过 `sg audit verify` 验证 |
| **配置权限** | 如果配置文件全局可读或数据目录全局可写,则发出警告 |
| **最小权限** | 专用的 `serverguard` 系统用户;对使用 root 权限运行发出强烈警告 |
| **强化的 systemd** | `NoNewPrivileges`、`ProtectSystem=strict`、syscall 白名单、内存限制 |
| **密钥仅存于环境** | 配置文件中绝不包含 API 密钥 |
| **零遥测** | 除了已配置的通知程序和您的 AI 提供商外,没有任何外部连接 |
| **最小依赖** | 极小的攻击面;所有依赖项均在 CI 中锁定并经过审计 |
## 配置参考
```
[serverguard]
instance_id = "prod-web-01"
data_dir = "~/.serverguard/data"
[security]
max_lines_per_second = 10000
[ai]
provider = "openai" # openai | anthropic | openrouter | ollama | disabled
model = "gpt-4o"
[[log_sources]]
name = "auth"
type = "ssh_auth"
path = "/var/log/auth.log"
[[detectors]]
name = "ssh_bruteforce"
enabled = true
source = "auth"
failed_attempt_threshold = 5
window_seconds = 60
[[notifiers]]
type = "telegram"
enabled = true
[[notifiers]]
type = "discord"
enabled = true
```
完整参考:[docs/configuration.md](docs/configuration.md)
## 路线图
| 版本 | 功能 |
|---|---|
| **v0.0.1** | SSH 暴力破解、AI 摘要 + 地理定位、Telegram/Discord/Slack/Email、设置向导、`sg ask`、自学习循环、防篡改审计、安全加固 |
| **v0.1.0** | 端口扫描检测器、日志轮转、网关 bot(通过 Telegram 使用 `/status`)、`sg gateway telegram` |
| **v0.2.0** | 自愈操作(通过 `ufw` / `iptables` 自动封禁)、AI 异常基线、`sg schedule` cron 任务 |
| **v0.3.0** | 多服务器仪表盘、插件系统、`sg learn` 自定义模式 |
| **v1.0.0** | 稳定的 API、Windows PTY 支持、企业级功能 |
## 开发
```
git clone https://github.com/serverguard-oss/serverguard
cd serverguard
make install-dev # creates .venv + installs all dev deps
make test # 44+ tests (unit + contract)
make lint # ruff check
make run-daemon # demo against shared fixture (detects brute-force)
make run-events # show events from the demo run
```
请参阅 [AGENTS.md](AGENTS.md) 获取完整的开发者指南:包括架构、贡献准则、资源占用阶梯、安全检查清单,以及添加检测器/通知程序/AI 提供商的分步指南。
## 许可证
[MIT](LICENSE) © 2026 ServerGuard 贡献者标签:AI辅助, AI风险缓解, Petitpotam, Python, Python安全, 无后门, 逆向工具, 防御暴力破解