bash - Bash:通过管道进行进程的相互交互
问题描述
环境: Linux/Docker,bash 4.2 版。
问题:
server-app
接受带有交互式 shell 的命令。server-app
client.sh
通过管道接收来自 a 的命令。server-app
写入由 接收的标准输出client.sh
。client.sh
考虑server-app
的输出以确定进一步的命令。server-app
可能还要求输入密码 => 也就是说,终端的标准输入必须server-app
与client.sh
.
我尝试了多种设置coproc
。但是,我要么陷入停滞状态,要么没有收到数据。如何实现如下所示的设置bash
?
.------>------------------------.
.---------. | .------------. stdin | .-----------.
| user |-------' | server-app |<-------+-------| client.sh |
| console |<--+-------------| | .--------->| |
'---------' | stdout '------------' | '-----------'
'--------------------------------'
我的尝试:
coproc server.app
function expect { local expectation=$1
# read from pipe until $expectation occurs in the input stream
# when found, echo the line to 'stdout'
echo "EXPECT: '$expectation'"
while true; do
read text <&"${COPROC[0]}"
if [[ "$text" == *"$expectation"* ]]; then
echo $text
break
fi
done
}
function send { local command=$1
# send $command through pipe
echo "SEND: $command"
echo "$command" >&"${COPROC[1]}"
}
expect "Conected to URL"
send "open"
expect "Session keepalive"
send "session open"
# use the reported session identifier to setup the user command
session_n=$(expect "Identifier of Session created" | cut -d' ' -f5)
command=$(echo "$user_command" | sed -e "s/SESSION/$session_n/g")
最后三行仅演示了对server-app
' 输出的可能处理。这又有什么问题呢?怎么可能带去上班。
解决方案
正如@sexpect 所提到的,“自然”的方式是解决问题的期望。该工具将基于 Tcl 的脚本作为输入。
spawn server-app
将开始在server-app
期望的控制之下。expect
也是这些脚本中的关键字。
expect -re "something (..)"
等待与表达式匹配的输出something (..)
。
send ...
向应用程序发送一些字符。
expect_tty ...
从启动期望脚本的用户那里获取一些输入。
推荐阅读
- python - 如何在带有循环的星星框中打印文本
- ios - 上传应用程序更新时无法选择构建
- ios - 减小 SpriteKit 节点的大小
- c++ - c++ std::bad_alloc on std::filesystem::path append
- excel - 声明良好时出现错误“需要对象”
- c - 为什么C中的字符串数组在开头存储了一个空元素?
- codesys - Codesys 和 CANopen 多节点 ID
- python - 删除与数组中的元素不匹配的行
- excel - 如何在 VBA 中动态生成和填充列表框?
- java - Androids代码优化中SharedPreferences“commit()”会自动改成“apply()”吗?