Linux Expect 使用样例

Linux Expect 使用样例

Expect介绍

我们通过Shell脚本可以实现简单的控制流功能,如:循环、判断等,对于需要交互的场合则必须通过人工来干预,有时候我们可能会需要实现和交互程序如telnet服务器等进行交互的功能,expect就是用来实现这种功能的工具。

Expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预。Expect的作者Don Libes在1990年开始编写Expect时对Expect做有如下定义:Expect是一个用来实现自动交互功能的软件套件 (Expect [is a] software suite for automating interactive tools)。使用它系统管理员 的可以创建脚本用来实现对命令或程序提供输入,而这些命令和程序是期望从终端(terminal)得到输入,一般来说这些输入都需要手工输入进行的。 Expect则可以根据程序的提示模拟标准输入提供给程序需要的输入来实现交互程序执行。甚至可以实现实现简单的BBS聊天机器人。

Expect是不断发展的,随着时间的流逝,其功能越来越强大,已经成为系统管理员的的一个强大助手。Expect需要Tcl编程语言的支持,要在系统上运行Expect必须首先安装Tcl。

expect自动交互流程:
spawn启动指定进程—expect获取指定关键字—send向指定程序发送指定字符—执行完成退出。

Expect样例

如下样例脚本,可自动ssh登录到指定主机,并执行命令

#!/usr/bin/expect
set timeout 20

if { [llength $argv] < 3} {
puts “Usage: $argv0 ip username pass”
exit 1
}

set ip [lindex $argv 0]
set username [lindex $argv 1]
set des_pass [lindex $argv 2]

–spawn启动指定进程
spawn ssh u s e r n a m e @ username@ username@ip

–expect获取指定关键字
expect "Password: "

–send向指定程序发送指定字符
send “$des_pass\r”

–input your command line here, like the following examples
expect “%”
send “ls -l\r”
#expect “%”
#send “cd /app/aijh/audit_proc_monitor\r”
#expect “%”
#send “sh start_deamonnew.sh\r”

expect “%”
send “exit\r”

猜你喜欢

转载自blog.csdn.net/weixin_43182179/article/details/114602145
今日推荐