1. 基本原理
ssh 免密码登录通过公钥认证实现:
- 在客户端生成一对密钥(公钥和私钥)。
- 将公钥添加到目标服务器的
~/.ssh/authorized_keys
文件中。 - 客户端使用私钥登录,无需输入密码。
2. 具体步骤
2.1 在客户端生成 ssh 密钥对
检查是否已有密钥
在客户端(你的本地机器或跳板机)上,检查是否已有 ssh 密钥:
ls -l ~/.ssh/
如果存在 id_rsa
(私钥)和 id_rsa.pub
(公钥),可以跳到步骤 2.2。
生成密钥对
使用 ssh-keygen
生成 rsa 或 ed25519 密钥(推荐 ed25519,安全性更高):
ssh-keygen -t ed25519 -c "your_email@example.com"
或使用 rsa(旧系统可能不支持 ed25519):
ssh-keygen -t rsa -b 4096 -c "your_email@example.com"
- 按 enter 接受默认文件路径(
~/.ssh/id_ed25519
或~/.ssh/id_rsa
)。 - 可设置密码保护私钥(为空则无密码,推荐为空以实现完全免密)。
- 执行后会生成:
~/.ssh/id_ed25519
或~/.ssh/id_rsa
(私钥)~/.ssh/id_ed25519.pub
或~/.ssh/id_rsa.pub
(公钥)
2.2 将公钥复制到目标服务器
将客户端的公钥添加到目标服务器的 ~/.ssh/authorized_keys
文件中。
使用 ssh-copy-id
(推荐,简单)
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@remote_host
- 替换
user
为目标服务器的用户名,remote_host
为服务器 ip 或域名。 - 输入目标服务器密码,公钥会自动添加到
~/.ssh/authorized_keys
。
手动复制(如果 ssh-copy-id
不可用)
- 在客户端查看公钥内容:
cat ~/.ssh/id_ed25519.pub
- 复制输出内容(类似
ssh-ed25519 aaaac3... your_email@example.com
)。 - 登录目标服务器,编辑
authorized_keys
:
ssh user@remote_host mkdir -p ~/.ssh echo "your_public_key" >> ~/.ssh/authorized_keys
- 确保权限正确:
chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys
2.3 测试免密码登录
在客户端尝试登录:
ssh user@remote_host
如果配置正确,将无需输入密码直接登录。
2.4 (可选)配置 ssh 客户端
为方便管理,可以在客户端的 ~/.ssh/config
文件中添加配置:
# 编辑配置文件 nano ~/.ssh/config
添加以下内容:
host alias_name hostname remote_host user user identityfile ~/.ssh/id_ed25519
alias_name
:自定义别名,如myserver
。- 保存后,使用
ssh alias_name
即可登录。
3. 防火墙与 ssh 配置
确保目标服务器的防火墙允许 ssh 连接(默认端口 22):
使用 firewalld:
sudo firewall-cmd --zone=public --add-service=ssh --permanent sudo firewall-cmd --reload
使用 iptables:
sudo iptables -a input -p tcp --dport 22 -j accept sudo iptables-save > /etc/sysconfig/iptables
使用 ufw(ubuntu):
sudo ufw allow ssh
4. 常见问题排查
无法免密登录
检查服务器端 ssh 配置(/etc/ssh/sshd_config
):
sudo nano /etc/ssh/sshd_config
确保以下配置启用:
pubkeyauthentication yes authorizedkeysfile .ssh/authorized_keys
重启 ssh 服务:
sudo systemctl restart sshd
检查 ~/.ssh/authorized_keys
文件权限(必须为 600):
ls -l ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys
检查客户端私钥权限:
chmod 600 ~/.ssh/id_ed25519
selinux 限制(centos/rhel)
如果 selinux 启用,可能阻止 ssh 登录:
sudo setsebool -p ssh_keysign on sudo restorecon -r -v ~/.ssh
连接被拒绝
- 确认服务器 ssh 服务运行:
sudo systemctl status sshd
- 检查防火墙是否开放 22 端口:
sudo firewall-cmd --list-ports
- 测试端口连通性:
nc -zv remote_host 22
公钥格式错误
确保公钥是一行完整内容,复制时不要引入换行符。
5. ai 开发相关场景
在 ai 开发中,免密码登录常用于:
- 远程访问 gpu 服务器:配置 jupyter notebook 或 tensorflow serving 的远程访问。
- 自动化脚本:如批量部署模型训练任务,需在多台机器间免密传输文件(
scp
或rsync
)。 - docker 集群:在多节点集群中配置 ssh 免密登录以便管理。
示例:在客户端配置 scp
免密传输:
scp dataset.tar.gz user@remote_host:/path/to/destination
6. 安全注意事项
- 保护私钥:不要泄露
~/.ssh/id_rsa
或~/.ssh/id_ed25519
,确保文件权限为 600。
限制公钥访问:在 authorized_keys
中可添加限制,如:
from="192.168.1.100" ssh-ed25519 aaaac3... your_email@example.com
仅允许特定 ip 使用该公钥登录。
禁用密码登录:为提高安全性,可在 /etc/ssh/sshd_config
中设置:
passwordauthentication no
然后重启 sshd
:
sudo systemctl restart sshd
以上就是linux中设置ssh免密码(密钥)登录的具体步骤的详细内容,更多关于linux ssh免密码登录的资料请关注代码网其它相关文章!