SSH 配置仅密钥登录
1. 本地生成密钥对
1 2 3
| ssh-keygen -t ed25519 -C "备注信息"
|
生成文件:~/.ssh/id_ed25519(私钥,权限 600,严禁泄露)、~/.ssh/id_ed25519.pub(公钥,需上传服务器)
2. 公钥上传到服务器
自动上传(推荐)
1
| ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 端口 用户名@服务器IP
|
手动上传(备用)
1 2 3 4 5 6
| mkdir -p ~/.ssh chmod 700 ~/.ssh echo "本地公钥内容" >> ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys chown -R 用户名:用户名 ~/.ssh
|
3. 服务器禁用密码登录
编辑 SSH 配置文件
1
| sudo vi /etc/ssh/sshd_config
|
关键配置项
1 2 3 4 5 6 7 8
| PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no
PermitRootLogin without-password
|
生效配置
1 2 3 4 5 6
| sudo sshd -t
sudo systemctl restart sshd
|
4. 验证密码登录是否禁用
1 2
| ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no -p 端口 用户名@服务器IP
|
- 正常结果:提示
Permission denied (publickey,gssapi-keyex,gssapi-with-mic),无 password 选项
5. 简化 SSH 登录(客户端配置)
编辑客户端 SSH 配置文件
配置示例
1 2 3 4 5 6
| Host 自定义别名 HostName 服务器IP User 用户名 Port 端口 IdentityFile ~/.ssh/id_ed25519 ServerAliveInterval 60
|
快捷登录