1. expect脚本
1.1. 自动远程登录
vim test_login_expect.sh
chmod a+x test_login_expect.sh
# 内容如下
#!/usr/bin/expect
#定义变量host和passwd
set host "192.168.137.30"
set passwd "root"
#登录远程机器,要使用spawn命令
spawn ssh root@$host
#以下为expect交互部分,当输出yes/no的时候,脚本会自动提供yes,\r为回车的意思,exp_continue的作用是继续执行{ }内下面的语句,如果不加,下面的就不会生效了.
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
#interact的作用是,登录完远程机器后,不要退出来,一直保持登录状态,如果不加这句,登录完后马上会退出.
interact
# 测试
./test_login_expect.sh
1.2. 远程登录后执行命令
#!/usr/bin/expect
set user "root"
set passwd "root"
spawn ssh $user@192.168.137.30
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
#这里的*为通配符号,比如']#'或者']$'都匹配,它的意思是当遇到']*'时,发送下面的指令.
expect "]*"
send "touch /tmp/12.txt\r"
expect "]*"
send "echo 1212 > /tmp/12.txt\r"
expect "]*"
send "exit\r"
#增加expect eof的目的是,保证脚本中所有的指令都能执行完成.它相当于是一个结尾符.
expect eof
1.3. 给expect脚本增加参数
#!/usr/bin/expect
#定义第一个参数,类似于shell的$1
set user [lindex $argv 0]
#定义第二个参数,类似于shell的$2
set host [lindex $argv 1]
set passwd "root"
#定义第三个参数,类似于shell的$3
set cm [lindex $argv 2]
spawn ssh $user@$host
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
此时执行脚本时,需要带上参数,比如脚本名字为test.expect,用户为root,ip为192.168.137.30,执行的命令为w,则最终执行该脚本时应该这样写:
[root@aminglinux ~]# ./test.expect root 192.168.137.30 "w"
1.4. 自动同步文件
#!/usr/bin/expect
set passwd "root"
#spawn后面的命令不是ssh,而是rsync
spawn rsync -av root@192.168.137.30:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
#如果不加expect eof,则rsync命令不会正常执行完成的.
expect eof
1.5. 简易批量文件分发
vim rsync.expect
# 内容如下
#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -av --files-from=$file / root@$host:/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
然后创建一个ip列表:
vim ip.list
# 内容如下
192.168.137.30
192.168.137.31
运行:
for ip in `cat ip.list`
do
./rsync.expect $ip a.file
done
1.6. 批量执行脚本
vim bash.expect
#内容如下
#!/usr/bin/expect
set host [lindex $argv 0]
set passwd "123456"
set cm [lindex $argv 1]
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
执行
#!/bin/bash
for ip in `cat ip.list`
do
echo $ip
./bash.expect $ip "w;free -m;ls /tmp"
done