2

连接服务器、运行一些命令、断开连接并在本地运行更多命令的非常简单的代码。

#!/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 或等到它超时。

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

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

我究竟做错了什么?我怎样才能实现所需的行为?

4

1 回答 1

2

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

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

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

于 2015-05-08T13:14:53.913 回答