通过perl中的ssh查找远程服务器的主机名

Noo*_*rep 0 ssh perl

我有一个包含一系列IP的数组.现在我正在尝试通过ssh连接到这些IP并回显它们的主机名.我遇到了这个Stackoverflow的答案,但没有得到太多的信息.这就是我所拥有的:

#!/usr/bin/perl
use warnings;
use strict;
use Term::ANSIColor;
print colored( "Number of machines: \n", 'green' );
my $number = <>;

my @arr = ();
my $ip = 0;
while (@arr < $number) {
        print colored( "\nIP Address: \n", 'green' );
        my $IP = <STDIN>;
        chomp $IP;
        push @arr, $IP;
}


print colored( "this is the hostname:\n", 'green' ); foreach $ip (@arr) {
        print "`ssh host\@$ip hostname \n`";
}
Run Code Online (Sandbox Code Playgroud)

但我得到以下错误:

Can't use string ("IP") as an ARRAY ref while "strict refs" in use at
Run Code Online (Sandbox Code Playgroud)

当我删除 use strict; the error is also removed, but the code still doesn't work


编辑:\ @做了删除错误的技巧,但现在它只是打印

`ssh axiroot@172.31.222.135` `hostname` 
Run Code Online (Sandbox Code Playgroud)

而它应该只打印主机名

rje*_*rje 5

语法

@$ip
Run Code Online (Sandbox Code Playgroud)

在您的print语句中被解释为数组引用.这就是导致错误的原因.

尝试转义:

"...host\@$ip..."
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用反引号来执行命令并捕获输出

`ssh bla@example.com hostname`
Run Code Online (Sandbox Code Playgroud)

但你用引号包围了反引号,使它们变得无用......我想你想要删除引号.