python - 如何读取expect脚本中的send命令输出

标签 python bash expect sys

我有一个期望脚本,它将登录到远程服务器并执行 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

最佳答案

这是您需要在提示之前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 将输出缓冲到 expect_out 数组中,数组键 1,string (注意,那里没有空格)包含以下内容正则表达式模式的第一个捕获括号

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

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

关于python - 如何读取expect脚本中的send命令输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57975853/

相关文章:

python - 方法的 "self"参数是否受到某种保护?

python - pygame key.set_repeat 不工作

python - 从数据样本计算逆 CDF

bash - 无法让 ASCII 艺术回显到控制台

linux - 如何在循环中附加到 screen session ?

regex - 用于多个搜索的 sed 正则表达式语法

bash - 我如何使用Expect通过ssh连接到系统并更改主机系统的密码?

tcl - 如何从 tcl/tk 生成应用程序,使其独立于父应用程序?

使用 DAL 的 python app engine restful 服务

预期脚本 : How to provide default values if arguments are not passed