taoCMS是基于php+sqlite/mysql的国内最小(100Kb左右)的功能完善、开源免费的CMS管理系统

linux expect例子教程

2015-06-27

本文主要介绍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转发

if ...else 没啥可说的^.^

2 switch结构 还是上面的判断,我这里留下2个表达语法:
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	

类别:未分组 | 阅读:207833 | 评论:556 | 标签:linux expect

想收藏或者和大家分享这篇好文章→

“linux expect例子教程”共有0条留言

发表评论

姓名:

邮箱:

网址:

验证码:

公告

taoCMS发布taoCMS 3.0.2(最后更新21年03月15日),请大家速速升级,欢迎大家试用和提出您宝贵的意见建议。

捐助与联系

☟请使用新浪微博联系我☟

☟在github上follow我☟

标签云