Ansible安装与自动化部署SSH密钥认证

  • Post author:
  • Post category:Ansible
  • Page Views 818 阅读

1.Ansible安装

curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum list ansible --showduplicates #查看可安装版本
yum install ansible -y
ansible --version

2.创建自动交互脚本

使用Expect自动交互程序

yum instal expect -y

脚本如下:

[root@Ansible ansible]# cat ssh_key.exp
#!/usr/bin/expect
if { $argc !=2 } {
send_user "usage:expect expect.exp file host\n"
exit
}
set file [ lindex $argv 0 ]
set host [ lindex $argv 1 ]
set passwd "123456"
spawn ssh-copy-id -i $file root@$host
expect {
"yes/no" {send "yes\r";exp_continue}
"*password" {send "$passwd\r"}
}
expect eof

使用Shell脚本循环执行Expect脚本,Shell脚本如下:

[root@Ansible ansible]# cat ssh_key.sh
#!/bin/bash
rm -rf ~/.ssh/id_rsa*
ssh-keygen -f ~/.ssh/id_rsa -P "" >/dev/null 2>&1
for n in 131 151
do
expect ssh_key.exp ~/.ssh/id_rsa.pub 192.168.244.$n
done

>>>优化脚本:从文件读取主机、账号、密码<<<

3.测试结果

[root@Ansible ansible]# sh ssh_key.sh
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.244.131
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.244.131 (192.168.244.131)' can't be established.
ECDSA key fingerprint is SHA256:7MF+VxvVw5ZJcOLY0ZNqjF6xr3hAdzqCIZgIlGFt5mw.
ECDSA key fingerprint is MD5:c5:43:3b:6a:1e:a3:51:08:c6:6e:a7:c7:8e:a7:0f:88.
Are you sure you want to continue connecting (yes/no)? yes #自动输入
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.244.131's password: #自动输入
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.244.131'"
and check to make sure that only the key(s) you wanted were added.
...

 

 


「 文章如果对你有帮助,请点个赞哦^^ 」 

0