二、Expect安装
1
|
yum
install
expect -y
|
三、Expect使用
使用Expect批量管理和部署服务器大致分为两个步骤,使用for循环读取服务器IP、密码列表并取值,远程执行命令。如下需求,在两台服务器上执行mkdir /tmp/`date +%Y%m%d`命令,如何实现?
首先定义expect 登陆脚本:
1、login.exp,内容如下(详细的参数就不解释了):
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/usr/bin/expect -f
set
ip [lindex $argv 0 ]
set
passwd
[lindex $argv 1 ]
set
command
[lindex $argv 2]
set
timeout 1
spawn
ssh
root@$ip
expect {
"yes/no"
{ send
"yes\r"
;exp_continue }
"password:"
{ send
"$passwd\r"
}
}
expect
"*#*"
{ send
"$command\r"
}
expect eof
|
2、创建批量执行脚本auto_exec.sh
1
2
3
4
5
6
7
8
9
|
#!/bin/sh
#auto exec command
#wugk 20130712
CMD=
"$*"
for
i
in
`
awk
'{print $1}'
passwd
.txt`
do
j=`
awk
-
v
I=
"$i"
'{if(I==$1)print $2}'
passwd
.txt`
expect
/data/sh/login
.exp $i $j
"$CMD"
done
|
3、建立批量IP、密码文件
cat passwd.txt内容如下:(第一列为IP,第二列为密码)
1
2
|
192.168.1.100 abc_123
192.168.1.101 abc_456
|
四、测试脚本
直接执行:
1
|
/bin/sh
auto_exec.sh
"mkdir -p /tmp/`date +%Y%m%d`"
|
然后登陆两台服务器查看是否在/tmp/下生产一个以当前系统日期为名称的目录。
五、SCP远程拷贝
如果需要远程推送文件,重新建立文件login.scp相关参数和auto_exec.sh变量:
1、login.scp内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#!/usr/bin/expect -f
set
ip [lindex $argv 0 ]
set
passwd
[lindex $argv 1 ]
set
src_file [lindex $argv 2]
set
des_dir [lindex $argv 3]
set
timeout 1
spawn
scp
-r $src_file root@$ip:$des_dir
expect {
"yes/no"
{ send
"yes\r"
;exp_continue }
"password:"
{ send
"$passwd\r"
}
}
expect
"#*"
expect eof
|
2、auto_exec.sh脚本内容如下
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/bin/sh
#auto exec command
#wugk 20130712
read
-p
"Please Enter insert Source File or DIR: "
src_file
echo
======================================================
sleep
1
read
-p
"Please Enter insert Destination DIR: "
des_dir
for
i
in
`
awk
'{print $1}'
passwd
.txt`
do
j=`
awk
-
v
I=
"$i"
'{if(I==$1)print $2}'
passwd
.txt`
expect login.
scp
$i $j $src_file $des_dir
done
|
密码文件保持不变即可。
六、一键安装expect、scp批量auto_exec.sh脚本:(其实就是如上几个脚本合成的)
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
|
#!/bin/sh
#auto exec expect shell scripts
#wugk 20130712
if
[ ! -e
/usr/bin/expect
];
then
yum
install
expect -y
fi
#Judge passwd.txt exist
if
[ ! -e .
/passwd
.txt ];
then
echo
-e
"The passwd.txt is not exist......Please touch ./passwd.txt ,Content Example:\n192.168.1.11 passwd1\n192.168.1.12 passwd2"
sleep
2 &&
exit
0
fi
#Auto Tuoch login.exp File
cat
>login.exp <<EOF
#!/usr/bin/expect -f
set
ip [lindex \$argv 0 ]
set
passwd
[lindex \$argv 1 ]
set
src_file [lindex \$argv 2]
set
des_dir [lindex \$argv 3]
set
timeout 1
spawn
scp
-r \$src_file root@\$ip:\$des_dir
expect {
"yes/no"
{ send
"yes\r"
;exp_continue }
"password:"
{ send
"\$passwd\r"
}
}
expect
"#*"
expect eof
EOF
##Auto exec shell scripts
read
-p
"Please Enter insert Source File or DIR: "
src_file
echo
======================================================
sleep
1
read
-p
"Please Enter insert Destination DIR: "
des_dir
for
i
in
`
awk
'{print $1}'
passwd
.txt`
do
j=`
awk
-
v
I=
"$i"
'{if(I==$1)print $2}'
passwd
.txt`
expect .
/login
.exp $i $j $src_file $des_dir
done
|