Linux Expect 用法

Linux Expect 用法

1. 基本介绍

expect是建立在tcl基础上的一个自动化交互套件, 在一些需要交互输入指令的场景下, 可通过脚本设置自动进行交互通信. 其交互流程是:

spawn启动指定进程 -> expect获取指定关键字 -> send想指定进程发送指定指令 -> 执行完成, 退出.

2. 安装expect工具

在ubuntu1804 上安装

sudo apt install expect -y

查看expect的安装路径:

~ command -v expect
/usr/bin/expect

3. expect的常用命令

命 令 说 明
spawn 启动新的交互进程, 后面跟命令或者指定程序
expect 从进程中接收信息, 如果匹配成功, 就执行expect后的动作
send 向进程发送字符串
send exp_send 用于发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的echo
interact 允许用户交互
exit 退出expect脚本
eof expect执行结束, 退出
set 定义变量
puts 输出变量
set timeout 设置超时时间

4. 脚本使用示例

这里以ssh远程登录某台服务器的脚本为例进行说明, 假设此脚本名称为remote_login.sh:

#!/usr/bin/expect
set timeout 30
spawn ssh -l root 172.16.22.131
expect "password*"
send "123456\r"
interact

interact
expect执行完成后保持用户的交互状态, 这个时候用户就可以手工操作了.
如果没有这一句, expect执行完成后就会退出脚本刚刚远程登录过去的终端, 用户也就不能继续操作了.

直接通过expect执行多条命令

#!/usr/bin/expect -f
set timeout 10
# 切换到root用户, 然后执行ls和df命令:
spawn su - root
expect "Password*"
send "123456\r"
expect "]*" # 通配符
send "ls\r"
expect "#*" # 通配符的另一种形式
send "df -Th\r"
send "exit\r" # 退出spawn开启的进程
expect eof # 退出此expect交互程序

通过shell调用expect执行多条命令
注意首行内容, 这种情况下可通过sh script.sh、bash script.sh 或./script.sh, 都可以执行这类脚本:

#!/bin/bash
ip="172.16.22.131"
username="root"
password="123456"
# 指定执行引擎
/usr/bin/expect <<EOF
set time 30
spawn ssh $username@$ip df -Th
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$password\r" }
}
expect eof
EOF

https://www.cnblogs.com/saneri/p/10819348.html
http://xstarcd.github.io/wiki/shell/expect.html
http://xstarcd.github.io/wiki/shell/expect_handbook.html
http://xstarcd.github.io/wiki/shell/expect_description.html

posted @   michaelchengjl  阅读(1231)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示