Home: Perl Programming Help: Beginner:
help a newbie: how to read external hostfile list and execute a scp command to copy to listed hosts??



struct
New User

Feb 27, 2013, 6:36 PM


Views: 576
help a newbie: how to read external hostfile list and execute a scp command to copy to listed hosts??

Hi I'm trying to write up a perl script which puts line string from a file in array and executes it with external command for each iteration.

so far the script can read from external file.
hosts file

Code
myhost1.test.com 
myhost2.test.com


massscp

Code
#!/usr/bin/perl -w 
use strict;
use warnings;

my $file = "hosts";
open (FH, "< $file") or die "Can't open $file for read: $!";
my @lines;
while (<FH>) {
push (@lines, $_);
}
close FH or die "Cannot close $file: $!";

print @lines; # output test


then I would like to execute a scp command to copy local file to the host listed on the list. for example:

scp file/to/trasfer $host:/tmp/

Please guide me.


rovf
Veteran

Feb 28, 2013, 3:12 AM


Views: 563
Re: [struct] help a newbie: how to read external hostfile list and execute a scp command to copy to listed hosts??

First, I would remove the trailing \n from the lines you read, before storing them into @lines:


Code
  chomp; 
push @lines,$_;


An even better alternative would be to just transfer all the lines at once and omitting the push:


Code
open(my $fh,'<',$file) # This is the preferable way to use 'open' 
or die "....";
my @lines = map {chomp;$_} (<$fh>);
close $fh;


Of course the question is, *why* you need the content of the file stored in an array. Do you need it repeatedly? If you only need it for the scp, the array is unnecessary.

For running scp, you have two choices:

my $exitcode_and_errorcode=system("scp ....");

my $output=qx(scp ... 2>&1);

In the latter case, you get the output stored in a file. In the former one, the output goes to stdout/stderr.


FishMonger
Veteran / Moderator

Feb 28, 2013, 6:47 AM


Views: 557
Re: [rovf] help a newbie: how to read external hostfile list and execute a scp command to copy to listed hosts??

Here are 2 other options for reading the file into an array. We would need to benchmark all of them to be sure, but I believe these are more efficient than the other options.


Code
my @lines = <$fh>; 
chomp @lines;

# or we could combine the statements
chomp(my @lines = <$fh>);



Code
use File::Slurp; 

my @lines = read_file( 'filename' { chomp => 1 } );


There are more than the 2 suggested choices for doing the scp.

You could use IPC::Run or one of its brothers, like IPC::Open2 or IPC::Open3. Or, you could use Net::SCP.

IPC::Run - system() and background procs w/ piping, redirs, ptys (Unix, Win32)
http://search.cpan.org/~toddr/IPC-Run-0.92/lib/IPC/Run.pm

Net::SCP - Perl extension for secure copy protocol
http://search.cpan.org/~ivan/Net-SCP-0.08/SCP.pm

Personally, I think I'd use Net::SCP because I like its OO interface more than the other options.