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

如何在Ansible中手动发送回车键?解决sudo二次回车认证错误

解决Ansible中"Incorrect sudo password"错误及服务器sudo挂起问题

我之前碰到过一模一样的情况!你看到的这个错误:

fatal: [192.168.1.10]: FAILED => {"msg": "Incorrect sudo password"}

其实根本不是密码输错了——是服务器上的PAM配置有bug:手动SSH登录后执行sudo su,进程会莫名挂住,必须再按一次回车才能进入root shell。Ansible的sudo交互逻辑没处理这个额外回车的情况,就误判成密码错误了。

要自动修复这个问题,我们可以用Ansible模拟手动操作的流程(执行修复命令+延迟后按回车),下面给你两种可行的Playbook方案:

方案一:用expect模块(推荐,更可靠)

expect模块专门用来处理交互式命令,能完美模拟输入密码、等待延迟后发送回车的操作:

- name: Fix sudo hang issue caused by PAM krb5/tacplus modules
  hosts: 192.168.1.10
  become: false
  vars:
    ansible_become_pass: "你的sudo密码" # 建议用ansible-vault加密存储,不要明文填写
  tasks:
    - name: Install expect tool (Debian/Ubuntu)
      apt:
        name: expect
        state: present
      when: ansible_os_family == 'Debian'

    - name: Install expect tool (RHEL/CentOS/Rocky)
      dnf:
        name: expect
        state: present
      when: ansible_os_family == 'RedHat'

    - name: Execute pam-auth-update and send extra enter to fix hang
      expect:
        command: sudo pam-auth-update --remove krb5 tacplus
        responses:
          # 这里要匹配你服务器的sudo密码提示,英文环境是"Password:",中文环境是"密码:"
          "Password:": "{{ ansible_become_pass }}"
        timeout: 5 # 给命令足够的执行时间,可根据服务器响应速度调整
        echo: yes # 确保输入内容被正确传递
      register: fix_result
      failed_when: fix_result.rc != 0

方案二:用shell模块(快速替代方案)

如果不想安装expect,也可以用shell结合sleep和管道来模拟,不过这种方式依赖shell环境,稳定性稍差:

- name: Alternative fix for sudo hang issue
  hosts: 192.168.1.10
  become: false
  vars:
    ansible_become_pass: "你的sudo密码"
  tasks:
    - name: Run pam-auth-update with extra enter
      shell: |
        echo "{{ ansible_become_pass }}" | sudo -S pam-auth-update --remove krb5 tacplus
        sleep 3
        echo ""
      args:
        executable: /bin/bash
      register: fix_result
      failed_when: fix_result.rc != 0

注意事项

  • 优先推荐expect方案,它对交互式场景的处理更稳定
  • 替换ansible_become_pass为实际sudo密码,强烈建议用ansible-vault加密存储敏感信息
  • 可根据服务器实际响应速度,调整sleep(方案二)或timeout(方案一)的时长
  • 若目标服务器是RHEL系,可能需要调整pam-auth-update相关命令,换成对应系统的PAM配置工具

内容的提问来源于stack exchange,提问作者Tim R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:56:20