【发布时间】: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 模块来运行本地命令?使用
system或IPC::Run或IPC::Open2会不会更容易?对于 ssh 命令,我会使用其中一个 SSH 模块而不是 Expect。 -
@RonBergin 另外,我将看看 perl 的 ssh。我是 perl 新手,甚至没有意识到它有这样的模块。