Linux 命令--expect自动化交互程序
文章目录
expect是Linux的自动化交互程序;expect从其他的交互式程序期望(expect)输出,同时对所期望的输出做出相应。
下面通过一段代码来说明expect常用的命令。现在我们想通过ssh命令远程登录一台机器, 同时在远程主机上执行命令ls。代码如下
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行将交互交给用户。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论