Noosrep
Noosrep

Reputation: 416

Find hostname of remote server through ssh in perl

I have an array which contains a series of IPs. Now i'm trying to connect to those IPs through ssh and echo their hostname. I came accross this Stackoverflow answer but didn't get much info out of it. This is what I've got:

#!/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`";
}

but I get following error:

Can't use string ("IP") as an ARRAY ref while "strict refs" in use at

When I remove use strict; the error is also removed, but the code still doesn't work


edit: the \@ did the trick of removing the error but now it just prints

`ssh [email protected]` `hostname` 

while it should print just the hostname

Upvotes: 0

Views: 1115

Answers (3)

FrankH
FrankH

Reputation: 1

Your print has too many quotes to execute the ssh command. Try

 print `ssh host\@$ip hostname \n`;

or

system "ssh host\@$ip hostname \n";

Finally, "host" must be a valid user on the remote machine. The syntax for ssh is

ssh user@remote-host

Upvotes: 0

rje
rje

Reputation: 6418

The syntax

@$ip

In your print statement is interpreted as an array reference. That is what caused the error.

Try escaping:

"...host\@$ip..."

Furthermore, you can use backticks to execute a command and capture the output

`ssh [email protected] hostname`

But you have surrounded the backticks with quotes, rendering them useless.. I think you want to remove the quotes.

Upvotes: 5

Rob K
Rob K

Reputation: 8926

@$ip in the print statement is your problem. Try changing to \@$ip.

Upvotes: 2

Related Questions