ToolkitX
知识库工具箱

SSH 高级用法

SSH 密钥、端口转发、跳板机、配置优化

30min·高级

01. SSH 密钥——告别密码

每次 ssh 都输密码?又慢又不安全。用密钥对登录,既快又防暴力破解。说白了就是一对「锁和钥匙」——公钥(锁)放服务器上,私钥(钥匙)你自己拿着:
bash
ssh-keygen -t ed25519 -C "[email protected]"   # 生成密钥对(推荐 ed25519)
ssh-keygen -t rsa -b 4096 -C "[email protected]"  # 或者 RSA 4096 位

ssh-copy-id [email protected]    # 把公钥复制到服务器(一把梭)
# 手动方式:
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

ssh -i ~/.ssh/my_key [email protected]  # 指定私钥登录
ed25519 比 RSA 更快更短更安全,新机器推荐用它。

02. SSH Config——不用再记 IP

每次都打 ssh [email protected] -p 2222 太痛苦了。创建一个 ~/.ssh/config 文件,给服务器起个昵称,以后直接 ssh 昵称就行:
ssh_config
# ~/.ssh/config
Host my-server
HostName 192.168.1.100
User john
Port 2222
IdentityFile ~/.ssh/my_key

Host prod-web
HostName 10.0.1.50
User deploy
IdentityFile ~/.ssh/prod_key

# 使用:直接 ssh my-server 就行!

03. 端口转发——打通隧道

SSH 不只是登录用的,它还能当隧道用。端口转发说白了就是「借道 SSH 连接访问本来访问不到的服务」。 三种常见场景: - 本地转发:把远程服务器的端口「搬到」你本地来访问 - 远程转发:反过来,把你本地的端口暴露给远程 - 动态转发:把 SSH 当 SOCKS 代理用
bash
# 本地转发:把服务器上只监听 localhost:3306 的 MySQL 映射到你本地的 3306
ssh -L 3306:localhost:3306 user@server

# 远程转发:把你本地的 8080 端口暴露给远程服务器的 9090 端口的用户
ssh -R 9090:localhost:8080 user@server

# 动态转发(SOCKS 代理):浏览器设代理为 localhost:1080,走服务器上网
ssh -D 1080 user@server

04. 跳板机——中间人转发

生产环境的服务器往往不给直接连,你需要先连一台「跳板机」,再从跳板机跳到目标服务器。SSH 有几种办法解决这个问题:
bash
# 方法一:ProxyJump 一步到位(推荐,OpenSSH 7.3+)
ssh -J [email protected] [email protected]

# 方法二:SSH Config 配置 ProxyJump
Host target
HostName 10.0.1.100
User admin
ProxyJump bastion

Host bastion
HostName bastion.example.com
User jumpuser

# 方法三:ProxyCommand(老版本,兼容性好)
ssh -o ProxyCommand="ssh -W %h:%p bastion.com" target.com
ProxyJump 是跳板机的标准做法,配置一次以后直接 ssh target 就行,中间过程全透明。

知识测验

1/4正确 0

SSH 密钥对中,哪个可以公开?

下一节

日志分析与管理

下一节