使用expect实现交互式输入
简介
expect是一款基于Tcl语言的自动化交互工具,由Don Libes于 1990 年开发,主要用于模拟终端输入以实现无需人工干预的交互式任务。其核心功能包括通过脚本自动化处理 SSH 登录、FTP 传输、密码修改等需要人工响应的场景。
核心命令
spawn:启动交互进程(如ssh user@host)expect:等待进程输出的特定模式(如"password:")-
send:向进程发送输入字符串(如密码"your_password\r") -
interact:允许用户手动接管进程交互
安装
expect不是默认安装的,如果是Redhat系统,请安装:
sudo yum install expect
实例
使用expect实现psql交互式执行。
完成交互式操作:psql登录用户user1,数据库为test,用户需要输入密码。登录成功后,显示"max_connections"参数值,最后退出psql客户端。
编写expect脚本,假设脚本文件为psql_login.exp,内容如下:
- snippet.bash
#!/usr/bin/expect set timeout 10 spawn psql -d test -U user1 expect "Password for user user1:" send "ABC\r" expect "test=>" send "show max_connections;\r" expect "test=>" send "\\q\r" expect eof
执行脚本:
expect ./psql_login.exp
执行效果如下图所示:
参考
打赏作者以资鼓励:
![]() | ![]() |


