Net::SSH2 - Support for the SSH 2 protocol via libssh2. |
Net::SSH2 - Support for the SSH 2 protocol via libssh2.
use Net::SSH2;
my $ssh2 = Net::SSH2->new();
$ssh2->connect('example.com') or $ssh2->die_with_error;
$ssh->check_hostkey('ask') or $ssh2->die_with_error;
if ($ssh2->auth_keyboard('fizban')) { my $chan = $ssh2->channel(); $chan->exec('program');
my $sftp = $ssh2->sftp(); my $fh = $sftp->open('/etc/passwd') or $sftp->die_with_error; print $_ while <$fh>; }
Net::SSH2 is a Perl interface to the libssh2 (http://www.libssh2.org) library. It supports the SSH2 protocol (there is no support for SSH1) with all of the key exchanges, ciphers, and compression of libssh2.
Even if the module can be compiled and linked against very old versions of the library, nothing below 1.5.0 should really be used (older versions were quite buggy and unreliable) and version 1.7.0 or later is recommended.
Unless otherwise indicated, methods return a true value on success and
undef
on failure; use the error method to get extended error
information.
Important: methods in Net::SSH2 not backed by libssh2 functions (i.e. check_hostkey or SCP related methods) require libssh2 1.7.0 or later in order to set the error state. That means that after any of those methods fails, error would not return the real code but just some bogus result when an older version of the library is used.
The typical usage order is as follows:
All the constants defined in libssh2 can be imported from Net::SSH2.
For instance:
use Net::SSH2 qw(LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE LIBSSH2_CHANNEL_FLUSH_ALL LIBSSH2_HOSTKEY_POLICY_ASK);
Though note that most methods accept the uncommon part of the constant name as a string. For instance the following two method calls are equivalent:
$channel->ext_data(LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE); $channel->ext_data('merge');
Tags can be used to import the following constant subsets:
callback channel error socket trace hash method disconnect policy fx fxf sftp
The tag all
can also be used to import all of them.
Create new Net::SSH2 object representing a SSH session.
The accepted options are as follows:
Example:
my $ssh2 = Net::SSH2->new(trace => -1);
Note that tracing requires a version of libssh2 compiled with debugging support.
LIBSSH2_FLAG_COMPRESS
. See flag.
LIBSSH2_FLAG_SIGPIPE
. See flag.
Set the SSH2 banner text sent to the remote host (prepends required ``SSH-2.0-'').
In scalar context, returns libssh2 version/patch e.g. 0.18 or ``0.18.0-20071110''. In list context, returns that version plus the numeric version (major, minor, and patch, each encoded as 8 bits, e.g. 0x001200 for version 0.18) and the default banner text (e.g. ``SSH-2.0-libssh2_0.18.0-20071110'').
Returns the last error code. In list context, returns (code, error name, error string).
Note that the returned error value is only meaningful after some other method indicates an error by returning false.
Calls die
with the given message and the error information from the
object appended.
For instance:
$ssh2->connect("ajhkfhdklfjhklsjhd", 22) or $ssh2->die_with_error; # dies as: # Unable to connect to remote host: Invalid argument (-1 LIBSSH2_ERROR_SOCKET_NONE)
Returns a reference to the underlying the IO::Socket manpage object (usually a
derived class as the IO::Socket::IP manpage or the IO::Socket::INET manpage), or
undef
if not yet connected.
Calls libssh2_trace
with supplied bitmask. In order to enable all
tracing pass -1
as follows:
$ssh2->trace(-1);
A version of libssh2 compiled with tracing support is required.
Enables a global timeout (in milliseconds) which will affect every action (requires libssh2 1.2.9 or later).
By default, or if you set the timeout to zero, Net::SSH2 has no timeout.
Note that timeout errors may leave the SSH connection in an inconsistent state and further operations may fail or behave incorrectly. Actually, some methods are able to recover after a timeout error and others are not.
Don't hesitate to report any issue you encounter related to this so that it can be fixed or at least, documented!
Sets or gets a method preference. For get, pass in the type only; to set, pass in either a list of values or a comma-separated string. Values can only be queried after the session is connected.
The following methods can be set or queried:
LIBSSH2_METHOD_CRYPT_CS
entry above for supported algorithms.
The argument combinations accepted are as follows:
IO::*
object referenceThe port number defaults to 22.
This method used to accept a Timeout
argument. That feature has
been replaced by the constructor timeout
option but note that it
takes milliseconds instead of seconds!
Sends a clean disconnect message to the remote server. Default values are empty
strings for description and language, and SSH_DISCONNECT_BY_APPLICATION
for
the reason.
The name of the remote host given at connect time or retrieved from the TCP layer.
The port number of the remote SSH server.
Returns a hash of the host key; note that the key is raw data and may contain nulls or control characters.
The type may be as follows:
Note: in previous versions of the module this method was called
hostkey
.
Returns the public key from the remote host and its type which is one of
LIBSSH2_HOSTKEY_TYPE_RSA
, LIBSSH2_HOSTKEY_TYPE_DSS
, or
LIBSSH2_HOSTKEY_TYPE_UNKNOWN
.
Looks for the remote host key inside the given known host file
(defaults to ~/.ssh/known_hosts
).
On success, this method returns the result of the call done under the
hood to Net::SSH2::KnownHost::check
(i.e. LIBSSH2_KNOWNHOST_CHECK_MATCH
,
LIBSSH2_KNOWNHOST_CHECK_FAILURE
,
LIBSSH2_KNOWNHOST_CHECK_NOTFOUND
or
LIBSSH2_KNOWNHOST_CHECK_MISMATCH
).
On failure it returns undef
.
The accepted policies are as follows:
This is the default policy.
If accepted, the key is added to the known host file with the given comment.
LIBSSH2_KNOWNHOST_CHECK_FAILURE
,
LIBSSH2_KNOWNHOST_CHECK_NOTFOUND
or
LIBSSH2_KNOWNHOST_CHECK_MISMATCH
) and the comment.
Returns the authentication methods accepted by the server. In scalar context the methods are returned as a comma separated string.
When the server accepted an unauthenticated session for the given
username, this method returns undef
but auth_ok returns true.
Returns true when the session is authenticated.
Authenticates using a password.
If the password has expired, if a callback code reference was given, it's
called as callback($self, $username)
and should return a password. If
no callback is provided, LIBSSH2_ERROR_PASSWORD_EXPIRED is returned.
Prompts the user for the password interactively (requires the Term::ReadKey manpage).
Authenticate using the given private key and an optional passphrase.
When libssh2 is compiled using OpenSSL as the crypto backend, passing
this method undef
as the public key argument is acceptable (OpenSSL
is able to extract the public key from the private one).
Authenticate using the given public/private key and an optional passphrase. The keys must be PEM encoded (requires libssh2 1.6.0 or later with the OpenSSL backend).
Host-based authentication using an optional passphrase. The local username defaults to be the same as the remote username.
Authenticate using keyboard-interactive
. Takes either a password,
or a callback code reference which is invoked as
callback->(self, username, name, instruction, prompt...)
(where
each prompt is a hash with text
and echo
keys, signifying the
prompt text and whether the user input should be echoed, respectively)
which should return an array of responses.
If only a username is provided, the default callback will handle standard interactive responses (requires the Term::ReadKey manpage)
Try to authenticate using an SSH agent (requires libssh2 1.2.3).
This is a general, prioritizing authentication mechanism that can use
any of the previous methods. You provide it some parameters and
(optionally) a ranked list of methods you want considered (defaults to
all). It will remove any unsupported methods or methods for which it
doesn't have parameters (e.g. if you don't give it a public key, it
can't use publickey or hostkey), and try the rest, returning whichever
one succeeded or undef
if they all failed. If a parameter is passed
with an undef
value, a default value will be supplied if possible.
The parameters are:
auth
methods, e.g. keyboard
or
publickey
, with the addition of keyboard-auto
for automated
keyboard-interactive
and password-interact
which prompts the
user for the password interactively.
privatekey
and publickey
are file paths.
For historical reasons and in order to maintain backward compatibility
with older versions of the module, when the password
argument is
given, it is also used as the passphrase (and a deprecation warning
generated).
In order to avoid that behaviour the passphrase
argument must be
also passed (it could be undef
). For instance:
$ssh2->auth(username => $user, privatekey => $privatekey_path, publickey => $publickey_path, password => $password, passphrase => undef);
This work around will be removed in a not too distant future version of the module.
Sets the given session flag.
The currently supported flag values are:
Compression can also be enabled passing option compress
to the
constructor new.
Set how often keepalive messages should be sent.
want_reply
indicates whether the keepalive messages should request
a response from the server. interval
is number of seconds that can
pass without any I/O.
Send a keepalive message if needed.
On failure returns undef. On success returns how many seconds you can sleep after this call before you need to call it again.
Note that the underlying libssh2 function libssh2_keepalive_send
can not recover from EAGAIN errors. If this method fails with such
error, the SSH connection may become corrupted.
The usage of this function is discouraged.
Creates and returns a new channel object. See the Net::SSH2::Channel manpage.
Type, if given, must be session
(a reminiscence of an old, more
generic, but never working wrapping).
Creates a TCP connection from the remote host to the given host:port, returning a new channel.
The shost
and sport
arguments are merely informative and passed
to the remote SSH server as the origin of the connection. They default
to 127.0.0.1:22.
Note that this method does not open a new port on the local machine and forwards incoming connections to the remote side.
Sets up a TCP listening port on the remote host. Host defaults to 0.0.0.0; if bound port is provided, it should be a scalar reference in which the bound port is returned. Queue size specifies the maximum number of queued connections allowed before the server refuses new connections.
Returns a new Net::SSH2::Listener object.
Retrieve a file with SCP. Local path defaults to basename of remote.
Alternatively, local_path
may be an already open file handle or an
IO::Handle object (e.g. IO::File, IO::Scalar).
Send a file with SCP. Remote path defaults to same as local.
Alternatively, local_path
may be an already open file handle or a
reference to a IO::Handle object (it must have a valid stat method).
Return SecureFTP interface object (see the Net::SSH2::SFTP manpage).
Note that SFTP support in libssh2 is pretty rudimentary. You should consider using the Net::SFTP::Foreign manpage with the the Net::SSH2 manpage backend the Net::SFTP::Foreign::Backend::Net_SSH2 manpage instead.
Return public key interface object (see the Net::SSH2::PublicKey manpage).
Returns known hosts interface object (see the Net::SSH2::KnownHosts manpage).
Deprecated: the poll functionality in libssh2 is deprecated and its usage disregarded. Session methods sock and block_directions can be used instead to integrate Net::SSH2 inside an external event loop.
Pass in a timeout in milliseconds and an arrayref of hashes with the following keys:
value
key with
the integer value.
Returns undef on error, or the number of active objects.
Get the blocked direction after some method returns
LIBSSH2_ERROR_EAGAIN
.
Returns LIBSSH2_SESSION_BLOCK_INBOUND
or/and
LIBSSH2_SESSION_BLOCK_OUTBOUND
.
Class method (affects all Net::SSH2 objects).
Pass 1 to enable, 0 to disable. Debug output is sent to STDERR
.
Enable or disable blocking.
A good number of the methods in Net::SSH2/libssh2 can not work in non-blocking mode. Some of them may just forcibly enable blocking during its execution. A few may even corrupt the SSH session or crash the program.
The ones that can be safely called are read
and, with some
caveats, write
. See write in the Net::SSH2::Channel manpage.
Don't hesitate to report any bug you found in that area!
the Net::SSH2::Channel manpage, the Net::SSH2::Listener manpage, the Net::SSH2::SFTP manpage, the Net::SSH2::File manpage, the Net::SSH2::Dir manpage.
LibSSH2 documentation at http://www.libssh2.org.
IETF Secure Shell (secsh) working group at http://www.ietf.org/html.charters/secsh-charter.html.
the Net::SSH::Any manpage and the Net::SFTP::Foreign manpage integrate nicely with Net::SSH2.
Other Perl modules related to SSH you may find interesting: the Net::OpenSSH manpage, the Net::SSH::Perl manpage, the Net::OpenSSH::Parallel manpage, the Net::OpenSSH::Compat manpage.
Copyright (C) 2005 - 2010 by David B. Robins (dbrobins@cpan.org)
Copyright (C) 2010 - 2016 by Rafael Kitover (rkitover@cpan.org)
Copyright (C) 2011 - 2016 by Salvador Fandiño (salva@cpan.org)
All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.0 or, at your option, any later version of Perl 5 you may have available.
Net::SSH2 - Support for the SSH 2 protocol via libssh2. |