一、生成SSH密钥对
在客户端主机 ClientHost
上,以 root
用户身份生成SSH密钥对:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
# -t rsa:指定使用RSA算法
# -b 4096:指定密钥长度为4096位
# -C "" :添加注释,用于标识密钥。
二、将公钥复制到服务端主机
使用 ssh-copy-id 命令将公钥复制到服务机 ServerHost 的 root 用户 ~/.ssh/authorized_keys 文件中:
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.29.28
# -i ~/.ssh/id_rsa.pub:指定要复制的公钥文件。
# root@192.168.29.28:目标用户(root)和主机(192.168.29.28)。
三、确保服务端配置文件正确
在服务端主机 ServerHost 上,确保SSH服务配置正确:
-
检查并编辑 /etc/ssh/sshd_config 文件,确保以下选项被正确设置。
# 允许公钥认证 PubkeyAuthentication yes # 禁止密码认证(可选,但推荐) PasswordAuthentication no # 确保ChallengeResponseAuthentication被禁用(如果存在) ChallengeResponseAuthentication no # 允许使用.ssh/authorized_keys文件中的密钥 AuthorizedKeysFile .ssh/authorized_keys
-
保存并关闭文件。
-
重启SSH服务以应用更改。
systemctl restart sshd
四、测试SSH免密登录
回到客户端主机 ClientHost
,尝试通过SSH连接到服务端主机 ServerHost
,不需要输入密码: