ssh-configuration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSSH Configuration
SSH配置
Secure SSH server and client configuration for production environments, including key management, hardened sshd settings, bastion host architecture, tunneling, and multiplexing.
面向生产环境的安全SSH服务器与客户端配置,包括密钥管理、强化sshd设置、堡垒机架构、隧道及多路复用。
When to Use
适用场景
- Setting up secure remote access to Linux or Unix servers
- Hardening SSH daemon configuration to meet compliance requirements
- Configuring bastion / jump hosts for private network access
- Creating SSH tunnels for secure port forwarding
- Managing SSH keys for teams or automated deployments
- Troubleshooting connection, authentication, or performance issues
- 为Linux或Unix服务器搭建安全远程访问
- 强化SSH守护进程配置以满足合规要求
- 配置堡垒机/跳转主机以实现私有网络访问
- 创建SSH隧道以实现安全端口转发
- 为团队或自动化部署管理SSH密钥
- 排查连接、认证或性能相关问题
Prerequisites
前置条件
- OpenSSH client installed locally (to verify)
ssh -V - OpenSSH server installed on target ()
sshd - Root or sudo access on the server for sshd_config changes
- Firewall rules allowing TCP port 22 (or custom SSH port)
- 本地已安装OpenSSH客户端(执行验证)
ssh -V - 目标服务器已安装OpenSSH服务器()
sshd - 拥有服务器的Root或sudo权限以修改sshd_config
- 防火墙规则允许TCP端口22(或自定义SSH端口)
Key Generation and Management
密钥生成与管理
bash
undefinedbash
undefinedGenerate an Ed25519 key (recommended -- fast, secure, short)
生成Ed25519密钥(推荐——快速、安全、长度短)
ssh-keygen -t ed25519 -C "jane@example.com" -f ~/.ssh/id_ed25519
ssh-keygen -t ed25519 -C "jane@example.com" -f ~/.ssh/id_ed25519
Generate an RSA 4096-bit key (for legacy compatibility)
生成RSA 4096位密钥(用于兼容旧系统)
ssh-keygen -t rsa -b 4096 -C "jane@example.com" -f ~/.ssh/id_rsa_legacy
ssh-keygen -t rsa -b 4096 -C "jane@example.com" -f ~/.ssh/id_rsa_legacy
Generate a key with a custom comment and no passphrase (CI/CD use only)
生成带自定义注释且无密码的密钥(仅用于CI/CD场景)
ssh-keygen -t ed25519 -C "ci-deploy-key" -f ~/.ssh/ci_deploy -N ""
ssh-keygen -t ed25519 -C "ci-deploy-key" -f ~/.ssh/ci_deploy -N ""
Copy public key to a remote server
将公钥复制到远程服务器
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server
Manually append a public key (when ssh-copy-id is unavailable)
手动追加公钥(当ssh-copy-id不可用时)
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
List fingerprints of keys on the agent
列出代理中的密钥指纹
ssh-add -l
ssh-add -l
Start the SSH agent and add a key
启动SSH代理并添加密钥
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
Add a key with a lifetime (auto-removed after 8 hours)
添加带有效期的密钥(8小时后自动移除)
ssh-add -t 28800 ~/.ssh/id_ed25519
ssh-add -t 28800 ~/.ssh/id_ed25519
Remove all keys from the agent
移除代理中的所有密钥
ssh-add -D
ssh-add -D
Convert an OpenSSH key to PEM format (for tools that need it)
将OpenSSH密钥转换为PEM格式(供需要该格式的工具使用)
ssh-keygen -p -m PEM -f ~/.ssh/id_rsa_legacy
ssh-keygen -p -m PEM -f ~/.ssh/id_rsa_legacy
Show the public key fingerprint (SHA256)
显示公钥指纹(SHA256格式)
ssh-keygen -lf ~/.ssh/id_ed25519.pub
ssh-keygen -lf ~/.ssh/id_ed25519.pub
Rotate a key: generate new, deploy, then revoke old
密钥轮换:生成新密钥,部署后撤销旧密钥
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_new -C "jane@example.com rotated $(date +%Y-%m)"
ssh-copy-id -i ~/.ssh/id_ed25519_new.pub user@server
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_new -C "jane@example.com rotated $(date +%Y-%m)"
ssh-copy-id -i ~/.ssh/id_ed25519_new.pub user@server
After verifying the new key works, remove the old public key from authorized_keys on the server
验证新密钥可用后,从服务器的authorized_keys中移除旧公钥
undefinedundefinedSSH Client Configuration (~/.ssh/config)
SSH客户端配置(~/.ssh/config)
text
undefinedtext
undefinedGlobal defaults applied to all hosts
应用于所有主机的全局默认设置
Host *
AddKeysToAgent yes
IdentitiesOnly yes
ServerAliveInterval 60
ServerAliveCountMax 3
TCPKeepAlive yes
Compression yes
Host *
AddKeysToAgent yes
IdentitiesOnly yes
ServerAliveInterval 60
ServerAliveCountMax 3
TCPKeepAlive yes
Compression yes
Production servers via bastion
通过堡垒机访问生产服务器
Host bastion
HostName bastion.example.com
User ops
IdentityFile ~/.ssh/id_ed25519
Port 22
Host prod-web-*
User deploy
IdentityFile ~/.ssh/id_ed25519
ProxyJump bastion
Port 22
Host prod-web-1
HostName 10.0.1.10
Host prod-web-2
HostName 10.0.1.11
Host bastion
HostName bastion.example.com
User ops
IdentityFile ~/.ssh/id_ed25519
Port 22
Host prod-web-*
User deploy
IdentityFile ~/.ssh/id_ed25519
ProxyJump bastion
Port 22
Host prod-web-1
HostName 10.0.1.10
Host prod-web-2
HostName 10.0.1.11
Staging accessed directly
直接访问预发布环境
Host staging
HostName staging.example.com
User deploy
IdentityFile ~/.ssh/id_ed25519_staging
Host staging
HostName staging.example.com
User deploy
IdentityFile ~/.ssh/id_ed25519_staging
Database tunnel through bastion
通过堡垒机建立数据库隧道
Host db-tunnel
HostName 10.0.2.50
User dba
ProxyJump bastion
LocalForward 5432 localhost:5432
Host db-tunnel
HostName 10.0.2.50
User dba
ProxyJump bastion
LocalForward 5432 localhost:5432
GitHub deploy key
GitHub部署密钥
Host github-deploy
HostName github.com
User git
IdentityFile ~/.ssh/github_deploy_key
IdentitiesOnly yes
Host github-deploy
HostName github.com
User git
IdentityFile ~/.ssh/github_deploy_key
IdentitiesOnly yes
Connection multiplexing for faster repeated connections
连接多路复用,加快重复连接速度
Host fast-*
ControlMaster auto
ControlPath ~/.ssh/sockets/%r@%h-%p
ControlPersist 600
```bashHost fast-*
ControlMaster auto
ControlPath ~/.ssh/sockets/%r@%h-%p
ControlPersist 600
```bashCreate the sockets directory for multiplexing
创建多路复用所需的sockets目录
mkdir -p ~/.ssh/sockets
chmod 700 ~/.ssh/sockets
undefinedmkdir -p ~/.ssh/sockets
chmod 700 ~/.ssh/sockets
undefinedHardened Server Configuration (/etc/ssh/sshd_config)
强化版服务器配置(/etc/ssh/sshd_config)
bash
undefinedbash
undefined/etc/ssh/sshd_config -- hardened configuration
/etc/ssh/sshd_config -- 强化配置
-----------------------------------------------
-----------------------------------------------
Listen on a non-default port (obscurity, not security -- combine with firewall)
监听非默认端口(仅作隐藏,非安全措施——需配合防火墙使用)
Port 22
Port 22
Protocol and key exchange
协议与密钥交换
Protocol 2
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group16-sha512
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
Protocol 2
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group16-sha512
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
Authentication
认证设置
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
MaxAuthTries 3
MaxSessions 5
LoginGraceTime 30
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
MaxAuthTries 3
MaxSessions 5
LoginGraceTime 30
Restrict users and groups
限制用户与用户组
AllowGroups ssh-users ops-team
AllowGroups ssh-users ops-team
AllowUsers deploy admin
AllowUsers deploy admin
Disable unused authentication methods
禁用未使用的认证方式
ChallengeResponseAuthentication no
KerberosAuthentication no
GSSAPIAuthentication no
ChallengeResponseAuthentication no
KerberosAuthentication no
GSSAPIAuthentication no
Forwarding controls
转发控制
AllowTcpForwarding yes
AllowAgentForwarding no
X11Forwarding no
PermitTunnel no
AllowTcpForwarding yes
AllowAgentForwarding no
X11Forwarding no
PermitTunnel no
Security hardening
安全强化
ClientAliveInterval 300
ClientAliveCountMax 2
UsePAM yes
UseDNS no
PermitEmptyPasswords no
PermitUserEnvironment no
ClientAliveInterval 300
ClientAliveCountMax 2
UsePAM yes
UseDNS no
PermitEmptyPasswords no
PermitUserEnvironment no
Logging
日志设置
SyslogFacility AUTH
LogLevel VERBOSE
SyslogFacility AUTH
LogLevel VERBOSE
SFTP subsystem
SFTP子系统
Subsystem sftp /usr/lib/openssh/sftp-server -f AUTH -l INFO
Subsystem sftp /usr/lib/openssh/sftp-server -f AUTH -l INFO
Match block: restrict deploy user to SFTP only
Match块:限制deploy用户仅能使用SFTP
Match User sftponly
ForceCommand internal-sftp
ChrootDirectory /home/%u
AllowTcpForwarding no
AllowAgentForwarding no
X11Forwarding no
```bashMatch User sftponly
ForceCommand internal-sftp
ChrootDirectory /home/%u
AllowTcpForwarding no
AllowAgentForwarding no
X11Forwarding no
```bashValidate configuration before restarting
重启前验证配置有效性
sshd -t
sshd -t
Restart sshd to apply changes
重启sshd以应用更改
systemctl restart sshd
systemctl restart sshd
Always keep an existing session open while testing
测试时请保持现有会话打开
Open a NEW terminal to verify you can still connect before closing the old one
在关闭旧会话前,打开新终端验证仍能连接
undefinedundefinedBastion Host Setup
堡垒机搭建
bash
undefinedbash
undefinedOn the bastion server, restrict forwarding to internal subnets only
在堡垒机上,仅允许转发到内部子网
/etc/ssh/sshd_config addition on bastion:
堡垒机的/etc/ssh/sshd_config新增配置:
AllowTcpForwarding yes
PermitOpen 10.0.0.0/8:22 10.0.0.0/8:5432
AllowTcpForwarding yes
PermitOpen 10.0.0.0/8:22 10.0.0.0/8:5432
Disable shell access for jump-only users
为仅用于跳转的用户禁用shell访问
Match User jump-user
PermitTTY no
ForceCommand /usr/sbin/nologin
AllowTcpForwarding yes
Match User jump-user
PermitTTY no
ForceCommand /usr/sbin/nologin
AllowTcpForwarding yes
Connect through the bastion from a client in one command
通过堡垒机连接的单条命令
ssh -J ops@bastion.example.com deploy@10.0.1.10
ssh -J ops@bastion.example.com deploy@10.0.1.10
Equivalent using ProxyCommand (older SSH versions)
等效于使用ProxyCommand(适用于旧版SSH)
ssh -o ProxyCommand="ssh -W %h:%p ops@bastion.example.com" deploy@10.0.1.10
ssh -o ProxyCommand="ssh -W %h:%p ops@bastion.example.com" deploy@10.0.1.10
Multi-hop: client -> bastion -> app-server -> db-server
多跳连接:客户端 -> 堡垒机 -> 应用服务器 -> 数据库服务器
ssh -J ops@bastion,deploy@10.0.1.10 dba@10.0.2.50
undefinedssh -J ops@bastion,deploy@10.0.1.10 dba@10.0.2.50
undefinedSSH Tunneling
SSH隧道
bash
undefinedbash
undefinedLocal port forward: access remote service on localhost
本地端口转发:在本地访问远程服务
Access remote PostgreSQL (10.0.2.50:5432) via bastion at localhost:5432
通过堡垒机在本地5432端口访问远程PostgreSQL(10.0.2.50:5432)
ssh -L 5432:10.0.2.50:5432 ops@bastion.example.com -N
ssh -L 5432:10.0.2.50:5432 ops@bastion.example.com -N
Remote port forward: expose local service to the remote network
远程端口转发:将本地服务暴露到远程网络
Make local dev server (localhost:3000) available on server port 8080
让本地开发服务器(localhost:3000)在服务器的8080端口可用
ssh -R 8080:localhost:3000 user@server -N
ssh -R 8080:localhost:3000 user@server -N
Dynamic SOCKS proxy: route all traffic through the server
动态SOCKS代理:将所有流量通过服务器路由
ssh -D 1080 user@server -N
ssh -D 1080 user@server -N
Then configure browser or apps to use SOCKS5 proxy at localhost:1080
然后配置浏览器或应用使用localhost:1080的SOCKS5代理
Tunnel with a background process
在后台运行隧道
ssh -fN -L 5432:10.0.2.50:5432 ops@bastion.example.com
ssh -fN -L 5432:10.0.2.50:5432 ops@bastion.example.com
Find and kill the tunnel later
后续查找并终止隧道
ps aux | grep "ssh -fN" | grep -v grep
kill <pid>
ps aux | grep "ssh -fN" | grep -v grep
kill <pid>
Autossh for persistent tunnels (auto-reconnects)
使用Autossh建立持久隧道(自动重连)
autossh -M 0 -f -N -L 5432:10.0.2.50:5432 ops@bastion.example.com
-o "ServerAliveInterval=30" -o "ServerAliveCountMax=3"
-o "ServerAliveInterval=30" -o "ServerAliveCountMax=3"
undefinedautossh -M 0 -f -N -L 5432:10.0.2.50:5432 ops@bastion.example.com
-o "ServerAliveInterval=30" -o "ServerAliveCountMax=3"
-o "ServerAliveInterval=30" -o "ServerAliveCountMax=3"
undefinedAgent Forwarding (Use with Caution)
代理转发(谨慎使用)
bash
undefinedbash
undefinedEnable agent forwarding for a single connection
为单次连接启用代理转发
ssh -A user@bastion
ssh -A user@bastion
From the bastion, your local keys are available to authenticate further
在堡垒机上,你的本地密钥可用于进一步认证
ssh deploy@10.0.1.10 # Uses your local key via the agent
ssh deploy@10.0.1.10 # 通过代理使用本地密钥
SECURITY WARNING: Agent forwarding exposes your keys to anyone with root
安全警告:代理转发会将你的密钥暴露给中间主机的Root权限持有者
on the intermediate host. Prefer ProxyJump instead.
优先使用ProxyJump替代
Safer alternative: ProxyJump does not expose the agent
更安全的替代方案:ProxyJump不会暴露代理
ssh -J ops@bastion deploy@10.0.1.10
undefinedssh -J ops@bastion deploy@10.0.1.10
undefinedSSH Key Restrictions in authorized_keys
authorized_keys中的SSH密钥限制
text
undefinedtext
undefinedRestrict a key to a specific command only (backup key)
限制密钥仅能执行特定命令(备份密钥)
command="/usr/local/bin/run-backup.sh",no-port-forwarding,no-X11-forwarding,no-agent-forwarding ssh-ed25519 AAAA... backup@example.com
command="/usr/local/bin/run-backup.sh",no-port-forwarding,no-X11-forwarding,no-agent-forwarding ssh-ed25519 AAAA... backup@example.com
Restrict a key to specific source IPs
限制密钥仅能从特定源IP访问
from="10.0.0.0/24,192.168.1.0/24" ssh-ed25519 AAAA... admin@example.com
from="10.0.0.0/24,192.168.1.0/24" ssh-ed25519 AAAA... admin@example.com
Read-only SFTP key with chroot
只读SFTP密钥并启用chroot
command="internal-sftp",no-port-forwarding,no-pty ssh-ed25519 AAAA... sftp-upload@example.com
undefinedcommand="internal-sftp",no-port-forwarding,no-pty ssh-ed25519 AAAA... sftp-upload@example.com
undefinedTroubleshooting
故障排查
| Symptom | Diagnostic Command | Common Fix |
|---|---|---|
| Connection refused | | Ensure sshd is running; check firewall rules |
| Permission denied (publickey) | | Verify key is in authorized_keys, permissions 600/700 |
| Host key verification failed | | Remove stale host key; verify server identity |
| Connection timeout | | Check network path, security groups, NACLs |
| Slow SSH login | Check | Set |
| Broken pipe / dropped sessions | Add | Configure keepalive on both client and server |
| Agent forwarding not working | | Ensure |
| Tunnel port already in use | | Kill existing tunnel or use a different local port |
| 症状 | 诊断命令 | 常见修复方案 |
|---|---|---|
| 连接被拒绝 | 在服务器执行 | 确保sshd正在运行;检查防火墙规则 |
| 权限拒绝(publickey) | | 验证密钥已添加到authorized_keys,权限设置为600/700 |
| 主机密钥验证失败 | | 移除过期主机密钥;验证服务器身份 |
| 连接超时 | | 检查网络路径、安全组、网络访问控制列表(NACL) |
| SSH登录缓慢 | 检查sshd_config中的 | 设置 |
| 管道破裂/会话断开 | 在配置中添加 | 在客户端和服务器都配置保活机制 |
| 代理转发无法工作 | 在堡垒机执行 | 确保使用了 |
| 隧道端口已被占用 | | 终止现有隧道或使用其他本地端口 |
Related Skills
相关技能
- -- General Linux system administration
linux-administration - -- Managing the users who connect via SSH
user-management - -- Managing sshd as a systemd service
systemd-services - -- Network tuning for SSH performance
performance-tuning
- —— 通用Linux系统管理
linux-administration - —— 管理通过SSH连接的用户
user-management - —— 将sshd作为systemd服务管理
systemd-services - —— SSH性能的网络调优
performance-tuning