实现自动交互功能Expect

2024-2-1 19:48 wsl Ansible自动化 阅读量:576

一、expect的安装 

# yum -y install expect
 

二 、expect的语法

        expect是一个免费的编程工具, 用来实现自动的交互式任务 , 而无需人为干预. 说白了 expect 就是一套用来实现自动交互功能的软件  

        在实际工作中我们运行命令、脚本或程序时, 这些命令、脚本或程序都需要从终端输入某些继续运行的指令,而这些输 入都需要人为的手工进行. 
而利用 expect 则可以根据程序的提示 , 模拟标准输入提供给程序, 从而实现自动化交互执 行. 这就是 expect 
 
        能够在工作中熟练的使用Shell脚本就可以很大程度的提高工作效率, 如果再搭配上expect ,那么很多工作都可以自动化 进行 ,对工作的展开如虎添翼 
 
用法: 
1)定义脚本执行的shell
# !/usr/bin/expect 类似于#!/bin/bash 
 
2)set timeout 30
设置超时时间30s 
 
3)spawn
spawn是进入expect环境后才能执行的内部命令,不能直接在默认的shell环境中执行 
功能:传递交互命令
 
4)expect 
这里的expect同样是expect命令
功能:判断输出结果是否包含某项字符串 ,没有则立即返回,否则等待一段时间后返回,等待通过timeout设置 
 
5)send
执行交互动作 ,将交互要执行的动作进行输入给交互指令 
命令字符串结尾要加上“r”,如果出现异常等待状态可以进行核查
 
6)interact 
执行完后保持交互状态,把控制权交给控制台 
如果不加这一项 ,交互完成会自动退出
 
7)exp_continue 
继续执行接下来的操作
 
在expect中定义变量
set    key   vault
 
举例1:自动登录测试
#! /usr/bin/expect
set user "root"
set password "123"
set ip "192.168.58.11"
spawn ssh $user@$ip
expect {
   "yes/no" { send "yes\r";exp_continue }
   "password:" { send "$password\r" }
}
interact        #切换终端
 
举例2:生成密钥
# ! /usr/bin/expect
spawn ssh-keygen
expect {
   "which to save the key" { send "\r";exp_continue }
   "Overwrite" { send "y\r";exp_continue }
   "empty for no passphrase" { send "\r";exp_continue }
   "same passphrase again" { send "\r";exp_continue }
}
 
设置位置参数的方式 ( 拓展 )
#!/usr/bin/expect
set timeout 30
set user [ lindex $argv 0 ]
set pass [ lindex $argv 1 ]
set ip [ lindex $argv 2 ]
spawn ssh $user@$ip
 
expect {
        "yes/no" { send "yes\r";exp_continue }
        "password:" { send "$pass\r" }
}
interact
 
执行
# ./test.sh root 123 192.168.58.11
 
 
在其他脚本调用expect
 
#! /usr/bin/bash
/usr/bin/expect <<-EOF
spawn ssh-keygen
expect {
   "which to save the key" { send "\r";exp_continue }
   "Overwrite" { send "y\r";exp_continue }
   "empty for no passphrase" { send "\r";exp_continue }
   "same passphrase again" { send "\r";exp_continue }
}
EOF
 
 
 
 
版权所有:
文章标题:实现自动交互功能Expect
文章链接:https://www.51itlab.net/?post=91
本站文章均为原创,未经授权请勿用于任何商业用途

热门标签