linux expect教程
expect语法
expect使用的语法是TCL语法,TCL缩短工具命令语言的形式。由加州大学伯克利分校的约翰Ousterhout设计它。它是一种脚本语言,由其自身的解释器,它被嵌入到开发应用程序的组合。
常用命令
spawn 交互程序开始后面跟命令或者指定程序expect 获取匹配信息匹配成功则执行expect后面的程序动作send exp_send 用于发送指定的字符串信息exp_continue 在expect中多次匹配就需要用到send_user 用来打印输出 相当于shell中的echoexit 退出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 |