SSH 配置文件(~/.ssh/config)是管理 SSH 连接的重要工具,可以简化连接命令、提高工作效率并增强安全性。合理的配置能够大幅提升服务器管理的便捷性。
配置文件位置
- 用户级配置:
~/.ssh/config - 系统级配置:
/etc/ssh/ssh_config - 服务器配置:
/etc/ssh/sshd_config
常用配置选项
基本连接配置
bash# ~/.ssh/config Host production HostName prod.example.com User deploy Port 2222 IdentityFile ~/.ssh/id_rsa_prod Host staging HostName staging.example.com User deploy IdentityFile ~/.ssh/id_rsa_staging # 使用通配符配置多个服务器 Host *.internal User admin IdentityFile ~/.ssh/id_rsa_internal StrictHostKeyChecking no
高级连接选项
bashHost jump-server HostName jump.example.com User jumpuser # 连接超时设置 ConnectTimeout 10 # 保持连接活跃 ServerAliveInterval 60 ServerAliveCountMax 3 # 压缩传输 Compression yes # 使用特定密钥 IdentityFile ~/.ssh/id_rsa_jump
代理跳转配置
bash# 通过跳板机连接内网服务器 Host internal-db HostName db.internal User dbuser ProxyJump jump-server Host internal-app HostName app.internal User appuser ProxyJump jump-server
服务器安全配置(sshd_config)
基础安全设置
bash# /etc/ssh/sshd_config # 禁用 root 登录 PermitRootLogin no # 禁用密码认证 PasswordAuthentication no # 仅允许特定用户 AllowUsers user1 user2 # 禁用空密码 PermitEmptyPasswords no # 限制最大认证尝试次数 MaxAuthTries 3 # 登录超时 LoginGraceTime 60
网络安全设置
bash# 修改默认端口 Port 2222 # 仅监听特定地址 ListenAddress 192.168.1.100 # 禁用端口转发 AllowTcpForwarding no GatewayPorts no # 禁用 X11 转发 X11Forwarding no
性能优化设置
bash# 使用更快的加密算法 Ciphers aes256-gcm@openssh.com,chacha20-poly1305@openssh.com # 使用更快的密钥交换算法 KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256 # 使用更快的 MAC 算法 MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com # 启用压缩 Compression yes
日志和审计
bash# 详细日志 LogLevel VERBOSE # 记录登录信息 SyslogFacility AUTHPRIV # 启用 PAM UsePAM yes
配置文件最佳实践
1. 文件权限管理
bash# 设置正确的文件权限 chmod 700 ~/.ssh chmod 600 ~/.ssh/config chmod 600 ~/.ssh/id_rsa chmod 644 ~/.ssh/id_rsa.pub
2. 使用 Host 别名
bash# 简化连接命令 Host prod HostName production-server.example.com User deploy IdentityFile ~/.ssh/production_key # 使用: ssh prod 而不是: ssh deploy@production-server.example.com -i ~/.ssh/production_key
3. 环境特定配置
bash# 开发环境 Host dev-* User developer ForwardAgent yes # 生产环境 Host prod-* User deploy ForwardAgent no StrictHostKeyChecking yes
4. 多因素认证
bashHost critical-server HostName critical.example.com User admin # 使用多个认证方法 AuthenticationMethods publickey,keyboard-interactive
配置验证和测试
测试配置语法
bash# 测试用户配置 ssh -F ~/.ssh/config -T hostname # 测试服务器配置 sudo sshd -t
调试连接问题
bash# 详细调试信息 ssh -vvv user@hostname # 使用特定配置文件 ssh -F /path/to/config user@hostname
安全加固建议
- 定期更新:保持 SSH 软件最新版本
- 密钥管理:定期轮换 SSH 密钥
- 访问控制:使用防火墙限制 SSH 访问
- 监控日志:定期审查 SSH 登录日志
- 禁用不安全功能:关闭不需要的 SSH 功能
合理的 SSH 配置能够显著提高服务器管理的效率和安全性,是每个系统管理员必备的技能。