如何通过 ssh 运行 期望来自远程服务器的脚本?

How to run expect script from remote server via ssh?

我已经在远程服务器上部署了一个 expect 脚本,我想通过 ssh 运行。

ssh user@host 'expect -d ./netopeer_expect.sh' (1)

user@host:~$ cat netopeer_expect.sh
#!/usr/bin/expect

set timeout 5
#spawn netopeer2-cli
spawn ./np2_multi_cli
expect ">"
send "listen --timeout 120\r"
expect "ru_id 0"
send "get-config -D=0 --source running --out /home/user/out.xml\r"
expect ">"
send "exit\r"
expect "$"

此代码 运行 是 netopeer2-cli 的修改版本,我们称之为 ./np2_multi_cli。这个 netopeer2-cli 有一个自己的 shell 和一个类似 > 的提示符。当我分两步完成时效果很好

ssh user@host
expect -d ./netopeer_expect.sh (2)

但是,消息

send "get-config -D=0 --source running --out /home/user/out.xml\r"

被剪切并发送为,

send "-D=0 --source running --out /home/user/out.xml\r"

来自 运行ning (1) 和 -d 参数我看到了这个,

expect: does "\u001b[6n" (spawn_id exp3) match glob pattern ">"? no

当我尝试匹配第一个 > 时。当我改为尝试 运行 (2) 时,它看起来应该是

expect: does "> " (spawn_id exp4) match glob pattern ">"? yes

I 运行 bash 似乎关于 > 字符存在一些编码问题。知道如何处理这个吗?

BR 帕特里克

看起来好像我在 运行 ssh 时调用错误。我强制伪终端分配一切顺利,

ssh -t -t erusim@147.214.83.188 'expect -d ./netopeer_expect.sh'

做了一些调查,发现 ssh -t 产生影响的原因。请参阅以下示例:

根据预期manual

Internally, spawn uses a pty, initialized the same way as the user's tty.

使用 -t,ssh 会为远程会话分配一个 pty(与本地 $TERM 相同的类型),然后 expect 分配一个相同类型的 pty。

如果没有 -t,ssh 将不会为远程会话分配 pty,并且 expect 使用(默认?)dumb tty 功能不全。作为 "workaround",我们可以在 spawn.

之前明确设置 TERM 变量(例如 set env(TERM) vt100

这是我使用的命令。只是为了简单 copy-and-paste.

[STEP 101] # cmd=' "spawn -noe bash -c {echo TERM=$TERM | grep --color TERM}; expect eof" '
[STEP 102] #
[STEP 103] # ssh 127.0.0.1 expect -c "$cmd"
TERM=dumb
[STEP 104] # ssh -t 127.0.0.1 expect -c "$cmd"
TERM=linux
Connection to 127.0.0.1 closed.
[STEP 105] #
[STEP 106] # cmd=' "set env(TERM) vt100; spawn -noe bash -c {echo TERM=$TERM | grep --color TERM}; expect eof" '
[STEP 107] # ssh 127.0.0.1 expect -c "$cmd"
TERM=vt100
[STEP 108] #