expect是一种脚本语言,它能够代替我们实现与终端的交互。
核心命令是spawn expect send set
以下是两个expect 脚本例子及注析:
1. #!/usr/bin/expect :需要先安装软件,实际路径查看 whereis expect
2. set timeout : 例1 中 设置expect 1000秒超时,如果超过1000没有expect内容出现,则退出; 设置expect永不超时,set timeout -1 ;
3. spawn 是进入expect环境后才可以执行的expect内部命令,用来开启一个会话进程。
4. expect 是expect的内部命令,用来匹配字符串,如果有,就会立即返回下面设置的内容,如果没有匹配变会等到超时。
5. send "xx\r":这时执行交互式动作,在expect截获关键字之后,它就会输入send后面的内容,记得\r 否则相当只是在屏幕上输入了命令但没有回车。
6. expect eof 与spawn对应表示捕获终端输出信息终止,类似于if....endif
7. interact:执行完毕后保持交互状态,并等待手工输入的操作了。
8. [lindex $argv 0] 表示脚本的第一个参数,第二个参数+1 ,以此类推。
9. set src_file [lindex $argv 0] / set PASS "haha" :设置变量值 set <VAR> <value>
例子1:把远程主机xxx.xx.xx.xx的/vob/WAG_Testing/lastBuild/ 目录清空,并把传入的文件名拷到远程主机同一目录下。
执行:./scp_to_WAG.sh <filename>
- #!/usr/bin/expect
- set timeout 1000
- set src_file [lindex $argv 0]
- set PASS "haha"
- spawn ssh user@xx.xx.xx.xx "rm -f /vob/WAG_Testing/lastBuild/*"
- expect {
- "(yes/no)?"
- {
- send "yes\n"
- expect "*assword:" { send "$PASS\n"}
- }
- "*assword:"
- {
- send "haha\n"
- }
- }
- expect eof
- spawn scp $src_file user@xx.xx.xx.xx:/vob/WAG_Testing/lastBuild/
- expect {
- "(yes/no)?"
- {
- send "yes\n"
- expect "*assword:" { send "$PASS\n"}
- }
- "*assword:"
- {
- send "haha\n"
- }
- }
- expect "100%"
- expect eof
例子2:ftp 到远程主机,在远程主机上创建目录(传出入参数为目录名),并把当前所有文件通过ftp放到远程目录上。
执行:./ftp_file.sh <directory>
- #!/usr/bin/expect
- set timeout 7200
- set version_num [lindex $argv 0]
- #set list1 [lindex $argv 1]
- set FTP "ftp>"
- spawn ftp xx.xx.xx.xx
- expect {
- "):"
- { send "username\n"
- expect "*assword:" {send "6666\n"}
- }
- "command not found"
- {
- print "ftp not install"
- }
- }
- expect "Using binary mode to transfer files."
- send "pwd\n"
- sleep 1
- expect "$FTP"
- send "mkdir $version_num\n"
- sleep 1
- expect "$FTP"
- send "pwd\n"
- sleep 1
- expect "$FTP"
- send "cd $version_num\n"
- sleep 1
- expect "$FTP"
- send "pwd\n"
- sleep 1
- expect "$FTP"
- send "prompt\n"
- sleep 1
- expect "$FTP"
- send "mput * \n"
- expect "$FTP"
- send "quit\n"
- sleep 2
- expect eof
No Leanote account? Sign up now.