rycher has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to run a remote command through a Perl script and then capturing that output to a file on the local system.

This is what I have so far(doesn't work):

open (CSV, ">", $ADDListPresent) or die $!; my @CreateList = ( '/usr/bin/sudo', '-u', 'homer', '/usr/bin/ssh', qq($HomerServer), '/bin/ls', ); system("$CreateList > data/test.txt"); close CSV;

Replies are listed 'Best First'.
Re: Capturing remote command output to a file
by ikegami (Patriarch) on Aug 17, 2009 at 20:10 UTC

    It seems you were trying to use system safely by avoiding the shell by using it's multi-argument form, then abandoned your efforts and introducing other errors in the process. Solutions:

    • # Not portable to Windows sub shell_quote { my ($arg) = @_; $arg =~ s/'/'\\''/g; $arg = "'$arg'"; return $arg; } my $cmd = join ' ', map shell_quote($_), @CreateList; system("$cmd > data/test.txt") and die;
    • open(my $fh_out, '>', 'data/test.txt') or die; open(my $pipe, '|-', @CreateList) or die; print $fh_out $_ while <$pipe>;
    • use IPC::Open2 qw( open2 ); open(my $fh_out, '>', 'data/test.txt') or die; my $pid = open2('>&'.fileno($fh_out), '<&STDIN', @CreateList); waitpid($pid, 0);
Re: Capturing remote command output to a file
by SuicideJunkie (Vicar) on Aug 17, 2009 at 19:49 UTC
    my @CreateList = ...and
    system("$CreateList > data/test.txt");
    Involves two completely different variables, one an array and one a scalar. Did use strict not tell you about that problem?
Re: Capturing remote command output to a file
by josh097 (Initiate) on Aug 17, 2009 at 20:18 UTC
    From what I have read system() only captures the exit code of what you are executing.
    Have you tried backticks (` ` - under the escape key)? Edit: Nvm, I re-read your code. Try:
    system("$CreateList[0] $CreateList[1] $CreateList[2] $CreateList[3] $C +reateList[4] > data/test.txt");
      Duhhhh... Arrays have elements, who woulda thunk? ;-)

      Thanks josh097.

Re: Capturing remote command output to a file
by BioLion (Curate) on Aug 18, 2009 at 08:39 UTC

    Capture::Tiny is also very handy for capturing output from system calls, I asked a similar question a while back and it was the best suggestion made to me then.

    Just a something something...