运行Ansible脚本的用户与远程登录用户不同时,如何通过SSH私钥登录?
问题描述
在WSL的Windows机器上运行Ansible脚本,尝试通过RSA密钥SSH登录远程主机,但执行脚本的local_user和远程主机的登录用户remote_user不是同一个人。脚本内容如下:
- hosts: servers_test gather_facts: false remote_user: "remote_user" become: true become_method: sudo vars: ansible_ssh_user: "remote_user" ansible_become_password: "remote_user_pass" ansible_ssh_private_key_file: "/home/remote_user/.ssh/id_rsa" tasks: - name: Gather facts from remote_host setup:
运行时出现权限错误,无法访问remote_user的私钥,错误信息如下:
<172.27.254.109> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o 'IdentityFile="/home/remote_user/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="remote_user"' -o ConnectTimeout=10 -o 'ControlPath="/home/local_user/.ansible/cp/0eddb9ee6d"' 172.27.254.109 '/bin/sh -c '"'"'echo ~remote_user && sleep 0'"'"'' <172.27.254.109> (255, b'', b'no such identity: /home/remote_user/.ssh/id_rsa: Permission denied\r\nremote_user@172.27.254.109: Permission denied (publickey).\r\n') fatal: [172.27.254.109]: UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: no such identity: /home/remote_user/.ssh/id_rsa: Permission denied\r\nremote_user@172.27.254.109: Permission denied (publickey).", "unreachable": true }
核心原因是local_user没有权限访问所有权为remote_user:remote_user且权限为0600的私钥文件。
解决方案
下面是几种可行的调整方式:
方法1:复制私钥到local_user目录并修正权限
- 把
remote_user的私钥复制到local_user的.ssh目录:cp /home/remote_user/.ssh/id_rsa /home/local_user/.ssh/ - 修改私钥的所有权和权限,符合SSH的安全要求:
chown local_user:local_user /home/local_user/.ssh/id_rsa chmod 600 /home/local_user/.ssh/id_rsa - 修改Ansible脚本中的
ansible_ssh_private_key_file路径为/home/local_user/.ssh/id_rsa。
方法2:以remote_user身份执行Ansible
- 直接切换到
remote_user运行脚本,绕过权限限制:sudo -u remote_user ansible-playbook your-playbook.yml - 此方式无需修改原脚本,因为
remote_user本身有权限访问自己的私钥。
方法3:调整私钥权限(不推荐)
- 将
local_user加入remote_user的用户组,再调整目录和文件的组权限:usermod -aG remote_user local_user chmod 750 /home/remote_user/.ssh chmod 640 /home/remote_user/.ssh/id_rsa - 注意:这种做法会降低私钥的安全性,不建议在生产环境使用。
方法4:使用SSH代理转发
- 先以
remote_user身份启动SSH代理并添加私钥:sudo -u remote_user ssh-agent bash ssh-add /home/remote_user/.ssh/id_rsa - 在同一个会话中切换回
local_user运行Ansible脚本,SSH代理会自动使用remote_user的私钥完成认证。
内容的提问来源于stack exchange,提问作者Jan Pips
相关产品推荐
相关产品推荐

