views:

40

answers:

1

Hello,

I have a file say /a/b/c/file in my host. I want to create a file on remote host in directory say dest. Now the question is, how do I create a file in remote host as /dest/a/b/c/d/file using perl script and using ssh. Any idea how do I create directories in script.?

Thanks.

A: 

To reproduce the directory structure, use catfile and abs2rel from the File::Spec module: catfile joins pieces to make a path, and abs2rel gives the path relative to some base directory.

The File::Copy module's copy will copy to a handle. This fits nicely with how sshopen3 opens handles to the standard input, output, and error on the destination side.

The remote command has 3 parts:

  • mkdir -p $dst_dir, creates all directories preceding the file in the destination path
  • cat >$dst_file, connects the SEND handle to the destination file
  • md5sum $dst_file, shows that the data arrived safely

Sample program below:

#! /usr/bin/perl

use warnings;
use strict;

use File::Basename;
use File::Copy;
use File::Spec::Functions qw/ abs2rel catfile /;
use Net::SSH qw/ sshopen3 /;

my $HOST     = "user\@host.com";
my $SRC_BASE = "/tmp/host";
my $SRC_FILE = "$SRC_BASE/a/b/c/file";
my $DST_BASE = "/tmp/dest";
system("md5sum", $SRC_FILE) == 0 or exit 1;

my $dst_file = catfile $DST_BASE, abs2rel $SRC_FILE, $SRC_BASE;
my $dst_dir  = dirname $dst_file;
sshopen3 $HOST, *SEND, *RECV, *ERRORS,
         "mkdir -p $dst_dir && cat >$dst_file && md5sum $dst_file"
  or die "$0: ssh: $!";

binmode SEND;
copy $SRC_FILE, \*SEND or die  "$0: copy failed: $!";
close SEND             or warn "$0: close: $!";  # later reads hang without this

undef $/;
my $errors = <ERRORS>;
warn $errors if $errors =~ /\S/;
close ERRORS or warn "$0: close: $!";

print <RECV>;
close RECV or warn "$0: close: $!";

Sample run:

$ ./create-file
746308829575e17c3331bbcb00c0898b  /tmp/host/a/b/c/file
746308829575e17c3331bbcb00c0898b  /tmp/dest/a/b/c/file
Greg Bacon
Thanks. I could get your code.I am sorry. But I am pretty new to all this file and directory handling.How do I handle a case wherein, for example.Say I have host directory /src in variable $src_dirhost directory file ./a/b/f1 in variable $src_filedestination directory /dst in varisble $dst_dirnow I need file like /dst/a/b/c/f1now 1st problem.. I do $dst_dir/$src_file I get /dst/./a/b/c/f1where I need get rid of the extra ./ and create directory /dst/a/b/c by somehow getting directory path from $src_file and create a file f1 under it.How do I go about this problem. Thanks.
pythonperl
@pythonperl See updated answer.
Greg Bacon
Hi, I could get the solution. I used the use File::Basename module as suggested by you to get the fileame and the directory. Then I created the directory in remote host using mkdir -p "dir" using ssh. And then created the file. That worked very well. Thanks much for your help.
pythonperl
@pythonperl You're welcome! I'm glad it helped.
Greg Bacon
Thanks again :)
pythonperl