ansible 远程自动交互式命令的响应

2019-12-23 15:23:35 +08:00
 firejoke

因为管理一般都是用 ssh 密钥连接远程主机, 但要获取 ssh 密钥还是需要先用密码远程登陆一次去生成和获取 但 ssh-keygen 这个命令是一个交互式命令, 如果用 psexec 模块来做响应匹配, 则需要目标主机安装 pypsexec 包, 但我并不想在部署服务之前在远程主机安装任何依赖, 所以改用 shell 模块 原 shell 脚本:

if [ -f ~/.ssh/id_rsa.pub ]
then
  cat ~/.ssh/id_rsa.pub
elif [ -f ~/.ssh/id_rsa ] && [ ! -f ~/.ssh/id_rsa.pub ]
then
  echo -e "\ny\n\n\n" | ssh-keygen -t rsa
  cat ~/.ssh/id_rsa.pub
else
  echo -e "\n\n\n\n" | ssh-keygen -t rsa
  cat ~/.ssh/id_rsa.pub
fi

改成 play

- hosts: 192.168.8.128
  tasks:
  - name: create host ssh rsa
    shell: 
      if [ -f ~/.ssh/id_rsa.pub ];then cat ~/.ssh/id_rsa.pub;elif [ -f ~/.ssh/id_rsa ] && [ ! -f ~/.ssh/id_rsa.pub ];then  echo -e "\ny\n\n\n" | ssh-keygen -t rsa;  cat ~/.ssh/id_rsa.pub;else  echo -e "\n\n\n\n" | ssh-keygen -t rsa;  cat ~/.ssh/id_rsa.pub; fi

但似乎 echo -e "\ny\n\n\n" | ssh-keygen -t rsa; 这一句并没有起效果, 有遇到过这种问题的吗? 如果还是不行的话, 那就只能 script 模块传送脚本, 或者用 paramiko 封装一个, 之前在其他项目用的是 fabric, 但这个想用 ansible 做

4808 次点击
所在节点    Ansible
9 条回复
stcheng
2019-12-23 23:37:55 +08:00
楼主有没有试过 Ansible 的 expect 模块?
firejoke
2019-12-24 10:36:11 +08:00
@stcheng #1 试过, 需要目标主机安装了 pexpect
stcheng
2019-12-25 14:02:34 +08:00
@firejoke what about using 'yes' command?
stcheng
2019-12-25 14:27:24 +08:00
我研究了一下应该是 ssh-keygen 的问题 需要用-q 和-N 的参数
你可以试试这行命令
ansible localhost -m shell -a "cat /dev/zero | ssh-keygen -q -N ''"

这个可以保证在主机已经有 id_rsa 和 id_rsa.pub 的时候报错
也可以让主机在没有 id_rsa 和 id_rsa.pub 的时候产生这两个文件

ansible localhost -m shell -a "cat /dev/zero | ssh-keygen -q -N ''"
localhost | FAILED | rc=1 >>
/home/shuotian/.ssh/id_rsa already exists.
Overwrite (y/n)? Enter file in which to save the key (/home/shuotian/.ssh/id_rsa): cat: write error: Broken pipe

▶ ansible localhost -m shell -a "cat /dev/zero | ssh-keygen -q -N ''"
localhost | SUCCESS | rc=0 >>
Enter file in which to save the key (/home/shuotian/.ssh/id_rsa): cat: write error: Broken pipe

这样,也不需要一开始的 if 条件来判断是否存在文件了
firejoke
2019-12-26 12:32:03 +08:00
@stcheng #4
加 -N 参数会报错
``` bash
ansible localhost -m shell -a "cat /dev/zero | ssh-keygen -N -q"

localhost | FAILED | rc=1 >>
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): Saving key "/root/.ssh/id_rsa" failed: passphrase is too short (minimum five characters)non-zero return code
```
不管远程还是本地, 报的错一样

本地的不加 -N 可以
```bash
ansible localhost -m shell -a "cat /dev/zero | ssh-keygen -q"
```
但是远程机器还是会卡住, 似乎是管道没起作用
firejoke
2019-12-26 12:34:07 +08:00
@firejoke #5 你那个-N 后面是一对单引号吗? 我还以为你是打了两遍双引号......
stcheng
2019-12-26 12:38:52 +08:00
@firejoke N 后面是一对单引号
stcheng
2019-12-26 12:40:02 +08:00
-N new_passphrase
两个单引号是给一个空的 passphrase
firejoke
2019-12-26 14:07:59 +08:00
@stcheng #8 远程也可以, 谢谢了!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/631554

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX