gpt4 book ai didi

linux - perl远程执行错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:27:14 26 4
gpt4 key购买 nike

在下面的代码中,我尝试使用 Perl 脚本将 git 存储库克隆到另一台机器。

如果我打印 $output,我会得到所有登录消息,即 /etc/motd/ 的内容,但不是实际的命令输出。

如何解决这个问题?我在执行 ssh 命令时做错了什么吗?

    sub myexec_remote    
{
my($cmd, $hostname, $filename) = @_;

my $stdout = $stderr = $exit= "";
my ($output) = `ssh $hostname $cmd 2>&1`;
## this is the command i.e, executed
##command is ssh 111.22.11.32 "git clone --bare gt@l.com:/nfs/git/ /nfs/new123/"
$exit = $?;
if (defined $output)
{
open(MYOUTFILE, ">$filename");
print MYOUTFILE "$output";
close(MYOUTFILE);
}

}

我使用反引号是因为有时 ssh 没有无密码并且我已经看到 NET:SSH 模块不支持它...

最佳答案

这是因为你使用了backticks operator 在列表上下文中:

my ($output) = `ssh $hostname $cmd 2>&1`;

在列表上下文中调用时,反引号将返回行列表。您只捕获第一行,并将其放入 $output。其他行被忽略。来自 perldoc perlop:

In scalar context, it comes back as a single (potentially multi-line) string, or undef if the command failed. In list context, returns a list of lines (however you've defined lines with $/ or $INPUT_RECORD_SEPARATOR), or an empty list if the command failed.

解决方案:

1. my $output = `ssh $hostname $cmd 2>&1`;

在标量上下文中调用反引号将导致 $output 成为多行字符串。

2. my @output = `ssh $hostname $cmd 2>&1`;

您可以在数组上下文中调用反引号,但稍后您必须将整个数组打印到 MYOUTPUTFILE

其他评论:

这些不是解决方案的一部分。解决方案本身应该足以修复您的错误。但是,它们可以降低出现错误的风险,并增加您的 Perl 知识。

  1. 尝试使用 open 的三个参数版本,而不是全局的两个参数,并在无法打开文件时捕获错误:

    open(my $handle, '>', $filename) or die "无法打开文件,$!";

  2. 许多人决定使用 IPC::System::Simple而不是反引号,因为当出现问题时您可以获得更多信息并且可以避免 shell。

  3. 另一个选项是 IPC::Open3 ,它甚至可以让您轻松捕获 STDOUT、STDERR 和退出代码。不过使用起来有点困难。

关于linux - perl远程执行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9799745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com