彆著急,坐和放寬
使用社群帳號登入
SSH(Secure Shell)是远程管理 Linux/UNIX 系统的标准协议。通过合理配置 ~/.ssh/config 文件,开发者与运维人员可以显著提升工作效率、简化多主机管理,并增强连接的安全性。本文将系统介绍 SSH Config 的配置方法、问题排查技巧以及最佳实践建议。
SSH 客户端配置文件路径:
~/.ssh/config
推荐权限设置:
确保权限正确是 SSH 能成功读取配置并建立连接的前提条件。
| 参数 | 说明 |
|---|---|
Host | 本地定义的别名,用于简化连接命令 |
HostName | 远程主机的实际地址(IP或域名) |
User | 登录时使用的用户名 |
Port | SSH 服务端口,默认为 22 |
IdentityFile | 指定使用的私钥路径 |
连接示例:
通过 ssh prod 或 ssh dev 快速登录对应服务器。
当目标主机处于内网,需通过跳板机访问时:
ProxyJump 是 ProxyCommand 的简洁替代方案,推荐使用。
可能原因:
sshd排查方法:
排查步骤:
检查公钥是否添加至目标服务器:
~/.ssh/authorized_keys
确保权限设置正确:
authorized_keys,请在服务端修改配置:/etc/ssh/sshd_configauthorized_keys 的原因:检查方法:
使用 -vvv 参数可查看详细调试信息。
/etc/ssh/sshd_config):可结合 Fail2Ban 等工具防止暴力破解。
当目标主机无法被公网直接访问时,可通过 FRP 实现端口映射:
注意事项:
~/.ssh/authorized_keys 必须存在于 内网主机 上sshd 正常运行并监听对应端口配置 SSH Config 带来的好处包括:
建议:
ssh -vvv 快速定位连接问题通过规范化配置 SSH,运维与开发工作将变得更可靠、更安全、更高效。
chmod 600 ~/.ssh/config # 仅允许当前用户读写
chmod 700 ~/.ssh # 仅允许当前用户访问目录
Host myserver
HostName server.example.com
User myusername
Port 2222
IdentityFile ~/.ssh/my_key
ssh myserver
# 生产环境服务器
Host prod
HostName 192.168.1.100
User admin
IdentityFile ~/.ssh/prod_key
# 开发环境服务器
Host dev
HostName dev.example.com
User developer
IdentityFile ~/.ssh/dev_key
# 跳板机
Host jumpbox
HostName jump.example.com
User jumper
IdentityFile ~/.ssh/jump_key
# 内网服务器
Host internal-server
HostName 10.0.0.5
User internal
IdentityFile ~/.ssh/internal_key
ProxyJump jumpbox
Host *
PasswordAuthentication no
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
ServerAliveInterval 60
TCPKeepAlive yes
sudo systemctl status sshd
# 测试端口连通性
telnet server.example.com 22
# 或使用 nc
nc -zv server.example.com 22
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
ssh-keygen -y -f ~/.ssh/my_key
ssh-copy-id -i ~/.ssh/my_remote_key.pub username@remote_server_ip
cat ~/.ssh/my_remote_key.pub | ssh username@remote_server_ip \
"mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
AuthorizedKeysFile .ssh/my_keys # 相对路径
# 或
AuthorizedKeysFile /etc/ssh/my_keys/%u_keys # 绝对路径,%u表示用户名
sudo systemctl restart sshd
sshd -T | grep authorizedkeysfile
AuthorizedKeysFile .ssh/keys1 .ssh/keys2 /etc/global_keys
ssh -T HostAlias
ssh -vvv HostAlias
PermitRootLogin no
AllowUsers admin_user deploy_user
Host *
Compression yes
ControlMaster auto
ControlPath ~/.ssh/ssh_mux_%h_%p_%r
ControlPersist 4h
Host remote-via-frp
HostName frp-server.example.com
Port 6000 # 修改为你的 FRP 映射端口
User internal_user
IdentityFile ~/.ssh/internal_key