本文主要介绍expect,也就是tcl语言的控制结构 1 if …else 结构 首先展示一个脚本,这个叫本用来根据argv0的输入选择不同的expect语句SSH远程登录到相对应的服务器,并设置一些错误输出:
dongwm@linux-3qd1:~> cat bin/test #!/usr/bin/expect set timeout 10 set passwordops01 cpuqPFtkt{20 set passwordops02 O^v44qftahbN set passwordops03 9uujz)UUf7yr set file1 [lindex $argv 0] if {$argc!=1} { puts stderr "参数错误,请使用以下格式: $argv0 {想去的服务器简称,比如ops01} " exit 1 } if {$file1=="ops01"} { spawn luit -encoding gbk ssh dongwm@59.194.82.XX -p 9924 expect 194.168.45.XX send "su -n" //设置了不容许root组直接登录 expect "口令:" send "$passwordops01n" interact } elseif {$file1=="ops02"} { spawn luit -encoding gbk ssh dongwm@59.194.82.XX -p 9924 expect 194.168.45.XX send "ssh ops@ops04n" expect "192.168.9.24" send "su -n" expect "口令:" send "$passwordops02n" interact } elseif {$file1=="ops03"} { spawn luit -encoding gbk ssh dongwm@59.194.82.XX -p 9960 expect 194.168.45.XX send "su -n" expect "口令:" send "$passwordops03n" interact } else { send "参数错误,请输入以下名称:ops01 ops02 ops03n" } 注:这个脚本里面有SSH信任 有根据iptables转发2 switch结构 还是上面的判断,我这里留下2个表达语法:if ...else 没啥可说的^.^
switch -glob -- $file1 { ops01 { spawn luit -encoding gbk ssh dongwm@59.194.82.XX -p 9924expect 194.168.45.XX send "su -n" //设置了不容许root组直接登录 expect "口令:" send "$passwordops01n" interact } ops02 { spawn luit -encoding gbk ssh dongwm@59.194.82.XX -p 9924 expect 194.168.45.XX send "ssh ops@ops04n" expect "192.168.9.24" send "su -n" expect "口令:" send "$passwordops02n" interact }
3 while结构 (顺便break和continue)
dongwm@linux-3qd1:~> cat !$ cat bin/test #!/usr/bin/expect set test 0 while {$test<10} { set test [expr {$test + 1}] if {$test > 7} break if "$test < 3" continue puts "test is $test" } 本来此例去掉break和continue会输出1..9 因为break存在只能输出到7 ,因为continue存在,当test=1,2的时候 不符合要求,直接略过了
4 catch
catch用于捕捉让脚本停止执行的错误的输出:
dongwm@linux-3qd1:~> cat !$
cat bin/test1
#!/usr/bin/expect
proc Error {} {
error "This is a error for test"
}
catch Error test
puts $test
dongwm@linux-3qd1:~> !$
bin/test1
This is a error for test