无法使用 Net::OpenSSH 进行 SSH,可以通过命令行

Can't SSH using Net::OpenSSH, can through command line

这是我第一次使用 Net::OpenSSH,我正在尝试创建一个 SSH for 循环,在其中打印我正在使用 whoami 的服务器的主机名。我可以从命令行通过 SSH 连接到我想要的服务器,但是当我 运行 我的脚本时,我遇到以下错误...

ssh: could not resolve hostname
: Name or service not known
username

为了获得更多信息,我打印了 $ssh->error 的输出,其中 $ssh 是我的 Net::OpenSSH 对象。

unable to establish master SSH connection: bad password or master process exited unexpectedly at line 24, $fh line 1

这是目前的脚本...

#!/usr/bin/perl

 use strict;
 use warnings;
 use Net::OpenSSH;
 my $file = 'servers.txt';
 open (my $fh, $file) or die "Could not open";

 while (my $row = <$fh>) {
   my $user = "username";
   my $password = "password";
   my $ssh = Net::OpenSSH->new(host => $row, user => $user, password => $password);
   $ssh-error and die "SSH connection failed: " . $ssh->error;
   my $whoami = `whoami`;
   print $whoami;
 }

servers.txt 文件是一个纯文本文件,其中包含一个接一个的服务器主机名列表。

我的理解是,如果我可以从命令行 SSH 到这些服务器,问题一定出在脚本上,而不是 servers/network。如果能深入了解我 Net::OpenSSH 无法解析看似可访问的服务器的原因,我们将不胜感激。

"the problem must lie in the script" 是的,我执行的脚本有两个问题。第一个是语法错误。其他评论者已注意到它。

   $ssh-error and die "SSH connection failed: " . $ssh->error;

应该是

   $ssh->error and die "SSH connection failed: " . $ssh->error;

另一个问题来自您尚未展示的脚本版本,其他人也注意到了这一点,即您没有从 $row 中删除结尾的换行符。你这样做

chomp($row)

将其作为 while 块的开始指令执行,您应该可以开始了。

我必须强调在 posting MCV 中格外小心的重要性。在按下该提交按钮之前,将 post 中的代码复制到一个临时文件并执行它,这样您就会收到更少的响应者投诉。

顺便说一下,一个可能让你自己解决问题的良好调试习惯是在执行 Net::OpenSSH->new

之前添加这一行
print STDERR ";$row;\n" if $debugging;  # or something to this effect

如果你这样做了,你就会在 STDERR 上看到类似的东西

;myhost
;

此外,您正在使用的模块在其 pod 中提到了一个不错的调试功能。调试输出不太容易解释,但如果您不知道问题出在哪里,那么您可以从那里开始。如果你添加了这一行

$Net::OpenSSH::debug = 8;

那么你会在 STDERR 上看到这个

$ cat servers.txt
localhostx
$ perl x.pl
...
ssh: Could not resolve hostname localhostx
: nodename nor servname provided, or not known

如果您调用了 chomp 但主机名确实不存在,它会看起来像这样

ssh: Could not resolve hostname localhostx: nodename nor servname provided, or not known