概述
本文档介绍如何通过 Cloudflare Zero Trust 创建的 SSH 隧道(主机名:ssh.example.org)进行远程服务器访问和端口转发。
前置条件
- 已安装
cloudflared客户端 - 已配置 Cloudflare Zero Trust SSH 隧道
- 主机名:
ssh.example.org
一、基本连接
1.1 密码认证连接
ssh -o ProxyCommand="cloudflared access ssh --hostname %h" [email protected]
1.2 生成 SSH 密钥对(推荐)
生成无密码保护的 ED25519 密钥:
ssh-keygen -t ed25519 -f ~/.ssh/example -N "" -C "[email protected]"
1.3 复制公钥到服务器
ssh-copy-id -i ~/.ssh/example.pub -o ProxyCommand="cloudflared access ssh --hostname %h" [email protected]
1.4 使用密钥登录
ssh -i ~/.ssh/example -o ProxyCommand="cloudflared access ssh --hostname %h" [email protected]
二、SSH 配置简化
2.1 编辑 SSH 配置文件
vim ~/.ssh/config
2.2 添加以下配置
Host example-root
Hostname ssh.example.org
User root
IdentityFile ~/.ssh/example
ProxyCommand cloudflared access ssh --hostname %h
2.3 简化连接
配置完成后,只需执行:
ssh example-root
三、端口转发
3.1 本地端口转发
将远程内网服务的端口转发到本地:
ssh -Nf -L :本地端口:远程内网IP:远程端口 example-root
示例:转发 Proxmox Web 界面
ssh -Nf -L :8006:192.168.1.9:8006 example-root
-N: 不执行远程命令,仅做端口转发-f: 后台运行-L: 本地端口转发
访问方式:https://localhost:8006
3.2 多端口同时转发
ssh -Nf -L :8006:192.168.1.9:8006 -L :8080:192.168.1.9:8080 example-root
3.3 远程端口转发
将本地端口暴露给远程网络:
ssh -Nf -R :8080:localhost:8080 example-root
3.4 动态端口转发(SOCKS 代理)
ssh -Nf -D :1080 example-root
四、管理转发连接
4.1 查看运行中的 SSH 转发进程
ps aux | grep "ssh.*8006"
4.2 停止指定端口转发
pkill -f "ssh.*8006"
或找到具体 PID 后终止:
kill <PID>
五、安全建议
5.1 禁用密码登录(仅允许密钥登录)
登录服务器后执行:
sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo systemctl restart sshd
5.2 保持连接活跃
防止 SSH 连接因超时断开:
ssh -o ServerAliveInterval=60 example-root
或在 ~/.ssh/config 中添加:
Host *
ServerAliveInterval 60
六、故障排查
6.1 连接失败
检查 cloudflared 是否正常运行:
cloudflared --version
6.2 端口被占用
检查本地端口是否被占用:
lsof -i :8006
6.3 调试模式
使用 -v 参数查看详细连接信息:
ssh -v example-root
七、常用命令速查
| 场景 | 命令 |
|---|---|
| 基本连接 | ssh example-root |
| 本地端口转发 | ssh -Nf -L :8006:192.168.1.9:8006 example-root |
| 多端口转发 | ssh -Nf -L :8006:192.168.1.9:8006 -L :8080:192.168.1.9:8080 example-root |
| SOCSK 代理 | ssh -Nf -D :1080 example-root |
| 查看转发进程 | ps aux | grep "ssh.*8006" |
| 停止转发 | pkill -f "ssh.*8006" |
| 详细调试 | ssh -v example-root |