# 简介 `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`,内容如下: ```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 ``` 执行效果如下图所示: ![image](../../../../ff_internal_upload/img/2025/image-20251029145637071.png) # 参考 - [Linux expect 命令实战:附带实用示例](https://labex.io/zh/tutorials/linux-linux-expect-command-with-practical-examples-422669)