本文整合了 SSH 的常用配置,包括密钥生成、免密登录和跳板机代理。

密钥生成

生成 RSA 密钥对

1
ssh-keygen -t rsa -C "[email protected]"

生成后的文件:

  • 私钥:~/.ssh/id_rsa
  • 公钥:~/.ssh/id_rsa.pub

生成 Ed25519 密钥(推荐)

Ed25519 更安全、更快:

1
ssh-keygen -t ed25519 -C "[email protected]"

免密登录配置

方法一:ssh-copy-id

1
ssh-copy-id user@remote-host

方法二:手动复制公钥

1
2
3
4
# 查看公钥
cat ~/.ssh/id_rsa.pub

# 复制到远程服务器的 ~/.ssh/authorized_keys

权限设置

SSH 对权限有严格要求,权限过于宽松会导致认证失败:

1
2
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 连接命令。

基本配置

1
2
3
4
5
Host myserver
HostName 192.168.1.100
User admin
Port 22
IdentityFile ~/.ssh/id_rsa

使用:

1
2
# 不需要记 IP 和用户名
ssh myserver

多个服务器配置

1
2
3
4
5
6
7
8
9
10
11
12
# 开发服务器
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

跳板机配置

场景

需要通过跳板机(堡垒机)访问内网服务器。

1
本地 → 跳板机(Jump Host) → 目标服务器

ProxyCommand 配置

~/.ssh/config 中:

1
2
3
4
5
6
7
8
9
10
11
12
# 跳板机配置
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

使用:

1
2
# 自动通过 jump 跳转到 internal
ssh internal

ProxyJump(更简洁)

OpenSSH 7.3+ 支持更简洁的语法:

1
2
3
4
Host internal
HostName 10.0.0.100
User admin
ProxyJump jump

参数说明

参数 说明
-q 静默模式,不输出警告
-W %h:%p 转发 stdin/stdout 到目标主机和端口
%h 目标主机名
%p 目标端口

多级跳转

1
2
3
4
Host target
HostName 10.0.0.200
User admin
ProxyJump jump1,jump2

常见问题

sign_and_send_pubkey: signing failed

通常是权限问题,检查 ~/.ssh 目录权限:

1
2
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*

连接超时

添加 Keep Alive 设置:

1
2
3
Host *
ServerAliveInterval 60
ServerAliveCountMax 3

首次连接确认

跳过主机指纹确认(仅限受信任环境):

1
2
3
Host *
StrictHostKeyChecking no
UserKnownHostsFile /dev/null

实用配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 全局设置
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

参考资料