简介
ttyd 是一个轻量级的 Web 终端工具,可以通过浏览器直接访问服务器终端。
核心特性
- ✅ 浏览器访问 - 无需 SSH 客户端
- ✅ 实时交互 - WebSocket 实时通信
- ✅ 多会话 - 支持多个终端会话
- ✅ 轻量级 - 资源占用极低
- ✅ 跨平台 - 支持所有现代浏览器
- ✅ HTTPS 支持 - 安全加密传输
部署方式
方案一:Docker 部署(不推荐)
1 2 3 4 5
| docker run -d \ --name ttyd \ --restart=always \ -p 127.0.0.1:7681:7681 \ tsl0922/ttyd:latest
|
问题: Docker 容器内只能看到容器内进程,无法管理宿主机。
方案二:宿主机部署(推荐)
1. 下载安装
1 2 3 4 5 6 7
| wget https://github.com/tsl0922/ttyd/releases/download/1.7.7/ttyd.x86_64 -O /usr/local/bin/ttyd chmod +x /usr/local/bin/ttyd
ttyd --version
|
2. 创建 Systemd 服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| cat > /etc/systemd/system/ttyd.service << EOF [Unit] Description=ttyd - Web Terminal After=network.target
[Service] Type=simple ExecStart=/usr/local/bin/ttyd -p 7681 -W /bin/bash Restart=always RestartSec=3 User=root Environment=HOME=/root
[Install] WantedBy=multi-user.target EOF
systemctl daemon-reload systemctl enable ttyd systemctl start ttyd
|
3. 参数说明
| 参数 |
说明 |
-p 7681 |
监听端口 |
-W |
启用写入模式(可执行命令) |
/bin/bash |
使用的 Shell |
Nginx 反向代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| location /terminal/ { auth_basic "Web Terminal - Authentication Required"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://127.0.0.1:7681/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 86400s; proxy_send_timeout 86400s; }
|
基本认证配置
1. 安装 htpasswd 工具
1
| apt-get install -y apache2-utils
|
2. 创建密码文件
1 2 3 4 5 6 7
| PASSWORD=$(openssl rand -base64 12) htpasswd -bc /etc/nginx/.htpasswd 你的用户名 $PASSWORD echo "密码: $PASSWORD"
htpasswd -bc /etc/nginx/.htpasswd 你的用户名 你的密码
|
3. 重启 Nginx
1
| nginx -t && systemctl reload nginx
|
访问方式
- 访问地址: https://你的域名/terminal/
- 用户名: 你设置的用户名
- 密码: 你设置的密码
使用场景
远程运维
教学演示
应急访问
⚠️ 安全警告
重要安全提示
Web 终端直接暴露服务器操作权限,存在极高安全风险!
安全建议
1. 强密码
1 2
| openssl rand -base64 16
|
2. 限制访问 IP
1 2 3 4 5
| location /terminal/ { allow 你的IP; deny all; }
|
3. 定期更换密码
1 2 3
| htpasswd -bc /etc/nginx/.htpasswd 你的用户名 新密码 systemctl reload nginx
|
4. 监控访问日志
1 2
| tail -f /var/log/nginx/access.log | grep terminal
|
常见问题
Q: execvp failed: Permission denied?
A: 添加 -W 参数启用写入模式:
1
| ExecStart=/usr/local/bin/ttyd -p 7681 -W /bin/bash
|
Q: 终端无法连接?
A:
- 检查服务状态:
systemctl status ttyd
- 检查端口占用:
netstat -tlnp | grep 7681
- 查看 Nginx 日志:
tail -f /var/log/nginx/error.log
Q: 认证失败?
A:
- 检查密码文件:
cat /etc/nginx/.htpasswd
- 重新生成密码:
htpasswd -bc /etc/nginx/.htpasswd 用户名 密码
- 重启 Nginx:
systemctl reload nginx
服务管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| systemctl start ttyd
systemctl stop ttyd
systemctl restart ttyd
systemctl status ttyd
journalctl -u ttyd -f
|
相关资源
安全清单
部署完成后请妥善保管登录凭据!
持续更新中…