expect是一款Linux下的自动化交互程序;expect期待(expect)其他交互程序的输出,同时响应预期的输出。下面用一段代码来说明expect的常用命令。现在我们要通过ssh命令远程登录一台机器,同时在远程主机上执行命令ls。代码如下1#!/usr/bin/expect2settimeout2034send_user"请输入用户名:\n"5expect_user-re"(.*)\n"6setusername$expect_out(1,string)78send_user"请输入主机名或IP:\n"9expect_user-re"(.*)\n"10sethost$expect_out(1,string)1112stty-echo13send_user"请输入密码:\n"14expect_user-re"(.*)\n"15setpassword$expect_out(1,string)16sttyecho1718spawnssh$username@$host19expect{20"*password"{send"$password\n";exp_continue}21"#"{send"ls\n"}22"timeout"{send_user"登录到远程主机$username@$host超时!";exit}23}24interactline1#!/usr/bin/expect表示脚本的解释器,不同的系统略有不同;第二行settimeout20设置命令expect的超时时间,单位秒;第4~6行提示用户输入用户名,并将用户的输入存储在变量username中;第8-10行提示用户输入主机或IP地址,并将用户的输入存储在变量host中;第12-16行提示用户输入密码,并将用户的输入存储在变量password中;第18行开启了一个进程,用于执行命令ssh$username@$host;第19-23行与命令ssh$username@$host交互;第24行将交互交给用户。
