1Net::SFTP::Foreign(3) User Contributed Perl DocumentationNet::SFTP::Foreign(3)
2
3
4
6 Net::SFTP::Foreign - SSH File Transfer Protocol client
7
9 use Net::SFTP::Foreign;
10 my $sftp = Net::SFTP::Foreign->new($host);
11 $sftp->die_on_error("Unable to establish SFTP connection");
12
13 $sftp->setcwd($path) or die "unable to change cwd: " . $sftp->error;
14
15 $sftp->get("foo", "bar") or die "get failed: " . $sftp->error;
16
17 $sftp->put("bar", "baz") or die "put failed: " . $sftp->error;
18
20 SFTP stands for SSH File Transfer Protocol and is a method of
21 transferring files between machines over a secure, encrypted connection
22 (as opposed to regular FTP, which functions over an insecure
23 connection). The security in SFTP comes through its integration with
24 SSH, which provides an encrypted transport layer over which the SFTP
25 commands are executed.
26
27 Net::SFTP::Foreign is a Perl client for the SFTP version 3 as defined
28 in the SSH File Transfer Protocol IETF draft, which can be found at
29 <http://www.openssh.org/txt/draft-ietf-secsh-filexfer-02.txt> (also
30 included on this package distribution, on the "rfc" directory).
31
32 Net::SFTP::Foreign uses any compatible "ssh" command installed on the
33 system (for instance, OpenSSH "ssh") to establish the secure connection
34 to the remote server.
35
36 A wrapper module Net::SFTP::Foreign::Compat is also provided for
37 compatibility with Net::SFTP.
38
39 Net::SFTP::Foreign Vs. Net::SFTP Vs. Net::SSH2::SFTP
40 Why should I prefer Net::SFTP::Foreign over Net::SFTP?
41
42 Well, both modules have their pros and cons:
43
44 Net::SFTP::Foreign does not require a bunch of additional modules and
45 external libraries to work, just the OpenBSD SSH client (or any other
46 client compatible enough).
47
48 I trust OpenSSH SSH client more than Net::SSH::Perl, there are lots of
49 paranoid people ensuring that OpenSSH doesn't have security holes!!!
50
51 If you have an SSH infrastructure already deployed, by using the same
52 binary SSH client, Net::SFTP::Foreign ensures a seamless integration
53 within your environment (configuration files, keys, etc.).
54
55 Net::SFTP::Foreign is much faster transferring files, specially over
56 networks with high (relative) latency.
57
58 Net::SFTP::Foreign provides several high level methods not available
59 from Net::SFTP as for instance "find", "glob", "rget", "rput",
60 "rremove", "mget", "mput".
61
62 On the other hand, using the external command means an additional
63 process being launched and running, depending on your OS this could eat
64 more resources than the in process pure perl implementation provided by
65 Net::SSH::Perl.
66
67 Net::SSH2 is a module wrapping libssh2, an SSH version 2 client library
68 written in C. It is a very active project that aims to replace
69 Net::SSH::Perl. Unfortunately, libssh2 SFTP functionality (available in
70 Perl via Net::SSH2::SFTP) is rather limited and its performance very
71 poor.
72
73 Later versions of Net::SFTP::Foreign can use Net::SSH2 as the transport
74 layer via the backend module Net::SFTP::Foreign::Backend::Net_SSH2.
75
76 Error handling
77 The method "$sftp->error" can be used to check for errors after every
78 method call. For instance:
79
80 $sftp = Net::SFTP::Foreign->new($host);
81 $sftp->error and die "unable to connect to remote host: " . $sftp->error;
82
83 Also, the "die_on_error" method provides a handy shortcut for the last
84 line:
85
86 $sftp = Net::SFTP::Foreign->new($host);
87 $sftp->die_on_error("unable to connect to remote host");
88
89 The "status" method can also be used to get the value for the last SFTP
90 status response, but that is only useful when calling low level methods
91 mapping to single SFTP primitives. In any case, it should be considered
92 an implementation detail of the module usable only for troubleshooting
93 and error reporting.
94
95 autodie mode
96 When the "autodie" mode is set at construction time, non-recoverable
97 errors are automatically promoted to exceptions. For instance:
98
99 $sftp = Net::SFTP::Foreign->new($host, autodie => 1);
100 my $ls = $sftp->ls("/bar");
101 # dies as: "Couldn't open remote dir '/bar': No such file"
102
103 Error handling in non-recursive methods
104
105 Most of the non-recursive methods available from this package return
106 undef on failure and a true value or the requested data on success.
107
108 For instance:
109
110 $sftp->get($from, $to) or die "get failed!";
111
112 Error handling in recursive methods
113
114 Recursive methods (i.e. "find", "rget", "rput", "rremove") do not stop
115 on errors but just skip the affected files and directories and keep
116 going.
117
118 After a call to a recursive method, the error indicator is only set
119 when an unrecoverable error is found (i.e. a connection lost). For
120 instance, this code doesn't work as expected:
121
122 $sftp->rremove($dir);
123 $sftp->error and die "rremove failed"; # this is wrong!!!
124
125 This does:
126
127 my $errors;
128 $sftp->rremove($dir, on_error => sub { $errors++});
129 $errors and die "rremove failed";
130
131 The "autodie" mode is disabled when an "on_error" handler is passed to
132 methods accepting it:
133
134 my $sftp = Net::SFTP::Foreign->new($host, autodie => 1);
135 # prints "foo!" and does not die:
136 $sftp->find("/sdfjkalshfl", # nonexistent directory
137 on_error => sub { print "foo!\n" });
138 # dies:
139 $sftp->find("/sdfjkalshfl");
140
141 API
142 The methods available from this module are described below.
143
144 Don't forget to read also the FAQ and BUGS sections at the end of this
145 document!
146
147 Net::SFTP::Foreign->new($host, %args)
148 Net::SFTP::Foreign->new(%args)
149 Opens a new SFTP connection with a remote host $host, and returns a
150 Net::SFTP::Foreign object representing that open connection.
151
152 An explicit check for errors should be included always after the
153 constructor call:
154
155 my $sftp = Net::SFTP::Foreign->new(...);
156 $sftp->die_on_error("SSH connection failed");
157
158 The optional arguments accepted are as follows:
159
160 host => $hostname
161 remote host name
162
163 user => $username
164 username to log in to the remote server. This should be your
165 SSH login, and can be empty, in which case the username is
166 drawn from the user executing the process.
167
168 port => $portnumber
169 port number where the remote SSH server is listening
170
171 ssh1 => 1
172 use old SSH1 approach for starting the remote SFTP server.
173
174 more => [@more_ssh_args]
175 additional args passed to "ssh" command.
176
177 For debugging purposes you can run "ssh" in verbose mode
178 passing it the "-v" option:
179
180 my $sftp = Net::SFTP::Foreign->new($host, more => '-v');
181
182 Note that this option expects a single command argument or a
183 reference to an array of arguments. For instance:
184
185 more => '-v' # right
186 more => ['-v'] # right
187 more => "-c $cipher" # wrong!!!
188 more => [-c => $cipher] # right
189
190 timeout => $seconds
191 when this parameter is set, the connection is dropped if no
192 data arrives on the SSH socket for the given time while waiting
193 for some command to complete.
194
195 When the timeout expires, the current method is aborted and the
196 SFTP connection becomes invalid.
197
198 Note that the given value is used internally to time out low
199 level operations. The high level operations available through
200 the API may take longer to expire (sometimes up to 4 times
201 longer).
202
203 The "Windows" backend used by default when the operating system
204 is MS Windows (though, not under Cygwin perl), does not support
205 timeouts. To overcome this limitation you can switch to the
206 "Net_SSH2" backend or use Net::SSH::Any that provides its own
207 backend supporting timeouts.
208
209 fs_encoding => $encoding
210 Version 3 of the SFTP protocol (the one supported by this
211 module) knows nothing about the character encoding used on the
212 remote filesystem to represent file and directory names.
213
214 This option allows one to select the encoding used in the
215 remote machine. The default value is "utf8".
216
217 For instance:
218
219 $sftp = Net::SFTP::Foreign->new('user@host', fs_encoding => 'latin1');
220
221 will convert any path name passed to any method in this package
222 to its "latin1" representation before sending it to the remote
223 side.
224
225 Note that this option will not affect file contents in any way.
226
227 This feature is not supported in perl 5.6 due to incomplete
228 Unicode support in the interpreter.
229
230 key_path => $filename
231 key_path => \@filenames
232 asks "ssh" to use the key(s) in the given file(s) for
233 authentication.
234
235 password => $password
236 Logs into the remote host using password authentication with
237 the given password.
238
239 Password authentication is only available if the module IO::Pty
240 is installed. Note also, that on Windows this module is only
241 available when running the Cygwin port of Perl.
242
243 asks_for_username_at_login => 0|'auto'|1
244 During the interactive authentication dialog, most SSH servers
245 only ask for the user password as the login name is passed
246 inside the SSH protocol. But under some uncommon servers or
247 configurations it is possible that a username is also
248 requested.
249
250 When this flag is set to 1, the username will be send
251 unconditionally at the first remote prompt and then the
252 password at the second.
253
254 When it is set to "auto" the module will use some heuristics in
255 order to determine if it is being asked for an username.
256
257 When set to 0, the username will never be sent during the
258 authentication dialog. This is the default.
259
260 password_prompt => $regex_or_str
261 The module expects the password prompt from the remote server
262 to end in a colon or a question mark. This seems to cover
263 correctly 99% of real life cases.
264
265 Otherwise this option can be used to handle the exceptional
266 cases. For instance:
267
268 $sftp = Net::SFTP::Foreign->new($host, password => $password,
269 password_prompt => qr/\bpassword>\s*$/);
270
271 Note that your script will hang at the login phase if the wrong
272 prompt is used.
273
274 passphrase => $passphrase
275 Logs into the remote server using a passphrase protected
276 private key.
277
278 Requires also the module IO::Pty.
279
280 expect_log_user => $bool
281 This feature is obsolete as Expect is not used anymore to
282 handle password authentication.
283
284 ssh_cmd => $sshcmd
285 ssh_cmd => \@sshcmd
286 name of the external SSH client. By default "ssh" is used.
287
288 For instance:
289
290 $sftp = Net::SFTP::Foreign->new($host, ssh_cmd => 'plink');
291
292 When an array reference is used, its elements are inserted at
293 the beginning of the system call. That allows one, for
294 instance, to connect to the target host through some SSH proxy:
295
296 $sftp = Net::SFTP::Foreign->new($host,
297 ssh_cmd => [qw(ssh -l user proxy.server ssh)]);
298
299 But note that the module will not handle password
300 authentication for those proxies.
301
302 ssh_cmd_interface => 'plink' or 'ssh' or 'tectia'
303 declares the command line interface that the SSH client used to
304 connect to the remote host understands. Currently "plink",
305 "ssh" and "tectia" are supported.
306
307 This option would be rarely required as the module infers the
308 interface from the SSH command name.
309
310 transport => $fh
311 transport => [$in_fh, $out_fh]
312 transport => [$in_fh, $out_fh, $pid]
313 allows one to use an already open pipe or socket as the
314 transport for the SFTP protocol.
315
316 It can be (ab)used to make this module work with password
317 authentication or with keys requiring a passphrase.
318
319 "in_fh" is the file handler used to read data from the remote
320 server, "out_fh" is the file handler used to write data.
321
322 On some systems, when using a pipe as the transport, closing
323 it, does not cause the process at the other side to exit. The
324 additional $pid argument can be used to instruct this module to
325 kill that process if it doesn't exit by itself.
326
327 open2_cmd => [@cmd]
328 open2_cmd => $cmd;
329 allows one to completely redefine how "ssh" is called. Its
330 arguments are passed to IPC::Open2::open2 to open a pipe to the
331 remote server.
332
333 stderr_fh => $fh
334 redirects the output sent to stderr by the SSH subprocess to
335 the given file handle.
336
337 It can be used to suppress banners:
338
339 open my $ssherr, '>', '/dev/null' or die "unable to open /dev/null";
340 my $sftp = Net::SFTP::Foreign->new($host,
341 stderr_fh => $ssherr);
342
343 Or to send SSH stderr to a file in order to capture errors for
344 later analysis:
345
346 my $ssherr = File::Temp->new or die "File::Temp->new failed";
347 my $sftp = Net::SFTP::Foreign->new($hostname, more => ['-v'],
348 stderr_fh => $ssherr);
349 if ($sftp->error) {
350 print "sftp error: ".$sftp->error."\n";
351 seek($ssherr, 0, 0);
352 while (<$ssherr>) {
353 print "captured stderr: $_";
354 }
355 }
356
357 stderr_discard => 1
358 redirects stderr to /dev/null
359
360 block_size => $default_block_size
361 queue_size => $default_queue_size
362 default "block_size" and "queue_size" used for read and write
363 operations (see the "put" or "get" documentation).
364
365 autoflush => $bool
366 by default, and for performance reasons, write operations are
367 cached, and only when the write buffer becomes big enough is
368 the data written to the remote file. Setting this flag makes
369 the write operations immediate.
370
371 write_delay => $bytes
372 This option determines how many bytes are buffered before the
373 real SFTP write operation is performed.
374
375 read_ahead => $bytes
376 On read operations this option determines how many bytes to
377 read in advance so that later read operations can be fulfilled
378 from the buffer.
379
380 Using a high value will increase the performance of the module
381 for a sequential reads access pattern but degrade it for a
382 short random reads access pattern. It can also cause
383 synchronization problems if the file is concurrently modified
384 by other parties ("flush" can be used to discard all the data
385 inside the read buffer on demand).
386
387 The default value is set dynamically considering some runtime
388 parameters and given options, though it tends to favor the
389 sequential read access pattern.
390
391 autodisconnect => $ad
392 by default, the SSH connection is closed from the DESTROY
393 method when the object goes out of scope on the process and
394 thread where it was created. This option allows one to
395 customize this behaviour.
396
397 The acceptable values for $ad are:
398
399 '0' Never try to disconnect this object when exiting from any
400 process.
401
402 On most operating systems, the SSH process will exit when
403 the last process connected to it ends, but this is not
404 guaranteed.
405
406 You can always call the "disconnect" method explicitly to
407 end the connection at the right time from the right place.
408
409 '1' Disconnect on exit from any thread or process.
410
411 '2' Disconnect on exit from the current process/thread only.
412 This is the default.
413
414 See also the "disconnect" and "autodisconnect" methods.
415
416 late_set_perm => $bool
417 See the FAQ below.
418
419 dirty_cleanup => $bool
420 Sets the "dirty_cleanup" flag in a per object basis (see the
421 BUGS section).
422
423 backend => $backend
424 From version 1.57 Net::SFTP::Foreign supports plugable backends
425 in order to allow other ways to communicate with the remote
426 server in addition to the default pipe-to-ssh-process.
427
428 Custom backends may change the set of options supported by the
429 "new" method.
430
431 autodie => $bool
432 Enables the autodie mode that will cause the module to die when
433 any error is found (a la autodie).
434
435 $sftp->error
436 Returns the error code from the last executed command. The value
437 returned is similar to $!, when used as a string it yields the
438 corresponding error string.
439
440 See Net::SFTP::Foreign::Constants for a list of possible error
441 codes and how to import them on your scripts.
442
443 $sftp->die_on_error($msg)
444 Convenience method:
445
446 $sftp->die_on_error("Something bad happened");
447 # is a shortcut for...
448 $sftp->error and die "Something bad happened: " . $sftp->error;
449
450 $sftp->status
451 Returns the code from the last SSH2_FXP_STATUS response. It is also
452 a dualvar that yields the status string when used as a string.
453
454 Usually "$sftp->error" should be checked first to see if there was
455 any error and then "$sftp->status" to find out its low level cause.
456
457 $sftp->cwd
458 Returns the remote current working directory.
459
460 When a relative remote path is passed to any of the methods on this
461 package, this directory is used to compose the absolute path.
462
463 $sftp->setcwd($dir, %opts)
464 Changes the remote current working directory. The remote directory
465 should exist, otherwise the call fails.
466
467 Returns the new remote current working directory or undef on
468 failure.
469
470 Passing "undef" as the $dir argument resets the cwd to the server
471 default which is usually the user home but not always.
472
473 The method accepts the following options:
474
475 check => 0
476 By default the given target directory is checked against the
477 remote server to ensure that it actually exists and that it is
478 a directory. Some servers may fail to honor those requests even
479 for valid directories (i.e. when the directory has the hidden
480 flag set).
481
482 This option allows one to disable those checks and just sets
483 the cwd to the given value blindly.
484
485 $sftp->get($remote, $local, %options)
486 Copies remote file $remote to local $local. By default file
487 attributes are also copied (permissions, atime and mtime). For
488 instance:
489
490 $sftp->get('/var/log/messages', '/tmp/messages')
491 or die "file transfer failed: " . $sftp->error;
492
493 A file handle can also be used as the local target. In that case,
494 the remote file contents are retrieved and written to the given
495 file handle. Note also that the handle is not closed when the
496 transmission finish.
497
498 open F, '| gzip -c > /tmp/foo' or die ...;
499 $sftp->get("/etc/passwd", \*F)
500 or die "get failed: " . $sftp->error;
501 close F or die ...;
502
503 Accepted options (not all combinations are possible):
504
505 copy_time => $bool
506 determines if access and modification time attributes have to
507 be copied from remote file. Default is to copy them.
508
509 copy_perm => $bool
510 determines if permission attributes have to be copied from
511 remote file. Default is to copy them after applying the local
512 process umask.
513
514 umask => $umask
515 allows one to select the umask to apply when setting the
516 permissions of the copied file. Default is to use the umask for
517 the current process or 0 if the "perm" option is also used.
518
519 perm => $perm
520 sets the permission mask of the file to be $perm, remote
521 permissions are ignored.
522
523 resume => 1 | 'auto'
524 resumes an interrupted transfer.
525
526 If the "auto" value is given, the transfer will be resumed only
527 when the local file is newer than the remote one.
528
529 "get" transfers can not be resumed when a data conversion is in
530 place.
531
532 append => 1
533 appends the contents of the remote file at the end of the local
534 one instead of overwriting it. If the local file does not exist
535 a new one is created.
536
537 overwrite => 0
538 setting this option to zero cancels the transfer when a local
539 file of the same name already exists.
540
541 numbered => 1
542 modifies the local file name inserting a sequence number when
543 required in order to avoid overwriting local files.
544
545 For instance:
546
547 for (1..2) {
548 $sftp->get("data.txt", "data.txt", numbered => 1);
549 }
550
551 will copy the remote file as "data.txt" the first time and as
552 "data(1).txt" the second one.
553
554 If a scalar reference is passed as the numbered value, the
555 final target will be stored in the value pointed by the
556 reference. For instance:
557
558 my $target;
559 $sftp->get("data.txt", "data.txt", numbered => \$target);
560 say "file was saved as $target" unless $sftp->error
561
562 atomic => 1
563 The remote file contents are transferred into a temporal file
564 that once the copy completes is renamed to the target
565 destination.
566
567 If not-overwrite of remote files is also requested, an empty
568 file may appear at the target destination before the rename
569 operation is performed. This is due to limitations of some
570 operating/file systems.
571
572 mkpath => 0
573 By default the method creates any non-existent parent directory
574 for the given target path. That feature can be disabled setting
575 this flag to 0.
576
577 cleanup => 1
578 If the transfer fails, remove the incomplete file.
579
580 This option is set to by default when there is not possible to
581 resume the transfer afterwards (i.e., when using `atomic` or
582 `numbered` options).
583
584 best_effort => 1
585 Ignore minor errors as setting time or permissions.
586
587 conversion => $conversion
588 on the fly data conversion of the file contents can be
589 performed with this option. See "On the fly data conversion"
590 below.
591
592 callback => $callback
593 $callback is a reference to a subroutine that will be called
594 after every iteration of the download process.
595
596 The callback function will receive as arguments: the current
597 Net::SFTP::Foreign object; the data read from the remote file;
598 the offset from the beginning of the file in bytes; and the
599 total size of the file in bytes.
600
601 This mechanism can be used to provide status messages, download
602 progress meters, etc.:
603
604 sub callback {
605 my($sftp, $data, $offset, $size) = @_;
606 print "Read $offset / $size bytes\r";
607 }
608
609 The "abort" method can be called from inside the callback to
610 abort the transfer:
611
612 sub callback {
613 my($sftp, $data, $offset, $size) = @_;
614 if (want_to_abort_transfer()) {
615 $sftp->abort("You wanted to abort the transfer");
616 }
617 }
618
619 The callback will be called one last time with an empty data
620 argument to indicate the end of the file transfer.
621
622 The size argument can change between different calls as data is
623 transferred (for instance, when on-the-fly data conversion is
624 being performed or when the size of the file can not be
625 retrieved with the "stat" SFTP command before the data transfer
626 starts).
627
628 block_size => $bytes
629 size of the blocks the file is being split on for transfer.
630 Incrementing this value can improve performance but most
631 servers limit the maximum size.
632
633 queue_size => $size
634 read and write requests are pipelined in order to maximize
635 transfer throughput. This option allows one to set the maximum
636 number of requests that can be concurrently waiting for a
637 server response.
638
639 $sftp->get_content($remote)
640 Returns the content of the remote file.
641
642 $sftp->get_symlink($remote, $local, %opts)
643 copies a symlink from the remote server to the local file system
644
645 The accepted options are "overwrite" and "numbered". They have the
646 same effect as for the "get" method.
647
648 $sftp->put($local, $remote, %opts)
649 Uploads a file $local from the local host to the remote host saving
650 it as $remote. By default file attributes are also copied. For
651 instance:
652
653 $sftp->put("test.txt", "test.txt")
654 or die "put failed: " . $sftp->error;
655
656 A file handle can also be passed in the $local argument. In that
657 case, data is read from there and stored in the remote file. UTF8
658 data is not supported unless a custom converter callback is used to
659 transform it to bytes. The method will croak if it encounters any
660 data in perl internal UTF8 format. Note also that the handle is not
661 closed when the transmission finish.
662
663 Example:
664
665 binmode STDIN;
666 $sftp->put(\*STDIN, "stdin.dat") or die "put failed";
667 close STDIN;
668
669 This method accepts several options:
670
671 copy_time => $bool
672 determines if access and modification time attributes have to
673 be copied from remote file. Default is to copy them.
674
675 copy_perm => $bool
676 determines if permission attributes have to be copied from
677 remote file. Default is to copy them after applying the local
678 process umask.
679
680 umask => $umask
681 allows one to select the umask to apply when setting the
682 permissions of the copied file. Default is to use the umask for
683 the current process.
684
685 perm => $perm
686 sets the permission mask of the file to be $perm, umask and
687 local permissions are ignored.
688
689 overwrite => 0
690 by default "put" will overwrite any pre-existent file with the
691 same name at the remote side. Setting this flag to zero will
692 make the method fail in that case.
693
694 numbered => 1
695 when set, a sequence number is added to the remote file name in
696 order to avoid overwriting pre-existent files. Off by default.
697
698 append => 1
699 appends the local file at the end of the remote file instead of
700 overwriting it. If the remote file does not exist a new one is
701 created. Off by default.
702
703 resume => 1 | 'auto'
704 resumes an interrupted transfer.
705
706 If the "auto" value is given, the transfer will be resumed only
707 when the remote file is newer than the local one.
708
709 sparse => 1
710 Blocks that are all zeros are skipped possibly creating an
711 sparse file on the remote host.
712
713 mkpath => 0
714 By default the method creates any non-existent parent directory
715 for the given target path. That feature can be disabled setting
716 this flag to 0.
717
718 atomic => 1
719 The local file contents are transferred into a temporal file
720 that once the copy completes is renamed to the target
721 destination.
722
723 This operation relies on the SSH server to perform an
724 overwriting/non-overwriting atomic rename operation free of
725 race conditions.
726
727 OpenSSH server does it correctly on top of Linux/UNIX native
728 file systems (i.e. ext[234]>, ffs or zfs) but has problems on
729 file systems not supporting hard links (i.e. FAT) or on
730 operating systems with broken POSIX semantics as Windows.
731
732 cleanup => 1
733 If the transfer fails, attempts to remove the incomplete file.
734 Cleanup may fail (for example, if the SSH connection gets
735 broken).
736
737 This option is set by default when the transfer is not
738 resumable (i.e., when using `atomic` or `numbered` options).
739
740 best_effort => 1
741 Ignore minor errors, as setting time and permissions on the
742 remote file.
743
744 conversion => $conversion
745 on the fly data conversion of the file contents can be
746 performed with this option. See "On the fly data conversion"
747 below.
748
749 callback => $callback
750 $callback is a reference to a subroutine that will be called
751 after every iteration of the upload process.
752
753 The callback function will receive as arguments: the current
754 Net::SFTP::Foreign object; the data that is going to be written
755 to the remote file; the offset from the beginning of the file
756 in bytes; and the total size of the file in bytes.
757
758 The callback will be called one last time with an empty data
759 argument to indicate the end of the file transfer.
760
761 The size argument can change between calls as data is
762 transferred (for instance, when on the fly data conversion is
763 being performed).
764
765 This mechanism can be used to provide status messages, download
766 progress meters, etc.
767
768 The "abort" method can be called from inside the callback to
769 abort the transfer.
770
771 block_size => $bytes
772 size of the blocks the file is being split on for transfer.
773 Incrementing this value can improve performance but some
774 servers limit its size and if this limit is overpassed the
775 command will fail.
776
777 queue_size => $size
778 read and write requests are pipelined in order to maximize
779 transfer throughput. This option allows one to set the maximum
780 number of requests that can be concurrently waiting for a
781 server response.
782
783 late_set_perm => $bool
784 See the FAQ below.
785
786 $sftp->put_content($bytes, $remote, %opts)
787 Creates (or overwrites) a remote file whose content is the passed
788 data.
789
790 $sftp->put_symlink($local, $remote, %opts)
791 Copies a local symlink to the remote host.
792
793 The accepted options are "overwrite" and "numbered".
794
795 $sftp->abort()
796 $sftp->abort($msg)
797 This method, when called from inside a callback sub, causes the
798 current transfer to be aborted
799
800 The error state is set to SFTP_ERR_ABORTED and the optional $msg
801 argument is used as its textual value.
802
803 $sftp->ls($remote, %opts)
804 Fetches a listing of the remote directory $remote. If $remote is
805 not given, the current remote working directory is listed.
806
807 Returns a reference to a list of entries. Every entry is a
808 reference to a hash with three keys: "filename", the name of the
809 entry; "longname", an entry in a "long" listing like "ls -l"; and
810 "a", a Net::SFTP::Foreign::Attributes object containing file atime,
811 mtime, permissions and size.
812
813 my $ls = $sftp->ls('/home/foo')
814 or die "unable to retrieve directory: ".$sftp->error;
815
816 print "$_->{filename}\n" for (@$ls);
817
818 The options accepted by this method are as follows (note that usage
819 of some of them can degrade the method performance when reading
820 large directories):
821
822 wanted => qr/.../
823 Only elements whose name matches the given regular expression
824 are included on the listing.
825
826 wanted => sub {...}
827 Only elements for which the callback returns a true value are
828 included on the listing. The callback is called with two
829 arguments: the $sftp object and the current entry (a hash
830 reference as described before). For instance:
831
832 use Fcntl ':mode';
833
834 my $files = $sftp->ls ( '/home/hommer',
835 wanted => sub {
836 my $entry = $_[1];
837 S_ISREG($entry->{a}->perm)
838 } )
839 or die "ls failed: ".$sftp->error;
840
841 no_wanted => qr/.../
842 no_wanted => sub {...}
843 those options have the opposite result to their "wanted"
844 counterparts:
845
846 my $no_hidden = $sftp->ls( '/home/homer',
847 no_wanted => qr/^\./ )
848 or die "ls failed";
849
850 When both "no_wanted" and "wanted" rules are used, the
851 "no_wanted" rule is applied first and then the "wanted" one
852 (order is important if the callbacks have side effects,
853 experiment!).
854
855 ordered => 1
856 the list of entries is ordered by filename.
857
858 follow_links => 1
859 by default, the attributes on the listing correspond to a
860 "lstat" operation, setting this option causes the method to
861 perform "stat" requests instead. "lstat" attributes will still
862 appear for links pointing to non existent places.
863
864 atomic_readdir => 1
865 reading a directory is not an atomic SFTP operation and the
866 protocol draft does not define what happens if "readdir"
867 requests and write operations (for instance "remove" or "open")
868 affecting the same directory are intermixed.
869
870 This flag ensures that no callback call ("wanted", "no_wanted")
871 is performed in the middle of reading a directory and has to be
872 set if any of the callbacks can modify the file system.
873
874 realpath => 1
875 for every file object, performs a realpath operation and
876 populates the "realpath" entry.
877
878 names_only => 1
879 makes the method return a simple array containing the file
880 names from the remote directory only. For instance, these two
881 sentences are equivalent:
882
883 my @ls1 = @{ $sftp->ls('.', names_only => 1) };
884
885 my @ls2 = map { $_->{filename} } @{$sftp->ls('.')};
886
887 $sftp->find($path, %opts)
888 $sftp->find(\@paths, %opts)
889 Does a recursive search over the given directory $path (or
890 directories @path) and returns a list of the entries found or the
891 total number of them on scalar context.
892
893 Every entry is a reference to a hash with two keys: "filename", the
894 full path of the entry; and "a", a Net::SFTP::Foreign::Attributes
895 object containing file atime, mtime, permissions and size.
896
897 This method tries to recover and continue under error conditions.
898
899 The options accepted:
900
901 on_error => sub { ... }
902 the callback is called when some error is detected, two
903 arguments are passed: the $sftp object and the entry that was
904 being processed when the error happened. For instance:
905
906 my @find = $sftp->find( '/',
907 on_error => sub {
908 my ($sftp, $e) = @_;
909 print STDERR "error processing $e->{filename}: "
910 . $sftp->error;
911 } );
912
913 realpath => 1
914 calls method "realpath" for every entry, the result is stored
915 under the key "realpath". This option slows down the process as
916 a new remote query is performed for every entry, specially on
917 networks with high latency.
918
919 follow_links => 1
920 By default symbolic links are not resolved and appear as that
921 on the final listing. This option causes then to be resolved
922 and substituted by the target file system object. Dangling
923 links are ignored, though they generate a call to the
924 "on_error" callback when stat fails on them.
925
926 Following symbolic links can introduce loops on the search.
927 Infinite loops are detected and broken but files can still
928 appear repeated on the final listing under different names
929 unless the option "realpath" is also active.
930
931 ordered => 1
932 By default, the file system is searched in an implementation
933 dependent order (actually optimized for low memory
934 consumption). If this option is included, the file system is
935 searched in a deep-first, sorted by filename fashion.
936
937 wanted => qr/.../
938 wanted => sub { ... }
939 no_wanted => qr/.../
940 no_wanted => sub { ... }
941 These options have the same effect as on the "ls" method,
942 allowing to filter out unwanted entries (note that filename
943 keys contain full paths here).
944
945 The callbacks can also be used to perform some action instead
946 of creating the full listing of entries in memory (that could
947 use huge amounts of RAM for big file trees):
948
949 $sftp->find($src_dir,
950 wanted => sub {
951 my $fn = $_[1]->{filename}
952 print "$fn\n" if $fn =~ /\.p[ml]$/;
953 return undef # so it is discarded
954 });
955
956 descend => qr/.../
957 descend => sub { ... }
958 no_descend => qr/.../
959 no_descend => sub { ... }
960 These options, similar to the "wanted" ones, allow one to prune
961 the search, discarding full subdirectories. For instance:
962
963 use Fcntl ':mode';
964 my @files = $sftp->find( '.',
965 no_descend => qr/\.svn$/,
966 wanted => sub {
967 S_ISREG($_[1]->{a}->perm)
968 } );
969
970 "descend" and "wanted" rules are unrelated. A directory
971 discarded by a "wanted" rule will still be recursively searched
972 unless it is also discarded on a "descend" rule and vice versa.
973
974 atomic_readdir => 1
975 see "ls" method documentation.
976
977 names_only => 1
978 makes the method return a list with the names of the files only
979 (see "ls" method documentation).
980
981 equivalent:
982
983 my $ls1 = $sftp->ls('.', names_only => 1);
984
985 $sftp->glob($pattern, %opts)
986 performs a remote glob and returns the list of matching entries in
987 the same format as the "find" method.
988
989 This method tries to recover and continue under error conditions.
990
991 The given pattern can be a UNIX style pattern (see glob(7)) or a
992 Regexp object (i.e "qr/foo/"). In the later case, only files on the
993 current working directory will be matched against the Regexp.
994
995 Accepted options:
996
997 ignore_case => 1
998 by default the matching over the file system is carried out in
999 a case sensitive fashion, this flag changes it to be case
1000 insensitive.
1001
1002 This flag is ignored when a Regexp object is used as the
1003 pattern.
1004
1005 strict_leading_dot => 0
1006 by default, a dot character at the beginning of a file or
1007 directory name is not matched by wildcards ("*" or "?").
1008 Setting this flags to a false value changes this behaviour.
1009
1010 This flag is ignored when a Regexp object is used as the
1011 pattern.
1012
1013 follow_links => 1
1014 ordered => 1
1015 names_only => 1
1016 realpath => 1
1017 on_error => sub { ... }
1018 wanted => ...
1019 no_wanted => ...
1020 these options perform as on the "ls" method.
1021
1022 Some usage samples:
1023
1024 my $files = $sftp->glob("*/lib");
1025
1026 my $files = $sftp->glob("/var/log/dmesg.*.gz");
1027
1028 $sftp->set_cwd("/var/log");
1029 my $files = $sftp->glob(qr/^dmesg\.[\d+]\.gz$/);
1030
1031 my $files = $sftp->glob("*/*.pdf", strict_leading_dot => 0);
1032
1033 $sftp->rget($remote, $local, %opts)
1034 Recursively copies the contents of remote directory $remote to
1035 local directory $local. Returns the total number of elements
1036 (files, directories and symbolic links) successfully copied.
1037
1038 This method tries to recover and continue when some error happens.
1039
1040 The options accepted are:
1041
1042 umask => $umask
1043 use umask $umask to set permissions on the files and
1044 directories created.
1045
1046 copy_perm => $bool;
1047 if set to a true value, file and directory permissions are
1048 copied to the remote server (after applying the umask). On by
1049 default.
1050
1051 copy_time => $bool;
1052 if set to a true value, file atime and mtime are copied from
1053 the remote server. By default it is on.
1054
1055 overwrite => $bool
1056 if set to a true value, when a local file with the same name
1057 already exists it is overwritten. On by default.
1058
1059 numbered => $bool
1060 when required, adds a sequence number to local file names in
1061 order to avoid overwriting pre-existent remote files. Off by
1062 default.
1063
1064 newer_only => $bool
1065 if set to a true value, when a local file with the same name
1066 already exists it is overwritten only if the remote file is
1067 newer.
1068
1069 ignore_links => $bool
1070 if set to a true value, symbolic links are not copied.
1071
1072 on_error => sub { ... }
1073 the passed sub is called when some error happens. It is called
1074 with two arguments, the $sftp object and the entry causing the
1075 error.
1076
1077 wanted => ...
1078 no_wanted => ...
1079 This option allows one to select which files and directories
1080 have to be copied. See also "ls" method docs.
1081
1082 If a directory is discarded all of its contents are also
1083 discarded (as it is not possible to copy child files without
1084 creating the directory first!).
1085
1086 atomic => 1
1087 block_size => $block_size
1088 queue_size => $queue_size
1089 conversion => $conversion
1090 resume => $resume
1091 best_effort => $best_effort
1092 See "get" method docs.
1093
1094 $sftp->rput($local, $remote, %opts)
1095 Recursively copies the contents of local directory $local to remote
1096 directory $remote.
1097
1098 This method tries to recover and continue when some error happens.
1099
1100 Accepted options are:
1101
1102 umask => $umask
1103 use umask $umask to set permissions on the files and
1104 directories created.
1105
1106 copy_perm => $bool;
1107 if set to a true value, file and directory permissions are
1108 copied to the remote server (after applying the umask). On by
1109 default.
1110
1111 copy_time => $bool;
1112 if set to a true value, file atime and mtime are copied to the
1113 remote server. On by default.
1114
1115 perm => $perm
1116 Sets the permission of the copied files to $perm. For
1117 directories the value "$perm|0300" is used.
1118
1119 Note that when this option is used, umask and local permissions
1120 are ignored.
1121
1122 overwrite => $bool
1123 if set to a true value, when a remote file with the same name
1124 already exists it is overwritten. On by default.
1125
1126 newer_only => $bool
1127 if set to a true value, when a remote file with the same name
1128 already exists it is overwritten only if the local file is
1129 newer.
1130
1131 ignore_links => $bool
1132 if set to a true value, symbolic links are not copied
1133
1134 on_error => sub { ... }
1135 the passed sub is called when some error happens. It is called
1136 with two arguments, the $sftp object and the entry causing the
1137 error.
1138
1139 wanted => ...
1140 no_wanted => ...
1141 This option allows one to select which files and directories
1142 have to be copied. See also "ls" method docs.
1143
1144 If a directory is discarded all of its contents are also
1145 discarded (as it is not possible to copy child files without
1146 creating the directory first!).
1147
1148 atomic => 1
1149 block_size => $block_size
1150 queue_size => $queue_size
1151 conversion => $conversion
1152 resume => $resume
1153 best_effort => $best_effort
1154 late_set_perm => $bool
1155 see "put" method docs.
1156
1157 $sftp->rremove($dir, %opts)
1158 $sftp->rremove(\@dirs, %opts)
1159 recursively remove directory $dir (or directories @dirs) and its
1160 contents. Returns the number of elements successfully removed.
1161
1162 This method tries to recover and continue when some error happens.
1163
1164 The options accepted are:
1165
1166 on_error => sub { ... }
1167 This callback is called when some error is occurs. The
1168 arguments passed are the $sftp object and the current entry (a
1169 hash containing the file object details, see "ls" docs for more
1170 information).
1171
1172 wanted => ...
1173 no_wanted => ...
1174 Allows one to select which file system objects have to be
1175 deleted.
1176
1177 $sftp->mget($remote, $localdir, %opts)
1178 $sftp->mget(\@remote, $localdir, %opts)
1179 expands the wildcards on $remote or @remote and retrieves all the
1180 matching files.
1181
1182 For instance:
1183
1184 $sftp->mget(['/etc/hostname.*', '/etc/init.d/*'], '/tmp');
1185
1186 The method accepts all the options valid for "glob" and for "get"
1187 (except those that do not make sense :-)
1188
1189 $localdir is optional and defaults to the process current working
1190 directory ("cwd").
1191
1192 Files are saved with the same name they have in the remote server
1193 excluding the directory parts.
1194
1195 Note that name collisions are not detected. For instance:
1196
1197 $sftp->mget(["foo/file.txt", "bar/file.txt"], "/tmp")
1198
1199 will transfer the first file to "/tmp/file.txt" and later overwrite
1200 it with the second one. The "numbered" option can be used to avoid
1201 this issue.
1202
1203 $sftp->mput($local, $remotedir, %opts)
1204 $sftp->mput(\@local, $remotedir, %opts)
1205 similar to "mget" but works in the opposite direction transferring
1206 files from the local side to the remote one.
1207
1208 $sftp->join(@paths)
1209 returns the given path fragments joined in one path (currently the
1210 remote file system is expected to be UNIX like).
1211
1212 $sftp->open($path, $flags [, $attrs ])
1213 Sends the "SSH_FXP_OPEN" command to open a remote file $path, and
1214 returns an open handle on success. On failure returns "undef".
1215
1216 The returned value is a tied handle (see Tie::Handle) that can be
1217 used to access the remote file both with the methods available from
1218 this module and with perl built-ins. For instance:
1219
1220 # reading from the remote file
1221 my $fh1 = $sftp->open("/etc/passwd")
1222 or die $sftp->error;
1223 while (<$fh1>) { ... }
1224
1225 # writing to the remote file
1226 use Net::SFTP::Foreign::Constants qw(:flags);
1227 my $fh2 = $sftp->open("/foo/bar", SSH2_FXF_WRITE|SSH2_FXF_CREAT)
1228 or die $sftp->error;
1229 print $fh2 "printing on the remote file\n";
1230 $sftp->write($fh2, "writing more");
1231
1232 The $flags bitmap determines how to open the remote file as defined
1233 in the SFTP protocol draft (the following constants can be imported
1234 from Net::SFTP::Foreign::Constants):
1235
1236 SSH2_FXF_READ
1237 Open the file for reading. It is the default mode.
1238
1239 SSH2_FXF_WRITE
1240 Open the file for writing. If both this and "SSH2_FXF_READ"
1241 are specified, the file is opened for both reading and writing.
1242
1243 SSH2_FXF_APPEND
1244 Force all writes to append data at the end of the file.
1245
1246 As OpenSSH SFTP server implementation ignores this flag, the
1247 module emulates it (I will appreciate receiving feedback about
1248 the inter-operation of this module with other server
1249 implementations when this flag is used).
1250
1251 SSH2_FXF_CREAT
1252 If this flag is specified, then a new file will be created if
1253 one does not already exist.
1254
1255 SSH2_FXF_TRUNC
1256 Forces an existing file with the same name to be truncated to
1257 zero length when creating a file. "SSH2_FXF_CREAT" must also be
1258 specified if this flag is used.
1259
1260 SSH2_FXF_EXCL
1261 Causes the request to fail if the named file already exists.
1262 "SSH2_FXF_CREAT" must also be specified if this flag is used.
1263
1264 When creating a new remote file, $attrs allows one to set its
1265 initial attributes. $attrs has to be an object of class
1266 Net::SFTP::Foreign::Attributes.
1267
1268 $sftp->close($handle)
1269 Closes the remote file handle $handle.
1270
1271 Files are automatically closed on the handle "DESTROY" method when
1272 not done explicitly.
1273
1274 Returns true on success and undef on failure.
1275
1276 $sftp->read($handle, $length)
1277 reads $length bytes from an open file handle $handle. On success
1278 returns the data read from the remote file and undef on failure
1279 (including EOF).
1280
1281 $sftp->write($handle, $data)
1282 writes $data to the remote file $handle. Returns the number of
1283 bytes written or undef on failure.
1284
1285 $sftp->readline($handle)
1286 $sftp->readline($handle, $sep)
1287 in scalar context reads and returns the next line from the remote
1288 file. In list context, it returns all the lines from the current
1289 position to the end of the file.
1290
1291 By default "\n" is used as the separator between lines, but a
1292 different one can be used passing it as the second method argument.
1293 If the empty string is used, it returns all the data from the
1294 current position to the end of the file as one line.
1295
1296 $sftp->getc($handle)
1297 returns the next character from the file.
1298
1299 $sftp->seek($handle, $pos, $whence)
1300 sets the current position for the remote file handle $handle. If
1301 $whence is 0, the position is set relative to the beginning of the
1302 file; if $whence is 1, position is relative to current position and
1303 if $<$whence> is 2, position is relative to the end of the file.
1304
1305 returns a trues value on success, undef on failure.
1306
1307 $sftp->tell($fh)
1308 returns the current position for the remote file handle $handle.
1309
1310 $sftp->eof($fh)
1311 reports whether the remote file handler points at the end of the
1312 file.
1313
1314 $sftp->flush($fh)
1315 writes to the remote file any pending data and discards the read
1316 cache.
1317
1318 Note that this operation just sends data cached locally to the
1319 remote server. You may like to call "fsync" (when supported)
1320 afterwards to ensure that data is actually flushed to disc.
1321
1322 $sftp->fsync($fh)
1323 On servers supporting the "fsync@openssh.com" extension, this
1324 method calls fysnc(2) on the remote side, which usually flushes
1325 buffered changes to disk.
1326
1327 $sftp->sftpread($handle, $offset, $length)
1328 low level method that sends a SSH2_FXP_READ request to read from an
1329 open file handle $handle, $length bytes starting at $offset.
1330
1331 Returns the data read on success and undef on failure.
1332
1333 Some servers (for instance OpenSSH SFTP server) limit the size of
1334 the read requests and so the length of data returned can be smaller
1335 than requested.
1336
1337 $sftp->sftpwrite($handle, $offset, $data)
1338 low level method that sends a "SSH_FXP_WRITE" request to write to
1339 an open file handle $handle, starting at $offset, and where the
1340 data to be written is in $data.
1341
1342 Returns true on success and undef on failure.
1343
1344 $sftp->opendir($path)
1345 Sends a "SSH_FXP_OPENDIR" command to open the remote directory
1346 $path, and returns an open handle on success (unfortunately,
1347 current versions of perl does not support directory operations via
1348 tied handles, so it is not possible to use the returned handle as a
1349 native one).
1350
1351 On failure returns "undef".
1352
1353 $sftp->closedir($handle)
1354 closes the remote directory handle $handle.
1355
1356 Directory handles are closed from their "DESTROY" method when not
1357 done explicitly.
1358
1359 Return true on success, undef on failure.
1360
1361 $sftp->readdir($handle)
1362 returns the next entry from the remote directory $handle (or all
1363 the remaining entries when called in list context).
1364
1365 The return values are a hash with three keys: "filename",
1366 "longname" and "a". The "a" value contains a
1367 Net::SFTP::Foreign::Attributes object describing the entry.
1368
1369 Returns undef on error or when no more entries exist on the
1370 directory.
1371
1372 $sftp->stat($path_or_fh)
1373 performs a "stat" on the remote file and returns a
1374 Net::SFTP::Foreign::Attributes object with the result values. Both
1375 paths and open remote file handles can be passed to this method.
1376
1377 Returns undef on failure.
1378
1379 $sftp->fstat($handle)
1380 this method is deprecated.
1381
1382 $sftp->lstat($path)
1383 this method is similar to "stat" method but stats a symbolic link
1384 instead of the file the symbolic links points to.
1385
1386 $sftp->setstat($path_or_fh, $attrs)
1387 sets file attributes on the remote file. Accepts both paths and
1388 open remote file handles.
1389
1390 Returns true on success and undef on failure.
1391
1392 $sftp->fsetstat($handle, $attrs)
1393 this method is deprecated.
1394
1395 $sftp->truncate($path_or_fh, $size)
1396 $sftp->chown($path_or_fh, $uid, $gid)
1397 $sftp->chmod($path_or_fh, $perm)
1398 $sftp->utime($path_or_fh, $atime, $mtime)
1399 Shortcuts around "setstat" method.
1400
1401 $sftp->remove($path)
1402 Sends a "SSH_FXP_REMOVE" command to remove the remote file $path.
1403 Returns a true value on success and undef on failure.
1404
1405 $sftp->mkdir($path, $attrs)
1406 Sends a "SSH_FXP_MKDIR" command to create a remote directory $path
1407 whose attributes are initialized to $attrs (a
1408 Net::SFTP::Foreign::Attributes object).
1409
1410 Returns a true value on success and undef on failure.
1411
1412 The $attrs argument is optional.
1413
1414 $sftp->mkpath($path, $attrs, $parent)
1415 This method is similar to "mkdir" but also creates any non-existent
1416 parent directories recursively.
1417
1418 When the optional argument $parent has a true value, just the
1419 parent directory of the given path (and its ancestors as required)
1420 is created.
1421
1422 For instance:
1423
1424 $sftp->mkpath("/tmp/work", undef, 1);
1425 my $fh = $sftp->open("/tmp/work/data.txt",
1426 SSH2_FXF_WRITE|SSH2_FXF_CREAT);
1427
1428 $sftp->rmdir($path)
1429 Sends a "SSH_FXP_RMDIR" command to remove a remote directory $path.
1430 Returns a true value on success and undef on failure.
1431
1432 $sftp->realpath($path)
1433 Sends a "SSH_FXP_REALPATH" command to canonicalise $path to an
1434 absolute path. This can be useful for turning paths containing '..'
1435 into absolute paths.
1436
1437 Returns the absolute path on success, "undef" on failure.
1438
1439 When the given path points to an nonexistent location, what one
1440 gets back is server dependent. Some servers return a failure
1441 message and others a canonical version of the path.
1442
1443 $sftp->rename($old, $new, %opts)
1444 Sends a "SSH_FXP_RENAME" command to rename $old to $new. Returns a
1445 true value on success and undef on failure.
1446
1447 Accepted options are:
1448
1449 overwrite => $bool
1450 By default, the rename operation fails when a file $new already
1451 exists. When this options is set, any previous existent file is
1452 deleted first (the "atomic_rename" operation will be used if
1453 available).
1454
1455 Note than under some conditions the target file could be
1456 deleted and afterwards the rename operation fail.
1457
1458 $sftp->atomic_rename($old, $new)
1459 Renames a file using the "posix-rename@openssh.com" extension when
1460 available.
1461
1462 Unlike the "rename" method, it overwrites any previous $new file.
1463
1464 $sftp->readlink($path)
1465 Sends a "SSH_FXP_READLINK" command to read the path where the
1466 symbolic link is pointing.
1467
1468 Returns the target path on success and undef on failure.
1469
1470 $sftp->symlink($sl, $target)
1471 Sends a "SSH_FXP_SYMLINK" command to create a new symbolic link $sl
1472 pointing to $target.
1473
1474 $target is stored as-is, without any path expansion taken place on
1475 it. Use "realpath" to normalize it:
1476
1477 $sftp->symlink("foo.lnk" => $sftp->realpath("../bar"))
1478
1479 $sftp->hardlink($hl, $target)
1480 Creates a hardlink on the server.
1481
1482 This command requires support for the 'hardlink@openssh.com'
1483 extension on the server (available in OpenSSH from version 5.7).
1484
1485 $sftp->statvfs($path)
1486 $sftp->fstatvfs($fh)
1487 On servers supporting "statvfs@openssh.com" and
1488 "fstatvfs@openssh.com" extensions respectively, these methods
1489 return a hash reference with information about the file system
1490 where the file named $path or the open file $fh resides.
1491
1492 The hash entries are:
1493
1494 bsize => file system block size
1495 frsize => fundamental fs block size
1496 blocks => number of blocks (unit f_frsize)
1497 bfree => free blocks in file system
1498 bavail => free blocks for non-root
1499 files => total file inodes
1500 ffree => free file inodes
1501 favail => free file inodes for to non-root
1502 fsid => file system id
1503 flag => bit mask of f_flag values
1504 namemax => maximum filename length
1505
1506 The values of the f_flag bit mask are as follows:
1507
1508 SSH2_FXE_STATVFS_ST_RDONLY => read-only
1509 SSH2_FXE_STATVFS_ST_NOSUID => no setuid
1510
1511 $sftp->test_d($path)
1512 Checks whether the given path corresponds to a directory.
1513
1514 $sftp->test_e($path)
1515 Checks whether a file system object (file, directory, etc.) exists
1516 at the given path.
1517
1518 $sftp->disconnect
1519 Closes the SSH connection to the remote host. From this point the
1520 object becomes mostly useless.
1521
1522 Usually, this method should not be called explicitly, but
1523 implicitly from the DESTROY method when the object goes out of
1524 scope.
1525
1526 See also the documentation for the "autodiscconnect" constructor
1527 argument.
1528
1529 $sftp->autodisconnect($ad)
1530 Sets the "autodisconnect" behaviour.
1531
1532 See also the documentation for the "autodiscconnect" constructor
1533 argument. The values accepted here are the same as there.
1534
1535 On the fly data conversion
1536 Some of the methods on this module allow one to perform on the fly data
1537 conversion via the "conversion" option that accepts the following
1538 values:
1539
1540 conversion => 'dos2unix'
1541 Converts CR+LF line endings (as commonly used under MS-DOS) to LF
1542 (UNIX).
1543
1544 conversion => 'unix2dos'
1545 Converts LF line endings (UNIX) to CR+LF (DOS).
1546
1547 conversion => sub { CONVERT $_[0] }
1548 When a callback is given, it is invoked repeatedly as chunks of
1549 data become available. It has to change $_[0] in place in order to
1550 perform the conversion.
1551
1552 Also, the subroutine is called one last time with and empty data
1553 string to indicate that the transfer has finished, so that
1554 intermediate buffers can be flushed.
1555
1556 Note that when writing conversion subroutines, special care has to
1557 be taken to handle sequences crossing chunk borders.
1558
1559 The data conversion is always performed before any other callback
1560 subroutine is called.
1561
1562 See the Wikipedia entry on line endings
1563 <http://en.wikipedia.org/wiki/Newline> or the article Understanding
1564 Newlines by Xavier Noria
1565 (<http://www.onlamp.com/pub/a/onlamp/2006/08/17/understanding-newlines.html>)
1566 for details about the different conventions.
1567
1569 Closing the connection:
1570 Q: How do I close the connection to the remote server?
1571
1572 A: let the $sftp object go out of scope or just undefine it:
1573
1574 undef $sftp;
1575
1576 Using Net::SFTP::Foreign from a cron script:
1577 Q: I wrote a script for performing sftp file transfers that works
1578 beautifully from the command line. However when I try to run the
1579 same script from cron it fails with a broken pipe error:
1580
1581 open2: exec of ssh -l user some.location.com -s sftp
1582 failed at Net/SFTP/Foreign.pm line 67
1583
1584 A: "ssh" is not on your cron PATH.
1585
1586 The remedy is either to add the location of the "ssh" application
1587 to your cron PATH or to use the "ssh_cmd" option of the "new"
1588 method to hardcode the location of "ssh" inside your script, for
1589 instance:
1590
1591 my $ssh = Net::SFTP::Foreign->new($host,
1592 ssh_cmd => '/usr/local/ssh/bin/ssh');
1593
1594 "more" constructor option expects an array reference:
1595 Q: I'm trying to pass in the private key file using the -i option,
1596 but it keep saying it couldn't find the key. What I'm doing wrong?
1597
1598 A: The "more" argument on the constructor expects a single option
1599 or a reference to an array of options. It will not split an string
1600 containing several options.
1601
1602 Arguments to SSH options have to be also passed as different
1603 entries on the array:
1604
1605 my $sftp = Net::SFTP::Foreign->new($host,
1606 more => [qw(-i /home/foo/.ssh/id_dsa)]);
1607
1608 Note also that latest versions of Net::SFTP::Foreign support the
1609 "key_path" argument:
1610
1611 my $sftp = Net::SFTP::Foreign->new($host,
1612 key_path => '/home/foo/.ssh/id_dsa');
1613
1614 Plink and password authentication
1615 Q: Why password authentication is not supported for the plink SSH
1616 client?
1617
1618 A: A bug in plink breaks it.
1619
1620 Newer versions of Net::SFTP::Foreign pass the password to "plink"
1621 using its "-pw" option. As this feature is not completely secure a
1622 warning is generated.
1623
1624 It can be silenced (though, don't do it without understanding why
1625 it is there, please!) as follows:
1626
1627 no warnings 'Net::SFTP::Foreign';
1628 my $sftp = Net::SFTP::Foreign->new('foo@bar',
1629 ssh_cmd => 'plink',
1630 password => $password);
1631 $sftp->die_on_error;
1632
1633 Plink
1634 Q: What is "plink"?
1635
1636 A: Plink is a command line tool distributed with the PuTTY
1637 <http://the.earth.li/~sgtatham/putty/> SSH client. Very popular
1638 between MS Windows users, it is also available for Linux and other
1639 UNIX now.
1640
1641 Put method fails
1642 Q: put fails with the following error:
1643
1644 Couldn't setstat remote file: The requested operation cannot be
1645 performed because there is a file transfer in progress.
1646
1647 A: Try passing the "late_set_perm" option to the put method:
1648
1649 $sftp->put($local, $remote, late_set_perm => 1)
1650 or die "unable to transfer file: " . $sftp->error;
1651
1652 Some servers do not support the "fsetstat" operation on open file
1653 handles. Setting this flag allows one to delay that operation until
1654 the file has been completely transferred and the remote file handle
1655 closed.
1656
1657 Also, send me a bug report containing a dump of your $sftp object
1658 so I can add code for your particular server software to activate
1659 the work-around automatically.
1660
1661 Put method fails even with late_set_perm set
1662 Q: I added "late_set_perm => 1" to the put call, but we are still
1663 receiving the error "Couldn't setstat remote file (setstat)".
1664
1665 A: Some servers forbid the SFTP "setstat" operation used by the
1666 "put" method for replicating the file permissions and time-stamps
1667 on the remote side.
1668
1669 As a work around you can just disable the feature:
1670
1671 $sftp->put($local_file, $remote_file,
1672 copy_perm => 0, copy_time => 0);
1673
1674 Disable password authentication completely
1675 Q: When we try to open a session and the key either doesn't exist
1676 or is invalid, the child SSH hangs waiting for a password to be
1677 entered. Is there a way to make this fail back to the Perl program
1678 to be handled?
1679
1680 A: Disable anything but public key SSH authentication calling the
1681 new method as follows:
1682
1683 $sftp = Net::SFTP::Foreign->new($host,
1684 more => [qw(-o PreferredAuthentications=publickey)])
1685
1686 See ssh_config(5) for the details.
1687
1688 Understanding "$attr->perm" bits
1689 Q: How can I know if a directory entry is a
1690 (directory|link|file|...)?
1691
1692 A: Use the "S_IS*" functions from Fcntl. For instance:
1693
1694 use Fcntl qw(S_ISDIR);
1695 my $ls = $sftp->ls or die $sftp->error;
1696 for my $entry (@$ls) {
1697 if (S_ISDIR($entry->{a}->perm)) {
1698 print "$entry->{filename} is a directory\n";
1699 }
1700 }
1701
1702 Host key checking
1703 Q: Connecting to a remote server with password authentication fails
1704 with the following error:
1705
1706 The authenticity of the target host can not be established,
1707 connect from the command line first
1708
1709 A: That probably means that the public key from the remote server
1710 is not stored in the "~/.ssh/known_hosts" file. Run an SSH
1711 Connection from the command line as the same user as the script and
1712 answer "yes" when asked to confirm the key supplied.
1713
1714 Example:
1715
1716 $ ssh pluto /bin/true
1717 The authenticity of host 'pluto (172.25.1.4)' can't be established.
1718 RSA key fingerprint is 41:b1:a7:86:d2:a9:7b:b0:7f:a1:00:b7:26:51:76:52.
1719 Are you sure you want to continue connecting (yes/no)? yes
1720
1721 Your SSH client may also support some flag to disable this check,
1722 but doing it can ruin the security of the SSH protocol so I advise
1723 against its usage.
1724
1725 Example:
1726
1727 # Warning: don't do that unless you fully understand
1728 # its security implications!!!
1729 $sftp = Net::SFTP::Foreign->new($host,
1730 more => [-o => 'StrictHostKeyChecking no'],
1731 ...);
1732
1734 These are the currently known bugs:
1735
1736 - Doesn't work on VMS:
1737 The problem is related to IPC::Open3 not working on VMS. Patches
1738 are welcome!
1739
1740 - Dirty cleanup:
1741 On some operating systems, closing the pipes used to communicate
1742 with the slave SSH process does not terminate it and a work around
1743 has to be applied. If you find that your scripts hung when the
1744 $sftp object gets out of scope, try setting
1745 $Net::SFTP::Foreign::dirty_cleanup to a true value and also send me
1746 a report including the value of $^O on your machine and the OpenSSH
1747 version.
1748
1749 From version 0.90_18 upwards, a dirty cleanup is performed anyway
1750 when the SSH process does not terminate by itself in 8 seconds or
1751 less.
1752
1753 - Reversed symlink arguments:
1754 This package uses the non-conforming OpenSSH argument order for the
1755 SSH_FXP_SYMLINK command that seems to be the de facto standard.
1756 When interacting with SFTP servers that follow the SFTP
1757 specification, the "symlink" method will interpret its arguments in
1758 reverse order.
1759
1760 - IPC::Open3 bugs on Windows
1761 On Windows the IPC::Open3 module is used to spawn the slave SSH
1762 process. That module has several nasty bugs (related to STDIN,
1763 STDOUT and STDERR being closed or not being assigned to file
1764 descriptors 0, 1 and 2 respectively) that will cause the connection
1765 to fail.
1766
1767 Specifically this is known to happen under mod_perl/mod_perl2.
1768
1769 - Password authentication on HP-UX
1770 For some unknown reason, it seems that when using the module on HP-
1771 UX, number signs ("#") in password need to be escaped ("\#"). For
1772 instance:
1773
1774 my $password = "foo#2014";
1775 $password =~ s/#/\\#/g if $running_in_hp_ux;
1776 my $ssh = Net::OpenSSH->new($host, user => $user,
1777 password => $password);
1778
1779 I don't have access to an HP-UX machine, and so far nobody using it
1780 has been able to explain this behaviour. Patches welcome!
1781
1782 - Taint mode and data coming through SFTP
1783 When the module finds it is being used from a script started in
1784 taint mode, on every method call it checks all the arguments passed
1785 and dies if any of them is tainted. Also, any data coming through
1786 the SFTP connection is marked as tainted.
1787
1788 That generates an internal conflict for those methods that under
1789 the hood query the remote server multiple times, using data from
1790 responses to previous queries (tainted) to build new ones (die!).
1791
1792 I don't think a generic solution could be applied to this issue
1793 while honoring the taint-mode spirit (and erring on the safe side),
1794 so my plan is to fix that in a case by case manner.
1795
1796 So, please report any issue you find with taint mode!
1797
1798 Also, the following features should be considered experimental:
1799
1800 - support for Tectia server
1801
1802 - numbered feature
1803
1804 - autodie mode
1805
1806 - best_effort feature
1807
1809 To report bugs, send me and email or use the CPAN bug tracking system
1810 at <http://rt.cpan.org>.
1811
1812 Commercial support
1813 Commercial support, professional services and custom software
1814 development around this module are available through my current
1815 company. Drop me an email with a rough description of your requirements
1816 and we will get back to you ASAP.
1817
1818 My wishlist
1819 If you like this module and you're feeling generous, take a look at my
1820 Amazon Wish List: <http://amzn.com/w/1WU1P6IR5QZ42>
1821
1822 Also consider contributing to the OpenSSH project this module builds
1823 upon: <http://www.openssh.org/donations.html>.
1824
1826 Information about the constants used on this module is available from
1827 Net::SFTP::Foreign::Constants. Information about attribute objects is
1828 available from Net::SFTP::Foreign::Attributes.
1829
1830 General information about SSH and the OpenSSH implementation is
1831 available from the OpenSSH web site at <http://www.openssh.org/> and
1832 from the sftp(1) and sftp-server(8) manual pages.
1833
1834 Net::SFTP::Foreign integrates nicely with my other module Net::OpenSSH.
1835
1836 Net::SFTP::Foreign::Backend::Net_SSH2 allows one to run
1837 Net::SFTP::Foreign on top of Net::SSH2 (nowadays, this combination is
1838 probably the best option under Windows).
1839
1840 Modules offering similar functionality available from CPAN are
1841 Net::SFTP and Net::SSH2.
1842
1843 Test::SFTP allows one to run tests against a remote SFTP server.
1844
1845 autodie.
1846
1848 Copyright (c) 2005-2020 Salvador FandiƱo (sfandino@yahoo.com).
1849
1850 Copyright (c) 2001 Benjamin Trott, Copyright (c) 2003 David Rolsky.
1851
1852 _glob_to_regex method based on code (c) 2002 Richard Clamp.
1853
1854 All rights reserved. This program is free software; you can
1855 redistribute it and/or modify it under the same terms as Perl itself.
1856
1857 The full text of the license can be found in the LICENSE file included
1858 with this module.
1859
1860
1861
1862perl v5.32.0 2020-07-28 Net::SFTP::Foreign(3)