ssh手动添加免密

报错:

wsl环境 root@k8s:~/ansible# ssh-copy-id root@192.168.31.165 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub” /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed – if you are prompted now it is to install the new keys root@192.168.31.165: Permission denied (publickey).

这个情况说明:

  • WSL 本地已生成了 SSH 密钥(/root/.ssh/id_rsa.pub);
  • ssh-copy-id 成功读取了公钥;
  • 但目标主机 192.168.31.165 禁用了密码登录,所以 ssh-copy-id 无法登录进去安装公钥。

✅ 解决方法

因为目标主机只支持 publickey 登录,你有两个选择:


方案 1:手动通过目标主机控制台添加公钥

如果你能登录目标主机的控制台(比如通过 VMware/ESXi/vCenter、KVM 控制台或者物理机),请执行以下操作:

🚀 1. 在 WSL 查看公钥内容:

1
cat ~/.ssh/id_rsa.pub

输出形如:

1
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1z... root@k8s

🛠 2. 在目标主机(192.168.31.165)上执行:

1
2
3
4
mkdir -p /root/.ssh
echo "【上面那串公钥内容】" >> /root/.ssh/authorized_keys
chmod 700 /root/.ssh
chmod 600 /root/.ssh/authorized_keys

确保 sshd_config 中如下内容没有被禁用:

1
2
PermitRootLogin yes
PubkeyAuthentication yes

修改后重启 SSH 服务:

1
systemctl restart ssh

方案 2:临时允许密码登录用于 ssh-copy-id

仅建议你临时改一下,用完再改回去!

在目标机修改 /etc/ssh/sshd_config

1
2
PermitRootLogin yes
PasswordAuthentication yes

然后重启 SSH 服务:

1
systemctl restart ssh

然后在 WSL 执行:

1
ssh-copy-id root@192.168.31.165

验证后建议把 PasswordAuthentication 改回 no,提高安全性。


✅ 验证 SSH 是否成功:

1
ssh root@192.168.31.165

若无需密码,说明配置成功,此时 Ansible 就能正常跑了:

1
ansible all -i host -m ping

需要我帮你写自动检测是否已配置 SSH 公钥、自动推送脚本,也可以继续告诉我。