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

Hi all,

I am new to this forum. I have searched the archive for similar questions but I couldn't get quite.

I have a situation of copying a file to a remote machine. There is a trust established between the two machines and I am supposed to use 'scp' (like `scp local_file remotehost:targetdirectory/remote_file`)

If the targetdirectory does not exist.. the above command fails as, I guess, scp doesn't create directory on a remote machine if it doesn't exist.

So, what I would like to do is to do a test whether the directory exists.. if not, I would have to create one.

How do we make remote file/directory tests between two machines that have trust relationship? Is mkpath() of File::Path capable of doing that?

Thanks in advance.

Replies are listed 'Best First'.
Re: File test on remote machine and mkpath
by almut (Canon) on Sep 05, 2007 at 09:56 UTC

    Not a Perl solution... but I would just use ssh to issue a mkdir on the remote host (or mkdir -p if you need to create intermediate directories, too)

    ssh remotehost mkdir targetdirectory

    (the path is interpreted relative to your remote home/login directory, unless you specify an absolute one)

Re: File test on remote machine and mkpath
by narainhere (Monk) on Sep 05, 2007 at 09:41 UTC
    Hope this snippet would help,
    my $g_cmd="ssh Machinename ls <completefilepath>"; `$g_cmd`; if($?) { print "Error doesnot exist"; } else { $g_cmd="scp local_file remotehost:targetdirectory/remote_file"; `$g_cmd`; }
    if it's a directory you want to test add -d switch to the ls command.

    The world is so big for any individual to conquer

Re: File test on remote machine and mkpath
by casiano (Pilgrim) on Sep 09, 2007 at 13:15 UTC
    An alternative is to use the Module GRID::Machine (version 0.78 or higher, available at CPAN) I've developed. See an example:

    $ cat copyandmkdir.pl #!/usr/local/bin/perl -w use strict; use GRID::Machine; my $host = 'orion.pcg.ull.es'; my $dir = shift || "somedir"; my $file = shift || $0; # By default copy this program my $machine = GRID::Machine->new( host => $host, uses => [qw(Sys::Hostname)], ); my $r; $r = $machine->mkdir($dir, 0777) unless $machine->_w($dir); die "Can't make dir\n" unless $r->ok; $machine->chdir($dir)->ok or die "Can't change dir\n"; $machine->put([$file]) or die "Can't copy file\n"; print "HOST: ",$machine->eval(" hostname ")->result,"\n", "DIR: ",$machine->getcwd->result,"\n", "FILE: ",$machine->glob('*')->result,"\n";
    when running the former example we obtain an output like this:
    $ copyandmkdir.pl HOST: orion DIR: /home/casiano/somedir FILE: copyandmkdir.pl
      If your target is a UNIX machine you can send through your communications handler 'test -e file_name && echo EXISTS || echo DOESNOTEXIST'