Linux学习总结(六十三)expect脚本上

expect是Unix系统中用来进行自动化控制和测试的软件工具,由Don Libes制作,作为Tcl脚本语言的一个扩展,应用在交互式软件中如telnet,ftp,Passwd,fsck,rlogin,tip,ssh等等
yum install -y expect

脚本一:

自动远程登录

 #! /usr/bin/expect
set host "192.168.226..130"
set passwd "123456"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue}
"assword:" { send "$passwd\r" }
}
interact

运行脚本
chmod a+x 1.expect
./1.expect
备注,当初次ssh登陆时,会提示输入yes或者no,因此需要发送一个yes,再回车。紧接着输入账户的密码。如果做了秘钥认证,则不需要输入密码。interact 表示保持一个登陆状态。不加的话,会马上退出来。

脚本二:

自动远程登录后,执行命令并退出

#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh [email protected]
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"

备注:] 表示系统登陆进来,输入光标前面的状态提示符,root用户为]# 普通用户为]$,为通配符。上面的脚本表示登陆进系统,在当前用户目录下,执行了两条命令。

脚本三:

参数传递。相当于shell中的$1,$2,$3

#!/usr/bin/expect
set user [lindex $argv 0]
set host [lindex $argv 1]
set passwd "123456"
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"

备注:该脚本我们定义了三个需要传递的参数,第一个为要登陆机器的用户名,第二个为主机ip,第三个为登陆系统以后需要发送的命令。因此当运行脚本时,需要加上这三个参数。
chmod a+x 3.expect
./expect root 192.168.226.130 ls
如果需要一次性发送多个命令可以这样写“ls;w;ifconfig",或者在脚本中再定义几个参数。

脚本四:

同步文件 rsync的应用

#!/usr/bin/expect
set passwd "123456"
spawn rsync -av [email protected]:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof

备注:该脚本相当于直接执行了一个做远程同步的rsync命令,区别是里面嵌入了登陆密码,因此可以不需要和用户交互直接完成文件的同步。expect eof 的作用是让远程连接保持一个状态,不加的话会在同步未完成时,直接断开。

脚本五:

指定host和要同步的文件

#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -av $file root@$host:$file
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof

备注:该脚本的功能是将本地文件同步到远程主机上,定义了两个参数,第一个是运程主机ip,第二个是要同步的文件名。该文件必须在本地存在,执行脚本时,该文件名参数要使用绝对路径。
chmod a+x 5.expect
./5.expect 192.168.226.130 "/tmp/12.txt"

猜你喜欢

转载自blog.51cto.com/12606610/2130060