linux expect教程

linux expect教程

expect语法

expect使用的语法是TCL语法,TCL缩短工具命令语言的形式。由加州大学伯克利分校的约翰Ousterhout设计它。它是一种脚本语言,由其自身的解释器,它被嵌入到开发应用程序的组合。

常用命令

  • spawn 交互程序开始后面跟命令或者指定程序
  • expect 获取匹配信息匹配成功则执行expect后面的程序动作
  • send exp_send 用于发送指定的字符串信息
  • exp_continue 在expect中多次匹配就需要用到
  • send_user 用来打印输出 相当于shell中的echo
  • exit 退出expect脚本
  • eof expect执行结束 退出
  • set 定义变量
  • puts 输出变量
  • set timeout 设置超时时间

exp脚本文件

expect可以运行exp脚本文件

#!/usr/bin/expect

#设置变量,有空格可以使用{}括住
set varA 10
#定义一个叫var B的变量(含空格的变量)
set {var B} test
# 变量可以是运算后的结果
set sum [expr $varA +20];

#输出
puts $varA
puts ${var B}

# for循环
for { set a 10}  {$a < 20} {incr a} {
   puts "value of a: $a"
}

# foreach 循环
foreach i { 1 3 5 7 9 } {
    puts $i
}

#while loop execution 
while { $a < 20 } {
   puts "value of a: $a"
   incr a
}

# if..else
if {$a < 20 } {

} else {

}

#交互命令
set timeout 30
set passwd 123456
spawn ssh [email protected] df -Th
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect eof

在shell中写expect

#!/bin/bash

passwd="123456"

expect <<EOF

set timeout 30
set var 123

#想要使用expect中的变量,必须给$转义,避免解析成shell变量,否则解析成shell变量
puts \${var}

#交互
spawn ssh [email protected] df -Th
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect eof
EOF

语义冲突(转义)

我们经常会用expect去做一些需要命令交互任务,如:ftp命令行交互

命令交互时,我们往往会使用一些linux上的通配符,如[]{}等这些,而在expect中这些符合在expect中是语法的一部分,所以在交互时,需要使用反斜杠来转义。

还有一点要注意,就是在shell中写expect脚本,$要进行转义,才能被解析成expect中的变量

#!/bin/bash
pwd="123456"

expect <<EOF >LOG.log
set timeout 30
#开始交互
spawn sftp [email protected]
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r" }
}

#移动到指定目录
expect "*sftp>*"
send "cd /tmp/test"
expect "*sftp>*"
send "lcd /tmp/test2"
expect "*sftp>*"

#尽管使用了""括住,依旧需要转移
send "mget file\[1-3\]"
expect "*sftp>*"
send "exit"

expect eof
EOF

猜你喜欢

转载自blog.csdn.net/qq_43203949/article/details/131745771
今日推荐