大网数据广告活动
服务器运维问答

How to make Ansible use password if key was rejected?

· 52CE 我爱测

My new server instances are configured to login on root via ssh with password. I want my Ansible playbook to reconfigure it to use keys instead and disable root login with password on first run, so I need something like this: try…

问题原文

原帖链接 · petr0 · CC BY-SA 3.0

My new server instances are configured to login on root via ssh with password. I want my Ansible playbook to reconfigure it to use keys instead and disable root login with password on first run, so I need something like this:

  • try to login with key
  • if can't login with key:

    • login with password
    • add key to authorized_keys
    • disable root login with password
    • optionally reconnect using key
  • do other tasks

How can I accomplish that?

EDIT: To be clear, I'm not asking how to add key or disable root, that's just for context. I'm asking how to fallback to password if it couldn't authenticate with key. With --ask-pass or ansible_ssh_pass set, Ansible won't even try to use public key authentication

已采纳解答

原帖链接 · eisd · CC BY-SA 3.0

You could try the PreferredAuthentications option, setting it to publickey,password. The default includes these in this order, along with other options, so ansible is presumably setting this. Adding it via -o or the client ssh_config may prevent this.

You may be able to use a wrapper script. For example, with this in key_or_password.sh and a pass.sh that gives the password, running bash key_or_password.sh root@host will try a publickey followed by a non-interactive password login.

export DISPLAY=dummy:0
export SSH_ASKPASS=$PWD/pass.sh
exec setsid ssh -v -o 'PreferredAuthentications publickey,password' "$@"

The log indicates which method succeeded with, e.g.

debug1: Authentication succeeded (publickey).

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2013-11-04)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。