You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用sudo执行Ansible命令连接远程主机失败:SSH权限被拒绝

问题:普通用户执行Ansible临时命令正常,sudo执行失败

现象

普通用户执行ping模块成功:

[ansible@tower ansible-automation-platform-setup-bundle-2.3-2.1]$ ansible all -m ping
tower.vmnet.local | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

使用sudo执行相同命令失败:

[ansible@tower ansible-automation-platform-setup-bundle-2.3-2.1]$ sudo ansible all -m ping
tower.vmnet.local | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ansible@tower.vmnet.local: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}

现有配置

ansible.cfg配置

[defaults]
inventory = inventory
remote_user = ansible
host_key_checking = false

[privilege_escalation] 
become = True
become_method = sudo
become_user = root
become_ask_pass = False

SSH配置(/etc/ssh/sshd_config)

[ansible@tower ansible-automation-platform-setup-bundle-2.3-2.1]$ sudo cat /etc/ssh/sshd_config | grep Root
PermitRootLogin yes #原配置注释为prohibit-password,已修改为允许root登录

原因分析

当使用sudo执行Ansible命令时,实际是以root用户身份发起SSH连接请求,但root用户未配置对应的SSH密钥对,无法通过目标主机ansible用户的密钥认证,因此触发权限拒绝错误。而普通用户ansible本身拥有合法的SSH密钥,所以能正常完成连接和操作。

解决方法

方案1:为root用户配置SSH密钥对

生成root用户的SSH密钥,并将公钥复制到目标主机的ansible用户授权列表中:

sudo ssh-keygen -t rsa -N "" -f /root/.ssh/id_rsa
sudo ssh-copy-id ansible@tower.vmnet.local

方案2:保留原用户的SSH环境执行命令

使用sudo -E参数保留当前用户的环境变量(包括SSH相关配置),或者直接指定原用户的私钥路径:

# 保留环境变量执行
sudo -E ansible all -m ping

# 直接指定私钥路径
sudo ansible all -m ping --private-key=/home/ansible/.ssh/id_rsa

方案3:修改Ansible配置切换远程用户

如果目标主机允许root用户SSH登录,可以修改ansible.cfg的remote_user为root,或者执行命令时临时指定:

# 临时指定远程用户为root
sudo ansible all -m ping -u root

内容的提问来源于stack exchange,提问作者Somenath Sinha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:32:55