***Tips:***在使用ansible部署服务器的时候,部署机需要先做好和其他服务器的免密码登陆,如果一台一台手动执行那就太low了,所以就需要脚本来批量完成这些繁琐的工作,下面是我写的脚本,主要使用了expect这个工具。

expect介绍

  • expect是用于提供自动交互的工具,它可以控制处理输入和输出流,然后提供自动填写数据等功能(主要就是替代原本需要人机交互需要做的事情)
  • expect采用tcl(Tool Command Language)的脚本语言

脚本实例(自用脚本可随意参考)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/sh
###############################################################################
#Author: arvon
#Email: yafeng2011@126.com
#Blog: http://arvon.top/
#Date: 2016/08/08
#Filename: write_authorized_keys.sh
#Revision: 1.0
#License: GPL
#Description: auto write authorized to other server
#Notes:
###############################################################################
#vars
username='root'
server_passwd='arvon2014'
IP_list="
172.17.18.61
172.17.18.62
172.17.18.63
"
#functions
function Main(){
#install_expect_package
#create_ras_pub
write_authorized_file
}
#install expect package
function install_expect_package(){
yum install -y expect expect-devel
}
function create_rsa_pub(){
expect -c "
spawn ssh-keygen -t rsa
  expect {
    \"*y/n*\" {send \"y\r\"; exp_continue}
    \"*key*\" {send \"\r\"; exp_continue}
    \"*passphrase*\" {send \"\r\"; exp_continue}
    \"*again*\" {send \"\r\";}
  }"
}
function write_authorized_file(){
for each_ip in ${IP_list};do
    expect -c "  
    spawn ssh-copy-id ${username}@${each_ip}  
      expect {  
        \"*yes/no*\" {send \"yes\r\"; exp_continue}  
        \"*password*\" {send \"${server_passwd}\r\"; exp_continue}  
        \"*Password*\" {send \"${server_passwd}\r\";}  
      }  
    "  
done
}
#Main
Main

参考地址

1. Expect官方文档 2. python俱乐部 3. Beckham008的blog