SSH 完全配置指南
本文整合了 SSH 的常用配置,包括密钥生成、免密登录和跳板机代理。
密钥生成
生成 RSA 密钥对
ssh-keygen -t rsa -C "your-email@example.com"
生成后的文件:
- 私钥:
~/.ssh/id_rsa - 公钥:
~/.ssh/id_rsa.pub
生成 Ed25519 密钥(推荐)
Ed25519 更安全、更快:
ssh-keygen -t ed25519 -C "your-email@example.com"
免密登录配置
方法一:ssh-copy-id
ssh-copy-id user@remote-host
方法二:手动复制公钥
# 查看公钥
cat ~/.ssh/id_rsa.pub
# 复制到远程服务器的 ~/.ssh/authorized_keys
权限设置
SSH 对权限有严格要求,权限过于宽松会导致认证失败:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*
| 文件/目录 | 推荐权限 |
|---|---|
~/.ssh/ | 700 |
~/.ssh/id_rsa | 600 |
~/.ssh/id_rsa.pub | 644 |
~/.ssh/authorized_keys | 600 |
~/.ssh/config | 600 |
SSH 配置文件
~/.ssh/config 可以简化 SSH 连接命令。
基本配置
Host myserver
HostName 192.168.1.100
User admin
Port 22
IdentityFile ~/.ssh/id_rsa
使用:
# 不需要记 IP 和用户名
ssh myserver
多个服务器配置
# 开发服务器
Host dev
HostName dev.example.com
User developer
IdentityFile ~/.ssh/id_rsa_dev
# 生产服务器
Host prod
HostName prod.example.com
User admin
IdentityFile ~/.ssh/id_rsa_prod
Port 2222
跳板机配置
场景
需要通过跳板机(堡垒机)访问内网服务器。
本地 → 跳板机(Jump Host) → 目标服务器
ProxyCommand 配置
在 ~/.ssh/config 中:
# 跳板机配置
Host jump
HostName jump.example.com
User jumpuser
IdentityFile ~/.ssh/id_rsa
# 内网服务器(通过跳板机)
Host internal
HostName 10.0.0.100
User admin
IdentityFile ~/.ssh/id_rsa
ProxyCommand ssh -q -W %h:%p jump
使用:
# 自动通过 jump 跳转到 internal
ssh internal
ProxyJump(更简洁)
OpenSSH 7.3+ 支持更简洁的语法:
Host internal
HostName 10.0.0.100
User admin
ProxyJump jump
参数说明
| 参数 | 说明 |
|---|---|
-q | 静默模式,不输出警告 |
-W %h:%p | 转发 stdin/stdout 到目标主机和端口 |
%h | 目标主机名 |
%p | 目标端口 |
多级跳转
Host target
HostName 10.0.0.200
User admin
ProxyJump jump1,jump2
常见问题
sign_and_send_pubkey: signing failed
通常是权限问题,检查 ~/.ssh 目录权限:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*
连接超时
添加 Keep Alive 设置:
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
首次连接确认
跳过主机指纹确认(仅限受信任环境):
Host *
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
实用配置示例
# 全局设置
Host *
ServerAliveInterval 60
AddKeysToAgent yes
# 跳板机
Host bastion
HostName bastion.example.com
User ops
IdentityFile ~/.ssh/id_ed25519
# 内网开发服务器
Host dev-*
User developer
ProxyJump bastion
Host dev-web
HostName 10.0.1.10
Host dev-db
HostName 10.0.1.20
# GitHub
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/github_key