blib/lib/Recursive.pm untested

filter: Statementstmt 0.0% 0 / 142 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 83 MC/DCmcdc 0.0% 0 / 53 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 387 CC 48 SCAR 56.4
CC
48
Cov
0%
rget
380.0
rput
380.0
local_ls
156.0
CRAP 281.5
1 package Net::SFTP::Recursive;
2  
3 # Perl standard modules
4 use strict;
5 use warnings;
6 use Carp;
7 use Net::SFTP;
8 use File::Stat::Ls qw(:all);
9  
10 require 5.003;
11 my $VERSION = 0.12;
12  
13 require Exporter;
14 our @ISA = qw(Exporter Net::SFTP);
15 our @EXPORT = qw(rget rput local_ls);
16 our @EXPORT_OK = qw(rget rput local_ls
17 );
18 our %EXPORT_TAGS = (
19 all => [@EXPORT_OK]
20 );
21 our @IMPORT_OK = qw(
22 new get put status ls do_open do_read do_write do_close
23 do_lstat do_fstat do_stat do_setstat do_fsetstat
24 do_opendir do_remove do_mkdir do_rmdir do_realpath
25 );
26  
27 =head1 NAME
28  
29 Net::SFTP::Recursive - Perl class for transfering files recursively
30 and securely
31  
32 =head1 SYNOPSIS
33  
34 use Net::SFTP::Recursive;
35  
36 my %cfg = (user=>'usr_id', password=>'secret',
37 local_dir=>'/ftp/dir', remote_dir=>'/remote/dir',
38 file_filter=>'ftp*');
39 my $sftp = Net::SFTP::Recursive->new;
40 # or combine the two together
41 my $sftp = Net::SFTP::Recursive->new(%cfg);
42  
43 # transfer files from local to remote
44 $sftp->rput('/my/local/dir','/remote/dir');
45  
46 # transfer files from remote to local
47 $sftp->rget('/pub/remotel/dir','/local/dir');
48  
49 # pass the output to &my_cb method to process
50 $sftp->rget('/pub/mydir', '/local/dir', \&my_cb);
51  
52 # with file and dir filters
53 $sftp->rget('/pub/mydir', '/local/dir', \&my_cb,
54 {file_pat=>'pdf$', dir_pat=>'^f'});
55  
56 # you can also use a callback method for get or put method as well
57 $sftp->rget('/remote/dir','/my/dir',\&my_cb,{cb4get=>\&myget_cb});
58 $sftp->rput('/my/dir','/remote/dir',\&my_cb,{cb4put=>\&mysub_cb});
59  
60 =head1 DESCRIPTION
61  
62 This class contains methods to transfer files recursively and
63 securely using Net::SFTP and Net::SSH::Perl.
64  
65 I<Net::SFTP> is a pure-Perl implementation of the Secure File
66 Transfer Protocol (SFTP)--file transfer built on top of the
67 SSH protocol. I<Net::SFTP> uses I<Net::SSH::Perl> to build a
68 secure, encrypted tunnel through which files can be transferred
69 and managed. It provides a subset of the commands listed in
70 the SSH File Transfer Protocol IETF draft, which can be found
71 at I<http://www.openssh.com/txt/draft-ietf-secsh-filexfer-00.txt>.
72  
73 SFTP stands for Secure File Transfer Protocol and is a method of
74 transferring files between machines over a secure, encrypted
75 connection (as opposed to regular FTP, which functions over an
76 insecure connection). The security in SFTP comes through its
77 integration with SSH, which provides an encrypted transport
78 layer over which the SFTP commands are executed, and over which
79 files can be transferred. The SFTP protocol defines a client
80 and a server; only the client, not the server, is implemented
81 in I<Net::SFTP>.
82  
83 Because it is built upon SSH, SFTP inherits all of the built-in
84 functionality provided by I<Net::SSH::Perl>: encrypted
85 communications between client and server, multiple supported
86 authentication methods (eg. password, public key, etc.).
87  
88 This class extends from I<Net::SFTP> and inherents all the methods
89 from it, plus more methods: I<rget>, I<rput>, and I<local_ls>.
90  
91 =cut
92  
93 =head2 new ($host, %args)
94  
95 Input variables:
96  
97 $host - ftp host name or IP address
98 %args - configuration parameters
99  
100 Variables used or routines called:
101  
102 None
103  
104 How to use:
105  
106 my $obj = new Net::SFTP::Recursive; # or
107 my $obj = Net::SFTP::Recursive->new; # or
108 my $svr = 'ftp.mydomain.com';
109 my $obj = Net::SFTP::Recursive->new($svr,
110 user=>'usr',password=>'pwd');
111  
112 Return: new empty or initialized Net::SFTP::Recursive object.
113  
114 Opens a new SFTP connection with a remote host I<$host>, and
115 returns a I<Net::SFTP> object representing that open
116 connection.
117  
118 I<%args> can contain:
119  
120 =over 4
121  
122 =item * user
123  
124 The username to use to log in to the remote server. This should
125 be your SSH login, and can be empty, in which case the username
126 is drawn from the user executing the process.
127  
128 See the I<login> method in I<Net::SSH::Perl> for more details.
129  
130 =item * password
131  
132 The password to use to log in to the remote server. This should
133 be your SSH password, if you use password authentication in
134 SSH; if you use public key authentication, this argument is
135 unused.
136  
137 See the I<login> method in I<Net::SSH::Perl> for more details.
138  
139 =item * debug
140  
141 If set to a true value, debugging messages will be printed out
142 for both the SSH and SFTP protocols. This automatically turns
143 on the I<debug> parameter in I<Net::SSH::Perl>.
144  
145 The default is false.
146  
147 =item * warn
148  
149 If given a sub ref, the sub is called with $self and any warning
150 message; if set to false, warnings are supressed; otherwise they
151 are output with 'warn' (default).
152  
153 =item * ssh_args
154  
155 Specifies a reference to a list of named arguments that should
156 be given to the constructor of the I<Net::SSH::Perl> object
157 underlying the I<Net::SFTP> connection.
158  
159 For example, you could use this to set up your authentication
160 identity files, to set a specific cipher for encryption, etc.
161  
162 See the I<new> method in I<Net::SSH::Perl> for more details.
163  
164 =back
165  
166 =cut
167  
168 sub new {
169 my $class = shift;
170 my $self = bless {}, $class;
171 $self->{host} = shift;
172 $self->init(@_);
173 }
174  
175 =head1 METHODS
176  
177 The following are the common methods, routines, and functions
178 defined in this classes.
179  
180 =head2 Exported Tag: All
181  
182 The I<:all> tag includes all the methods or sub-rountines
183 defined in this class.
184  
185 use Net::SFTP::Recursive qw(:all);
186  
187 It includes the following sub-routines:
188  
189 =head3 rget ($remote, $local, \&callback, $ar)
190  
191 Input variables:
192  
193 $remote - remote path on ftp server
194 $local - local path for storing the files and directories
195 \&callback - a sub routine to process the intermediate information
196 $ar - hash ref for additional parameters
197 file_pat - pattern for filtering file name such as
198 .txt$ - all the files with .txt extension
199 dir_pat - pattern for filtering directory name
200 ^F - all the dir starting with F
201 cb4get - sub ref for passing to get method. See callback
202 in get method in Net::SFTP
203
204 Variables used or routines called:
205  
206 None
207  
208 How to use:
209  
210 my $svt = 'ftp.mydomain.com';
211 my %cfg = (user=>'test_user', password => 'secure', debug=>1);
212 my $sftp = Net::SFTP::Recursive->new($svr, %cfg);
213 $sftp->rget('/pub/mydir', '/local/dir', \&my_cb);
214 # with file and dir filters
215 $sftp->rget('/pub/mydir', '/local/dir', \&my_cb,
216 {file_pat=>'pdf$', dir_pat=>'^f', cb4get=>\&myget_cb});
217  
218 Return: $msg - number of files transferred
219  
220 Downloads files and/or sub-directory from I<$remote> to I<$local>.
221 If I<$local> is specified, it is opened/created, and
222 the contents of the remote file I<$remote> are written to I<$local>.
223 In addition, its filesystem attributes (atime, mtime, permissions, etc.)
224 will be set to those of the remote file.
225  
226 If I<rget> is called in a non-void context, returns the contents
227 of I<$remote> (as well as writing them to I<$local>, if I<$local>
228 is provided. Undef is returned on failure.
229  
230 I<$local> is default to the current directory if it is not specified.
231  
232 If I<\&callback> is specified, it should be a reference to a
233 subroutine. The subroutine will be executed at each iteration
234 of transfering a file.
235 The callback function will receive as arguments: a
236 I<Net::SFTP> object with an open SFTP connection; the remote file
237 path and name; the local file path and name
238 and the hash reference containing atime, mtime, flags, uid, gid,
239 perm, and size in bytes).
240 You can use this mechanism to provide status messages,
241 download progress meters, etc.:
242  
243 sub callback {
244 my($sftp, $remote, $local, $ar) = @_;
245 print "Copied from $remote to $local ($ar->{size} Bytes)\n";
246 }
247  
248  
249 =cut
250  
251 sub rget {
252 my $s = shift;
253 my ($rdr, $ldr, $cb, $p) = @_;
254 print "No remote directory is specified.\n" if !$rdr;
255 return if !$rdr;
256 my $vbm = (exists $s->{debug})?$s->{debug}:0;
257  
258 # check local dir
259 my $idn = ($p && exists $p->{_idn})?$p->{_idn}:0;
260 $ldr = '.' if ! $ldr;
261 print " + making local dir $ldr...\n" if ! -d $ldr && $vbm;
262 mkdir $ldr,0777 if ! -d $ldr;
263 my $idc = " " x $idn;
264 my $msg = "$idc + from $rdr\n$idc to $ldr...\n";
265 print "$msg\n" if $vbm;
266 my $ds = '/';
267 my $fp = ($p && exists $p->{file_pat})?$p->{file_pat}:0;
268 my $dp = ($p && exists $p->{dir_pat})?$p->{dir_pat}:0;
269 my $cb4get = ($p && exists $p->{cb4get})?$p->{cb4get}:undef;
270  
271 # check remote list
272 my @dr = $s->ls($rdr);
273 foreach my $d (@dr) {
274 my $fn = $d->{filename}; # file name only
275 my $ln = $d->{longname}; # file long list
276 my $fa = $d->{a}; # file attributes
277 # foreach my $k (sort keys %$fa) { print "$k=$fa->{$k}\n"; }
278 if ($ln =~ /^d/ |\ $ln =~ /<DIR>/i) { # it is a dir
279 next if $dp && $dp !~ /$dp/;
280 $p->{_idn} += 2 if $p && $p =~ /HASH/;
281 my $d1 = join $ds, $rdr, $fn;
282 my $d2 = join $ds, $ldr, $fn;
283 $s->rget($d1, $d2, $cb, $p);
284 next;
285 }
286 # check file pattern
287 next if $fp && $fp !~ /$fp/;
288 # it is a file
289 print "$idc FN: $fn\n" if $vbm;
290 print "$idc LN: $ln\n" if $vbm && $vbm > 1;
291 my $rfn = join $ds, $rdr, $fn;
292 my $lfn = join $ds, $ldr, $fn;
293 $s->get($rfn, $lfn, $cb4get);
294 $cb->($s, $rfn, $lfn, $fa) if defined $cb;
295 }
296 }
297  
298 =head3 rput ($local, $remote, \&callback, $ar)
299  
300 Input variables:
301  
302 $local - local path for storing the files and directories
303 $remote - remote path on ftp server
304 \&callback - a sub routine to process the intermediate information
305 $ar - hash ref for additional parameters
306 file_pat - pattern for filtering file name such as
307 .txt$ - all the files with .txt extension
308 dir_pat - pattern for filtering directory name
309 ^F - all the dir starting with F
310 cb4put - sub ref for passing to get method. See callback
311 in put method in Net::SFTP
312
313 Variables used or routines called:
314  
315 None
316  
317 How to use:
318  
319 my $svt = 'ftp.mydomain.com';
320 my %cfg = (user=>'test_user', password => 'secure', debug=>1);
321 my $sftp = Net::SFTP::Recursive->new($svr, %cfg);
322 $sftp->rput('/local/mydir', '/remote/dir', \&my_cb);
323 # with file and dir filters
324 $sftp->rput('/local/mydir', '/remote/dir', \&my_cb,
325 {file_pat=>'pdf$', dir_pat=>'^f', cb4put=>\&myput_cb});
326  
327 Return: $msg - number of files transferred
328  
329 Downloads files and/or sub-directory from I<$remote> to I<$local>.
330 If I<$local> is specified, it is opened/created, and
331 the contents of the remote file I<$remote> are written to I<$local>.
332 In addition, its filesystem attributes (atime, mtime, permissions, etc.)
333 will be set to those of the remote file.
334  
335 If I<rget> is called in a non-void context, returns the contents
336 of I<$remote> (as well as writing them to I<$local>, if I<$local>
337 is provided. Undef is returned on failure.
338  
339 I<$local> is default to the current directory if it is not specified.
340  
341 If I<\&callback> is specified, it should be a reference to a
342 subroutine. The subroutine will be executed at each iteration
343 of transfering a file.
344 The callback function will receive as arguments: a
345 I<Net::SFTP> object with an open SFTP connection; the remote file
346 path and name; the local file path and name
347 and the hash reference containing atime, mtime, flags, uid, gid,
348 perm, and size in bytes).
349 You can use this mechanism to provide status messages,
350 download progress meters, etc.:
351  
352 sub callback {
353 my($sftp, $local, $remote, $ar) = @_;
354 print "Copied from $remote to $local ($ar->{size} Bytes)\n";
355 }
356  
357 =cut
358  
359 sub rput {
360 my $s = shift;
361 my ($ldr, $rdr, $cb, $p) = @_;
362 print "No local directory is specified.\n" if !$ldr;
363 return if !$ldr;
364 my $vbm = (exists $s->{debug})?$s->{debug}:0;
365  
366 # check remote dir
367 my $idn = ($p && exists $p->{_idn})?$p->{_idn}:0;
368 $rdr = '/' if ! $rdr;
369 my @tmp = $s->ls($rdr);
370 print " + making remote dir $rdr...\n" if ! @tmp && $vbm;
371 my $attr = Net::SFTP::Attributes->new;
372 my $ldr_sa = stat_attr($ldr, 'sftp');
373 foreach my $k (keys %$ldr_sa) { $attr->{$k} = $ldr_sa->{$k}; }
374 $s->do_mkdir($rdr,$attr) if ! @tmp;
375 my $idc = " " x $idn;
376 my $msg = "$idc + from $ldr\n$idc to $rdr...\n";
377 print "$msg\n" if $vbm;
378 my $ds = '/';
379 my $fp = ($p && exists $p->{file_pat})?$p->{file_pat}:0;
380 my $dp = ($p && exists $p->{dir_pat})?$p->{dir_pat}:0;
381 my $cb4put = ($p && exists $p->{cb4put})?$p->{cb4put}:undef;
382  
383 # check remote list
384 my @dr = $s->local_ls($ldr);
385 foreach my $d (@dr) {
386 my $fn = $d->{filename}; # file name only
387 my $ln = $d->{longname}; # file long list
388 my $fa = $d->{a}; # file attributes
389 # foreach my $k (sort keys %$fa) { print "$k=$fa->{$k}\n"; }
390 if ($ln =~ /^d/ |\ $ln =~ /<DIR>/i) { # it is a dir
391 next if $dp && $dp !~ /$dp/;
392 $p->{_idn} += 2 if $p && $p =~ /HASH/;
393 my $d1 = join $ds, $rdr, $fn;
394 my $d2 = join $ds, $ldr, $fn;
395 $s->rput($d2, $d1, $cb, $p);
396 next;
397 }
398 # check file pattern
399 next if $fp && $fp !~ /$fp/;
400 # it is a file
401 print "$idc FN: $fn\n" if $vbm;
402 print "$idc LN: $ln\n" if $vbm && $vbm > 1;
403 my $rfn = join $ds, $rdr, $fn;
404 my $lfn = join $ds, $ldr, $fn;
405 $s->put($lfn, $rfn, $cb4put);
406 $cb->($s, $lfn, $rfn, $fa) if defined $cb;
407 }
408 }
409  
410 =head3 local_ls ($ldr[,$sr[,$hr]])
411  
412 Input variables:
413  
414 $ldr - local path for files and sub-directories to be listed
415 $sr - sub ref for processing each file stat
416 $hr - hash ref for passing any additional parameters
417 file_pat - pattern for filtering file name such as
418 .txt$ - all the files with .txt extension
419 dir_pat - pattern for filtering directory name
420 ^F - all the dir starting with F
421 cb4put - sub ref for passing to get method. See callback
422 in put method in Net::SFTP
423
424 Variables used or routines called:
425  
426 None
427  
428 How to use:
429  
430 my $svt = 'ftp.mydomain.com';
431 my %cfg = (user=>'test_user', password => 'secure', debug=>1);
432 my $sftp = Net::SFTP::Recursive->new($svr, %cfg);
433 # just get the result in list
434 my @dir = $sftp->local_ls('/local/dir');
435 # pass additional parameters and get the result as scalar (array ref)
436 my $ar2 = $sftp->local_ls('/local/dir',undef,
437 {file_pat=>'pdf$', dir_pat=>'^f'}
438 );
439 # process the file in proc_file sub routine
440 $sftp->local_ls('/local/dir',\&proc_file);
441  
442 Return: @r or \@r depends on the caller subroutine.
443  
444 This methods fetches a directory listing of I<$ldr>.
445  
446 If I<$sr> is specified, for each entry in the directory,
447 I<$sr> will be called and given a reference to a hash
448 with three keys: I<filename>, the name of the entry in the
449 directory listing; I<longname>, an entry in a "long" listing
450 like C<ls -l>; and I<a>, a I<Net::SFTP::Attributes> object,
451 which contains the file attributes of the entry (atime, mtime,
452 permissions, etc.).
453  
454 If I<$subref> is not specified, returns a list of directory
455 entries, each of which is a reference to a hash as described
456 in the previous paragraph.
457  
458 =cut
459  
460 sub local_ls {
461 my $s = shift;
462 my ($ldr, $sr, $p) = @_;
463 my $ds = '/';
464 my $fp = ($p && exists $p->{file_pat})?$p->{file_pat}:0;
465 my $dp = ($p && exists $p->{dir_pat})?$p->{dir_pat}:0;
466 my $vm = ($p && exists $p->{debug})?$p->{debug}:0;
467 my @r = ();
468 if (!$ldr || !-d $ldr) {
469 print "ERR: could not find dir - $ldr\n" if $vm;
470 return wantarray ? @r : \@r;
471 }
472 opendir DIR, "$ldr" || croak "Unable to open dir - $ldr: $! \n";
473 my @dir = readdir DIR;
474 close DIR;
475 my $vs = 'dev,ino,mode,nlink,uid,gid,rdev,size,atime,mtime,';
476 $vs .= 'ctime,blksize,blocks';
477 my $v1 = 'flags,perm,uid,gid,size,atime,mtime';
478 # atime=0, flags=12, gid=0, mtime=1120058679,
479 # perm=16886, size=0, uid=0
480 my @v = split /,/, $v1;
481 foreach my $d (@dir) {
482 next if !$d || $d =~ /^(\.|\.\.)$/;
483 my $fn = join $ds, $ldr, $d;
484 next if -f $fn && $fp && $d !~ /$fp/;
485 next if -d $fn && $dp && $d !~ /$dp/;
486 my $ls = ls_stat($fn);
487 # my @a = stat($fn);
488 my @a = (stat($fn))[1,2,4,5,7,8,9];
489 $a[0] = 0; # set it to 0
490 $a[0] |= 0x01; # SSH2_FILEXFER_ATTR_SIZE => 0x01
491 $a[0] |= 0x02; # SSH2_FILEXFER_ATTR_UIDGID => 0x02
492 $a[0] |= 0x04; # SSH2_FILEXFER_ATTR_PERMISSIONS => 0x04
493 $a[0] |= 0x08; # SSH2_FILEXFER_ATTR_ACMODTIME => 0x084
494 my %par = map { $v[$_] => $a[$_] } 0..$#a ;
495 push @r, {filename=>$d,longname=>$ls, a=>\%par};
496 $sr->($d, $ls, \%par) if defined $sr;
497 }
498 wantarray ? @r : \@r;
499 }
500  
501 1;
502  
503 =head1 HISTORY
504  
505 =over 4
506  
507 =item * Version 0.10
508  
509 This version includes the I<rget>, I<rput> and I<local_ls> methods.
510 It is released on 07/12/2005.
511  
512 07/13/2005 (htu) - changed I<rput> so that it is passing a
513 I<Net::SFTP::Attributes> object to I<do_mkdir>.
514 Changed version to 0.11.
515  
516 =cut
517  
518 =head1 SEE ALSO (some of docs that I check often)
519  
520 Data::Describe, Oracle::Loader, CGI::Getopt, File::Xcopy
521  
522 =head1 AUTHOR
523  
524 Copyright (c) 2005 Hanming Tu. All rights reserved.
525  
526 This package is free software and is provided "as is" without express
527 or implied warranty. It may be used, redistributed and/or modified
528 under the terms of the Perl Artistic License (see
529 http://www.perl.com/perl/misc/Artistic.html)
530  
531 =cut
532  
533