【问题标题】:Perl expect doesn't work after logout注销后 Perl 期望不起作用
【发布时间】:2017-09-05 23:03:28
【问题描述】:

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

#!/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 做同样的事情 - 连接到一台服务器,从它连接到另一台服务器等等......然后处理所有这些。

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

【问题讨论】:

  • 看起来您在断开连接后尝试向服务器发送命令。我不指望这会做很多事情。
  • 至于为什么会挂起,可能是超时如何实现的问题。你运行的是什么操作系统?
  • 我的第一个问题是为什么要使用 Expect 模块来运行本地命令?使用systemIPC::RunIPC::Open2 会不会更容易?对于 ssh 命令,我会使用其中一个 SSH 模块而不是 Expect。
  • @RonBergin 另外,我将看看 perl 的 ssh。我是 perl 新手,甚至没有意识到它有这样的模块。

标签: perl ssh expect.pm


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2017-02-19
    • 1970-01-01
    • 2013-06-17
    • 2021-07-09
    • 2021-11-20
    • 2016-05-14
    • 2017-01-07
    • 2012-06-19
    • 2018-06-09
    相关资源
    最近更新 更多