在Ubuntu上配置SSH密钥登录的完整步骤:
1. 生成SSH密钥对
在客户端机器上(你要用来连接的机器):
# 生成RSA密钥对(推荐4096位)ssh-keygen -t rsa -b 4096 -C "your_email@example.com"# 或者生成Ed25519密钥(更安全,推荐)ssh-keygen -t ed25519 -C "your_email@example.com"
按提示操作:
- 选择密钥保存位置(默认:
~/.ssh/id_rsa) - 设置密码短语(可选,但推荐)
2. 将公钥复制到服务器
方法一:使用ssh-copy-id(推荐)
ssh-copy-id username@server_ip
方法二:手动复制
# 查看公钥内容cat ~/.ssh/id_rsa.pub# 登录服务器后,将公钥内容添加到authorized_keysmkdir -p ~/.sshecho "公钥内容" >> ~/.ssh/authorized_keyschmod 700 ~/.sshchmod 600 ~/.ssh/authorized_keys
方法三:使用scp复制
scp ~/.ssh/id_rsa.pub username@server_ip:~/# 登录服务器后cat ~/id_rsa.pub >> ~/.ssh/authorized_keysrm ~/id_rsa.pub
3. 配置SSH服务器(在Ubuntu服务器上)
编辑SSH配置文件:
sudo nano /etc/ssh/sshd_config
确保以下配置正确:
# 启用公钥认证PubkeyAuthentication yes# 指定authorized_keys文件位置AuthorizedKeysFile .ssh/authorized_keys# 可选:禁用密码登录(提高安全性)PasswordAuthentication no# 可选:禁用root登录PermitRootLogin no# 可选:只允许特定用户登录AllowUsers username1 username2
注意:此处的文件是sshd_config,而不是ssh_config;同时,要把文件开头的“Include /etc/ssh/sshd_config.d/*.conf”语句注释,因为这个导入的配置文件里默认是开启密码登录的,这会导致你后续配置的密钥登录无效
重启SSH服务:
sudo systemctl restart sshd
注意:此处重启的服务是sshd,而不是ssh
4. 测试密钥登录
# 从客户端测试连接ssh username@server_ip# 指定密钥文件(如果不是默认位置)ssh -i ~/.ssh/your_private_key username@server_ip
5. 创建SSH配置文件(可选)
在客户端创建 ~/.ssh/config 文件来简化连接:
nano ~/.ssh/config
添加配置:
Host myserverHostName server_ipUser usernamePort 22IdentityFile ~/.ssh/id_rsaIdentitiesOnly yes
然后可以直接使用:
ssh myserver
6. 安全建议
设置正确的文件权限:
chmod 700 ~/.sshchmod 600 ~/.ssh/id_rsachmod 644 ~/.ssh/id_rsa.pubchmod 600 ~/.ssh/authorized_keyschmod 600 ~/.ssh/config
备份私钥并安全保存
考虑使用SSH Agent: ```bash
启动ssh-agent
eval “$(ssh-agent -s)”
添加私钥
ssh-add ~/.ssh/id_rsa
4. **定期更换密钥**5. **监控SSH日志**:```bashsudo tail -f /var/log/auth.log
配置完成后,你就可以使用密钥安全地登录Ubuntu服务器,无需输入密码了。
