如何在期望脚本中读取发送命令输出

How to read the send command output in expect script

我有一个 expect 脚本,它将登录到远程服务器并执行 python 脚本。在 python 脚本中,我为特定条件设置了 sys.exit(1) ,以便在满足该条件时停止执行。有没有办法知道 python 脚本是否停止执行或 运行 正常?
(或)有没有办法读取 python 脚本产生的输出(即我想读取 send "python pythonscript.py arg1\r" 的输出)。任何方法都可以。请提出想法

expectscript.exp

#!/usr/bin/expect

eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no user@******
expect "Password:"
send "password\r"
expect "$username$"
set prompt ":|#|\$"
set timeout -1
send "cd /Users/username/Documents/folder/\r"
send "python pythonscript.py arg1\r"
expect $prompt

运行 作为命令

spawn ssh -c "python pythonscript.py arg1"
expect $prompt

尝试对可执行命令使用spawn -c,因为这会取回结果,发送它们会在执行后终止。

这是您需要expect -re捕获提示前输出的地方:

send "cd /Users/username/Documents/folder/\r"
expect $prompt
send "python pythonscript.py arg1\r"
expect -re "(.+)$prompt"
set pythonOutput $expect_out(1,string)

expect buffers输出在expect_out数组中,数组键1,string(注意,没有space那里)包含内容正则表达式模式的第一个捕获括号

另请注意,输出将包含 python 命令,并且行以 \r\n 结尾:因此您可以执行以下操作:

set outputLines [lrange [lmap line [split $pythonOutput \n] {regsub {\r$} $line ""] 1 end]