NAME
Net::SFTP::Foreign - Secure File Transfer Protocol client
SYNOPSIS
use Net::SFTP::Foreign;
my $sftp = Net::SFTP::Foreign->new($host);
$sftp->get("foo", "bar");
$sftp->put("bar", "baz");
DESCRIPTION
WARNING: This is a development version, expect bugs on it!!!
WARNING: This package is not compatible with Net::SFTP anymore!!!
SFTP stands for Secure File Transfer Protocol and is a method of transferring files between machines over a secure, encrypted connection (as opposed to regular FTP, which functions over an insecure connection). The security in SFTP comes through its integration with SSH, which provides an encrypted transport layer over which the SFTP commands are executed.
Net::SFTP::Foreign is a Perl client for the SFTP. It provides a subset of the commands listed in the SSH File Transfer Protocol IETF draft, which can be found at http://www.openssh.org/txt/draft-ietf-secsh-filexfer-02.txt (also included on this package distribution, on the rfc
directory).
Net::SFTP::Foreign uses any compatible ssh
command installed on your system (for instance, OpenSSH ssh
) to establish the secure connection to the remote server.
Formelly Net::SFTP::Foreign was a hacked version of Net::SFTP, but from version 0.90 it has been almost completelly rewritten from scratch and a new much improved and incompatible API introduced (an adaptor module, Net::SFTP::Foreign::Compat, is also provided for backward compatibility).
Net::SFTP::Foreign Vs. Net::SFTP
Why should I prefer Net::SFTP::Foreign over Net::SFTP?
Well, both modules have their pros and cons:
Net::SFTP::Foreign does not requiere a bunch of additional modules and external libraries to work, just the OpenBSD SSH client (or any other client compatible enough).
I trust OpenSSH SSH client more than Net::SSH::Perl, there are lots of paranoid people ensuring that OpenSSH doesn't have security holes!!!
If you have an SSH infrastructure already deployed, by using the same binary SSH client, Net::SFTP::Foreign ensures a seamless integration within your environment (configuration files, keys, etc.).
Net::SFTP::Foreign is much faster transferring files, specially over networks with high (relative) latency.
Net::SFTP::Foreign provides several high level methods not available from Net::SFTP as for instance find
, rget
, rput
.
On the other hand, using the external command means an additional proccess being launched and running, depending on your OS this could eat more resources than the in process pure perl implementation provided by Net::SSH::Perl.
Net::SFTP::Foreign supports version 2 of the SSH protocol only.
Finally Net::SFTP::Foreign does not (and will never) allow to use passwords for authentication. Net::SFTP does.
USAGE
Most of the methods available from this package return undef on failure and a true value or the requested data on success. $sftp->error
can be used to check explicitly for an error after every method call.
Inside any method, a low-level network error (for instance, a broken SSH onnection) will cause the method to die.
- Net::SFTP::Foreign->new($host, %args)
-
Opens a new SFTP connection with a remote host
$host
, and returns a Net::SFTP::Foreign object representing that open connection.%args
can contain:- host => $hostname
-
remote host name
- user => $username
-
username to log in to the remote server. This should be your SSH login, and can be empty, in which case the username is drawn from the user executing the process.
- port => $portnumber
-
port number where the remote SSH server is listening
- more => [@more_ssh_args]
-
additional args passed to
ssh
command. - ssh_cmd => $sshcmd
-
name of the external SSH client. By default
ssh
is used. - open2_cmd => [@cmd]
- open2_cmd => $cmd;
-
allows to completely redefine how
ssh
is called. Its arguments are passed to IPC::Open2::open2 to open a pipe to the remote server.
If stablishing the connection fails, an exception is raised, you can use
eval
to catch it:my $sftp = eval { Net::SFTP::Foreign->new(foo) }; if ($@) { print STDERR "something went wrong ($@)" }
The exit code for the
ssh
command is available in$?
, though OpenSSHssh
does not return meaningful codes. For debugging purposes you can runssh
in verbose mode passing it the-v
option via themore
option.my $sftp = Net::SFTP::Foreign->new($host, more => '-v');
- $sftp->error
-
Returns the error code from the last executed command. The value returned is similar to
$!
, when used as a string it yields the corresponding error string.See Net::SFTP::Foreign::Constants for a list of possible error codes and how to import them on your scripts.
- $sftp->status
-
Returns the code from the last SSH2_FXP_STATUS response. It is also a dualvar that yields the status string when used as a string.
Usually
$sftp->error
should be checked first to see if there was any error and then$sftp->status
to find out its low level cause. - $sftp->get($remote, $local, %options)
-
Copies remote file
$remote
to local $local. By default file attributes are also copied (permissions, atime and mtime).The method accepts several options (not all combinations are possible):
- copy_time => $bool
-
determines if access and modification time attributes have to be copied from remote file. Default is to copy them.
- copy_perms => $bool
-
determines if permision attributes have to be copied from remote file. Default is to copy them after applying the local process umask.
- umask => $umask
-
allows to select the umask to apply when setting the permissions of the copied file. Default is to use the umask for the current process.
- perm => $perm
-
sets the permision mask of the file to be $perm, umask and remote permissions are ignored.
- block_size => $bytes
-
size of the blocks the file is being splittered on for transfer. Incrementing this value can improve performance but some servers limit its size.
- callback => $callback
-
$callback
is a reference to a subroutine that will be called after every iteration of the download process.The callback function will receive as arguments: the current Net::SFTP::Foreign object; the data read from the remote file; the offset from the beginning of the file in bytes; and the total size of the file in bytes.
This mechanism can be used to provide status messages, download progress meters, etc.:
sub callback { my($sftp, $data, $offset, $size) = @_; print "Read $offset / $size bytes\r"; }
- $sftp->get_content($remote)
-
Returns the content of the remote file.
- $sftp->put($local, $remote, %opts)
-
Uploads a file
$local
from the local host to the remote host, and saves it as$remote
. By default file attributes are also copied.This method accepts several options:
- copy_time => $bool
-
determines if access and modification time attributes have to be copied from remote file. Default is to copy them.
- copy_perms => $bool
-
determines if permision attributes have to be copied from remote file. Default is to copy them after applying the local process umask.
- umask => $umask
-
allows to select the umask to apply when setting the permissions of the copied file. Default is to use the umask for the current process.
- perm => $perm
-
sets the permision mask of the file to be $perm, umask and remote permissions are ignored.
- block_size => $bytes
-
size of the blocks the file is being splittered on for transfer. Incrementing this value can improve performance but some servers limit its size and if this limit is overpassed the command will fail.
- callback => $callback
-
$callback
is a reference to a subrutine that will be called after every iteration of the upload process.The callback function will receive as arguments: the current Net::SFTP::Foreign object; the data that is going to be written to the remote file; the offset from the beginning of the file in bytes; and the total size of the file in bytes.
This mechanism can be used to provide status messages, download progress meters, etc.
- $sftp->ls($remote, %opts)
-
Fetches a directory listing of the remote directory
$remote
.Returns a reference to a list of entries. Every entry is a reference to a hash with three keys:
filename
, the name of the entry;longname
, an entry in a "long" listing likels -l
; anda
, a Net::SFTP::Foreign::Attributes object containing file atime, mtime, permissions and size.my $ls = $sftp->ls('/home/foo') or die "unable to retrieve directory: ".$sftp->error; print "$_->{filename}\n" for (@$ls);
The options accepted by this method are:
- wanted => qr/.../
-
Only elements which filename match the regular expresion are included on the listing.
- wanted => sub {...}
-
Only elements for which the callback returns a true value are included on the listing. The callback is called with two arguments: the
$sftp
object and the current entry (a hash reference as described before). For instance:use Fcntl ':mode'; my $files = $sftp->ls ( '/home/hommer', wanted => sub { my $entry = $_[1]; S_ISREG($entry->{a}->perm) } ) or die "ls failed: ".$sftp->error;
- no_wanted => qr/.../
- no_wanted => sub {...}
-
those options have the oposite result to their
wanted
counterparts:my $no_hidden = $sftp->ls( '/home/homer', no_wanted => qr/^\./ ) or die "ls failed";
When both
no_wanted
andwanted
rules are used, theno_wanted
rule is applied first and then thewanted
one (order is important if the callbacks have side effects). - ordered => 1
-
the list of entries is ordered by filename.
- follow_links => 1
-
by default, the attributes on the listing correspond to a
lstat
operation, setting this option causes the method to performstat
requests instead.lstat
attributes will stil appear for links pointing to non existant places.
- $sftp->find($path, %opts)
- $sftp->find(\@paths, %opts)
-
Does a recursive seach over the given directory
$path
(or directories@path
) and returns a list of the entries found or the total number of them on scalar context.Every entry is a reference to a hash with two keys:
filename
, the full path of the entry; anda
, a Net::SFTP::Foreign::Attributes object containing file atime, mtime, permissions and size.This method tries to recover and continue under error conditions.
The options accepted by this method are:
- on_error => sub { ... }
-
the callback is called when some error is detected, two arguments are passed: the
$sftp
object and the entry that was being processed when the error happened. For instance:my @find = $sftp->find( '/', on_error => sub { my ($sftp, $e) = @_; print STDERR "error processing $e->{filename}: " . $sftp->error; } );
- realpath => 1
-
calls method
realpath
for every entry, the result is stored under the keyrealpath
. This option slows down the process as a new remote query is performed for every entry, specially on networks with high latency. - follow_links => 1
-
By default symbolic links are not resolved and appear as that on the final listing. This option causes then to be resolved and substituted by the target file system object. Dangling links are ignored, though they generate a call to the
on_error
callback when stat'ing them fails.Following sym links can introduce loops on the search. Infinite loops are detected and broken but files can still appear repeated on the final listing under different names unless the option
realpath
is also actived. - ordered => 1
-
By default, the file system is searched in an implementation dependant order (actually optimized for low memory comsumption). If this option is included, the file system is searched in a deep-first, sorted by filename fashion.
- wanted => qr/.../
- wanted => sub { ... }
- no_wanted => qr/.../
- no_wanted => sub { ... }
-
These options have the same effect as on the
ls
method, allowing to filter out unwanted entries (note that filename keys contain full paths here).The callbacks can also be used to perform some action instead of creating the full listing of entries in memory (that could use huge amounts of RAM for big file trees):
$sftp->find($src_dir, wanted => sub { my $fn = $_[1]->{filename} print "$fn\n" if $fn =~ /\.p[ml]$/; return undef # so it is discarded });
- descend => qr/.../
- descend => sub { ... }
- no_descend => qr/.../
- no_descend => sub { ... }
-
These options, similar to the
wanted
ones allow to prune the search, discarding full subdirectories. For instance:use Fcntl ':mode'; my @files = $sftp->find( '.', no_descend => qr/\.svn$/, wanted => sub { S_ISREG($_[1]->{a}->perm) } );
descend
andwanted
rules are unrelated. A directory discarded by awanted
rule will still be recursively searched unless it is also discarded on adescend
rule and vice-versa.
- $sftp->glob($pattern, %opts)
-
performs a remote glob and returns the list of matching entries in the same format as
find
method.The options accepted by this command are:
- ignore_case => 1
-
by default the matching over the file system is carried out in a case sensitive fashion, this flags changes it to be case insensitive.
- strict_leading_dot => 0
-
by default, a dot character at the begining of a file or directory name is not matched by willcards (
*
or?
). Setting this flags to a false value changes the behaviour. - follow_links => 1
- ordered => 1
- on_error => sub { ... }
- wanted => ...
- no_wanted => ...
-
these options perform as on the
ls
method.
- $sftp->rget($remote, $local, %opts)
-
Recursively copies the contents of remote directory
$remote
to local directory$local
. Not implemented yet. - $sftp->rput($local, $remote, %opts)
-
Recursively copies the contents of local directory
$local
to remote directory$remote
. Not implemented yet. - $sftp->join(@paths)
-
returns the given path fragments joined in one path (currently the remote file system is expected to be Unix like).
- $sftp->open($path, $flags [, $attrs ])
-
Sends the
SSH_FXP_OPEN
command to open a remote file$path
, and returns an open handle on success. On failure returnsundef
. The "open handle" is not a Perl filehandle, nor is it a file descriptor; it is merely a marker used to identify the open file between the client and the server.$flags
should be a bitmask of open flags, whose values can be obtained from Net::SFTP::Foreign::Constants:use Net::SFTP::Foreign::Constants qw( :flags );
$attrs
should be a Net::SFTP::Foreign::Attributes object, specifying the initial attributes for the file$path
. If you're opening the file for reading only,$attrs
can be left blank, in which case it will be initialized to an empty set of attributes. - $sftp->read($handle, $offset, $length)
-
Sends the
SSH_FXP_READ
command to read from an open file handle$handle
, starting at$offset
, and reading at most$length
bytes.On success returns the data read from the remote file and undef on failure.
You can test if the end of file has been reached through $sftp->status:
my $data = $sftp->read($handle, $offset, $length) if (!defined $data) { if ($sftp->status == SSH2_FX_EOF) { # end of file ... } else { # other error } }
Some servers (for instance OpenSSH SFTP server) limit the size of the read requests and so the length of data returned can be smaller than the requested.
- $sftp->write($handle, $offset, $data)
-
Sends the
SSH_FXP_WRITE
command to write to an open file handle$handle
, starting at$offset
, and where the data to be written is in$data
.Returns true on success and undef on failure.
- $sftp->close($handle)
-
Sends the
SSH_FXP_CLOSE
command to close either an open file or open directory, identified by$handle
(the handle returned from eitheropen
oropendir
).Returns true on success and undef on failure.
- $sftp->stat($path)
-
performs a
stat
on the remote file$path
and returns a Net::SFTP::Foreign::Attributes object with the result values.Returns undef on failure.
- $sftp->fstat($handle)
-
is similar to the previous method but is argument has to be a handle to an already open remote file instead of a file name.
- $sftp->lstat($path)
-
is similar to
stat
method but stats a symbolic link instead of the file the symbolic links points to. - $sftp->setstat($path, $attrs)
-
sets file attributes on remote file
$path
.Returns true on success and undef on failure.
- $sftp->fsetstat($handle, $attrs)
-
is similar to setstat but its first argument has to be an open remote file handle instead of a file name.
- $sftp->opendir($path)
-
Sends a
SSH_FXP_OPENDIR
command to open the remote directory$path
, and returns an open handle on success. On failure returnsundef
. - $sftp->remove($path)
-
Sends a
SSH_FXP_REMOVE
command to remove the remote file$path
. Returns a true value on success and undef on failure. - $sftp->mkdir($path, $attrs)
-
Sends a
SSH_FXP_MKDIR
command to create a remote directory$path
whose attributes should be initialized to$attrs
, a Net::SFTP::Foreign::Attributes object. Returns a true value on success and undef on failure. - $sftp->rmdir($path)
-
Sends a
SSH_FXP_RMDIR
command to remove a remote directory$path
. Returns a true value on success and undef on failure. - $sftp->realpath($path)
-
Sends a
SSH_FXP_REALPATH
command to canonicalise$path
to an absolute path. This can be useful for turning paths containing'..'
into absolute paths.Returns the absolute path on success,
undef
on failure. - $sftp->rename($old, $new)
-
Sends a
SSH_FXP_RENAME
command to rename$old
to$new
. Returns a true value on success and undef on failure.
BUGS
This is development version, expect bugs!!!
SEE ALSO
Information about the constants used on this module is available from Net::SFTP::Foreign::Constants. Information about attribute objects is available from Net::SFTP::Foreign::Attributes.
General information about SSH and the OpenSSH implementation is available from the OpenSSH web site at http://www.openssh.org/ and from the sftp(1) and sftp-server(8) manual pages.
COPYRIGHT
Copyright (c) 2005, 2006 Salvador Fandiño.
Copyright (c) 2001 Benjamin Trott, Copyright (c) 2003 David Rolsky.
_glob_to_regex method based on code (C) 2002 Richard Clamp.
All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the LICENSE file included with this module.