expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。
expect自动交互流程:
spawn启动指定进程—-expect获取指定关键字—-send向指定程序发送指定字符—-执行完成退出.
安装
查看提供expect的rpm包yum provides expect直接通过yum安装yum install -y expect查看expect程序安装的位置which expectspawn 交互程序开始后面跟命令或者指定程序expect 获取匹配信息匹配成功则执行expect后面的程序动作send exp_send 用于发送指定的字符串信息exp_continue 在expect中多次匹配就需要用到send_user 用来打印输出 相当于shell中的echoexit 退出expect脚本eof expect执行结束 退出set 定义变量puts 输出变量set timeout 设置超时时间[root@localhost ~]# cat connectmysql.sh#!/usr/bin/expect -fset pswd MyNewPass4!spawn mysql -uroot -pset timeout 300expect "Enter password:"send "$pswd\r"interact[root@localhost ~]# ./connectmysql.shspawn mysql -uroot -pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 11Server version: 5.7.33 MySQL Community Server (GPL)Copyright (c) 2000, 2021, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql>
