因为管理一般都是用 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 做
1
stcheng 2019-12-23 23:37:55 +08:00 via iPhone
楼主有没有试过 Ansible 的 expect 模块?
|
4
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 条件来判断是否存在文件了 |
5
firejoke OP @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" ``` 但是远程机器还是会卡住, 似乎是管道没起作用 |
8
stcheng 2019-12-26 12:40:02 +08:00
-N new_passphrase
两个单引号是给一个空的 passphrase |