Liunx expect 基础

#################################################

a script for study except

#################################################

#!/usr/bin/expect

声明文件内的语法使用 expect 的语法来执行。

send

send: 向进程发送字符串,用于模拟用户的输入。注意要加 \n 回车

expect

expect: 从 shell 进程接收字符串, " " 表示提示框里面的内容
expect {},多行期望,匹配到哪条执行哪条

spawn

spawn: 启动进程 (由 spawn 启动的进程的输出可以被 expect 所捕获)。

spawn ssh $user@10.10.10.10

spawn 启动一个进程,进程执行 ssh 命令,程序后面可以通过 expect/send 和新起的进程进行交互。

set 变量赋值

set timeout 60: 设置相应的时间,如果脚本执行或者网络问题超过了这个时间将不执行
set user "arlen"

set 嵌套命令

set user [lindex $argv 0]
set password [lindex $argv 1]

把命令行第一个参数赋给 user,第二个参数赋给 password 。

puts 输入输出

puts stderr "Usage: $argv0 login passwaord.n "
puts "hello world"
puts stdout "1234"

命令行参数

$argc$argv 0,$argv 1 ... $argv n

argc 表示命令行参数个数,后面分别表示各个参数项,0 表示第一个参数,1 表示第二个参数,以此类推,可以通过 lindex 获取对应参数值 (lindex $argv 0)。

llength argv 表示参数的个数, argv0 表示脚本的名称

if

if 判断需要用 {} 括起来, 并且与 {} 之间需要有空格。
else / elseif 不能单独放一行,所以 else / elseif 要跟在 } 后面。
两个花括号之间必须有空格隔开,比如 if {} {}。
使用 { 来衔接下一行,所以 if 的条件后需要加左花括号 { 。

grep

grep 到指定字符 $? 返回 0, grep 不到指定字符 $? 返回 1 。

函数定义和调用

proc do_console_login {login pass} { 

}

do_console_login $user $password

循环

while ($done) { 

}

条件分支 switch

switch -- $var { 

0 {

}

1 {

}

2 {

}

}

示例:

#!/usr/bin/expect

set timeout 60
set remote_host [lindex $argv 0]
set type [lindex $argv 1]
set target "output-0"
set invalid "output-1"

spawn ssh -o "no" $remote_host
set chan [open ansible.log a]
expect {
"$" {
send "sudo systemctl status ***.service | grep'active (running)'>&null; echo output-$?\n"
}
timeout {
puts "could not connect to $remote_host!"
exit 1
}
}
expect {
"output-0" {
puts $chan "***.service is ok"
}
"output-1" {

            puts <span class="hljs-string">"***.service is inactive!!!"</span>
            send <span class="hljs-string">"exit"</span>
            <span class="hljs-built_in">exit</span> 1
    }

timeout {

      puts <span class="hljs-string">"***.service service status is wrong(Timeout)!"</span>
      send <span class="hljs-string">"exit"</span>
      <span class="hljs-built_in">exit</span> 1
    }

}

if { "$type" == "***" } {
send "sudo systemctl status ***.service | grep'active (running)'>&null; echo output-$?\n"
expect {
"output-0" {
puts $chan "$type ***.service is ok !\n"
}
"output-1" {
puts "$type ***.service is wrong !\n"
exit 1
}
timeout {
puts "$type status is wrong(Timeout) !\n"
exit 1
}
}
} elseif { "$type" == "***" } {
send "sudo systemctl status ***.service | grep'active (running)'>&null; echo output-$?\n"
expect {
"output-0" {
puts $chan "$type ***.service is ok !\n"
}
"output-1" {
puts "$type ***.service is wrong !\n"
exit 1
}
timeout {
puts "$type status is wrong(Timeout) !\n"
exit 1
}
}
} else {
puts "it is not in these types"
exit 1
}
puts $chan "$type check service is done!!!"
exit 0

参考文章:

linux 下 expect 使用教程: http://www.cnblogs.com/arlenhou/p/learn_expect.html