Perl 期望执行命令的输出
我写了一个执行 ls 命令的小脚本。现在我想将该命令的输出存储在一个变量中,以便在进一步的 perl 脚本中使用它。不幸的是我无法获取 ls 命令的输出。
my ($core) = "servername";
my $tel_con = "ssh ".$core. " -l $user";
$ssh = Expect->spawn("$tel_con");
$ssh->log_stdout(1);
unless ( $ssh->expect( 5, -re => '$' ) ) {
return "Never connected " . $ssh->exp_error() . "\n";
}
sleep 1;
$ssh->send_slow(0, "ls -l\r");
$ssh->clear_accum();
my $str = $ssh->exp_after();
print "STR = '$str'\n";
也许你可以给我一些帮助?
i wrote a little script which executes the ls command. Now I want to store the output of that command in a variable to work with it in the further perl script. Unfortunately I cannot grab the output from the ls command.
my ($core) = "servername";
my $tel_con = "ssh ".$core. " -l $user";
$ssh = Expect->spawn("$tel_con");
$ssh->log_stdout(1);
unless ( $ssh->expect( 5, -re => '
Maybe you can give me some help please?
) ) {
return "Never connected " . $ssh->exp_error() . "\n";
}
sleep 1;
$ssh->send_slow(0, "ls -l\r");
$ssh->clear_accum();
my $str = $ssh->exp_after();
print "STR = '$str'\n";
Maybe you can give me some help please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您不能或不想使用 Net::OpenSSH 您可以这样做:
获取整个输出(包括使用的命令、返回字符串、控制台信息)
In case you can not or don't want to use Net::OpenSSH you may do:
To get the whole output (including the used command, return string, console information)
您可以在单独的进程中调用 Expect 并通过 qx 获取输出或打开管道
you could call expect in a seperate process and grab the output via qx or open a pipe
什么是send_slow?根据此命令发送 ls 命令的方式,可以通过不同的方式接收输出。
最有可能的是,命令的错误输出存储在 $?变量,可能是字节移位的。
What is send_slow? Depending on how this command sends the ls command, the output can be received in different ways.
Most probably, the error output of the command is stored in the $? variable, possibly byte-shifted.
看起来 Expect 会将所有内容重定向到 STDOUT 并在内部记录它。由于您使用
$ssh->log_stdout(1)
启用了输出,因此您应该能够直接从STDOUT
获取ls -l
的结果> (也许通过将标准输出重定向到变量)。您还可以看到尝试从内部日志记录中获取数据。只需确保在执行clear_accum()
之前获取输出即可。来自CPAN:
$object->send_slow($延迟,@strings);
It seems that Expect will redirect everything to
STDOUT
and log it internally. Since you enabled output with$ssh->log_stdout(1)
, you should be able to get the results ofls -l
directly fromSTDOUT
(maybe by redirecting standard out to a variable). You can also see try grab the data from the internal logging. Just make sure to grab the output before doingclear_accum()
.From CPAN:
$object->send_slow($delay, @strings);
外行术语?
我必须强制发布此链接 - 我仍然时不时地去那里,这是我发现的所有正则表达式的最外行的解释:
http://www.anaesthetist.com/mnm/perl/Findex.htm
Layman's terms?
I must obligatorily post this link - I still go there from time-to-time, it is the most layman-y explanation I've ever found of all things regex:
http://www.anaesthetist.com/mnm/perl/Findex.htm