注销后 Perl expect 不工作

Perl expect doesn't work after logout

连接服务器的非常简单的代码,运行 一些命令,断开连接和 运行 一些本地命令。

#!/usr/bin/perl

use strict;
use warnings;

use Expect;

my $timeout = 15;
my $password = "1234";

my $expect = new Expect;
$expect->raw_pty(1);
$expect->spawn("bash\n");

$expect->send("echo run some initial commands locally\n");   # edit: added this line

$expect->send("ssh 1.2.3.4\n");
$expect->expect($timeout,
                [   qr/password/,
                    sub {
                        $expect->send("$password\n");
                    }
                ]
                );
$expect->expect($timeout, [ qr/prompt/ ] );

$expect->send("echo run some commands on the server\n");

$expect->send("exit\n");   # disconnect from the server

$expect->send("echo run some more commands locally\n");

$expect->send("exit\n");   # exit bash
$expect->soft_close();

此代码在第一个 exit 命令之前一直有效。它与服务器断开连接,但随后整个脚本似乎冻结了。没有执行其他命令,我必须按 Ctrl+C 或等到超时。

编辑:当我在本地执行命令时它工作,当我远程执行一些命令时它工作,然后我想 return 在本地工作但我不能。

此外,我想对嵌套的 ssh 做同样的事情 - 连接到一台服务器,从它连接到另一台等等......然后处理所有这些。

我做错了什么?我怎样才能达到预期的行为?

显然就在 $expect->send("exit\n"); 之后,脚本仍在尝试向远程服务器发送消息或向任何人发送消息(因为它正在断开连接)。解决方案是将 expect 与来自本地服务器的提示文本一起使用( 但请确保使用仅匹配本地提示而不匹配远程提示的模式!):

$expect->expect($timeout, [ qr/local_prompt/ ] );

或使用某种延迟(send_slow、某种睡眠等...)。