expect
是Linux的自动化交互程序;expect
从其余的交互式程序指望(expect)输出,同时对所指望的输出作出相应。shell
下面经过一段代码来讲明expect
经常使用的命令。如今咱们想经过ssh
命令远程登陆一台机器, 同时在远程主机上执行命令ls
。代码以下ssh
1 #! /usr/bin/expect 2 set timeout 20 3 4 send_user "请输入用户名:\n" 5 expect_user -re "(.*)\n" 6 set username $expect_out(1,string) 7 8 send_user "请输入主机名或IP:\n" 9 expect_user -re "(.*)\n" 10 set host $expect_out(1,string) 11 12 stty -echo 13 send_user "请输入密码:\n" 14 expect_user -re "(.*)\n" 15 set password $expect_out(1,string) 16 stty echo 17 18 spawn ssh $username@$host 19 expect { 20 "*password" {send "$password\n";exp_continue} 21 "#" {send "ls\n"} 22 "timeout" {send_user "登陆远程主机$username@$host超时!";exit} 23 } 24 interact
第1行#! /usr/bin/expect
指明脚本的解释器,不一样的系统略有不一样;第二行set timeout 20
设置命令expect
的超时时间,单位为秒;第4~6行提示用户输入用户名,并将用户的输入存储在变量username
中;第8~10提示用户输入主机或IP地址,并将用户的输入存储到变量host
;第12~16行提示用户输入密码,并将用户的输入存储到变量password
;第18行开启一个进程用于执行命令ssh $username@$host
;第19~23行和命令ssh $username@$host
交互;第24行将交互交给用户。spa