Net::SSH2(3)
π¦ Net::SSH2 π
okay so bestie, this is the Net::SSH2(3) page from the User Contributed Perl Documentation section β yes that whole vibe. it's a lot, i know. but we're gonna get through it together, no cap. π
β¨ NAME β¨
Net::SSH2 β support for the SSH 2 protocol via libssh2. that's the whole thing. that's the tweet. π«Ά
π SYNOPSIS π
like, here's the whole glow-up in one code block, literally exactly as written:
use Net::SSH2;
my $ssh2 = Net::SSH2->new();
$ssh2->connect('example.com')
or $ssh2->die_with_error;
$ssh2->check_hostkey('ask')
or $ssh2->die_with_error;
$ssh2->auth_publickey($ENV{USER}, "$ENV{HOME}/.ssh/id_rsa.pub", "$ENV{HOME}/.ssh/id_rsa")
or $ssh2->die_with_error;
my $chan = $ssh2->channel()
or $ssh2->die_with_error;
$chan->exec('ls')
or $ssh2->die_with_error;
print while <$chan>;
print "EXIT CODE: ", $chan->exit_status, "\n";
$chan->close;
my $sftp = $ssh2->sftp()
or $ssh2->die_with_error;;
my $fh = $sftp->open('/etc/passwd')
or $sftp->die_with_error;
print while <$fh>;
(yes there's a lil double ;; in there, that's canon, we don't touch it π
)
πΈ DESCRIPTION πΈ
Net::SSH2 is a Perl interface to the libssh2 library (<http://www.libssh2.org>). it does the SSH2 protocol β and bestie, listen, there is no support for SSH1, okay? SSH1 is not invited to the party. but it DOES bring all of the key exchanges, ciphers, and compression of libssh2. ate. π
so even though this module can be compiled and linked against really really old versions of the libraryβ¦ nothing below 1.5.0 should actually be used (those older versions were buggy and unreliable, like genuinely a mess π) and version 1.7.0 or later is recommended.
π Error handling π
unless it says otherwise, methods return a true value on success and undef on failure. when that happens, hit up the error method to get the extended error info. iykyk.
Important: methods inNet::SSH2that are not backed bylibssh2functions (i.e.check_hostkeyor the SCP related methods) needlibssh21.7.0or later in order to set the error state. that means when one of those methods fails on an older version of the library,errorwon't return the real code β it'll just hand you some bogus result. π so watch out for that.
π¦ Typical usage π¦
the typical order of operations goes like this:
- create the SSH2 object by calling
new. - configure the session if you need to. like, enabling compression or picking some specific encryption methods.
- establish the SSH connection by calling the method
connect. - check the remote host public key by calling
check_hostkey. - authenticate by calling the required authentication methods.
- call
channeland related methods to create new bidirectional communication channels over the SSH connection. - close the connection by letting the
Net::SSH2object go out of scope, or by callingdisconnectexplicitly.
π CONSTANTS π
every single constant defined in libssh2 can be imported from Net::SSH2. periodt.
for instance:
use Net::SSH2 qw(LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE
LIBSSH2_CHANNEL_FLUSH_ALL
LIBSSH2_HOSTKEY_POLICY_ASK);
though ngl, most methods accept the uncommon part of the constant name as a string. so like, these two method calls are equivalent:
$channel->ext_data(LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE);
$channel->ext_data('merge');
you can use tags to import these constant subsets:
callback channel error socket trace hash method
disconnect policy fx fxf sftp
and the tag all imports literally all of them. slay. π
π METHODS π
β new ( %options ) β
creates a brand new Net::SSH2 object that represents an SSH session. main character energy fr.
the accepted options are:
timeoutβ sets the default timeout in milliseconds. seetimeout.traceβ sets tracing. seetrace.
example:
my $ssh2 = Net::SSH2->new(trace => -1);
note that tracing requires a version of libssh2 compiled with debugging support.
debugβ enable debugging. seedebug.compressβ sets flagLIBSSH2_FLAG_COMPRESS. seeflag.sigpipeβ sets flagLIBSSH2_FLAG_SIGPIPE. seeflag.
β banner ( text ) β
sets the SSH2 banner text that gets sent to the remote host. it prepends the required SSH-2.0- for you, don't worry. π
β version β
in scalar context, returns the libssh2 version/patch, e.g. 0.18 or 0.18.0-20071110. in list context, it 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). β¨
β error β
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. like, it's not just sitting there waiting for you bestie. π
β die_with_error ( [message] ) β
calls die with the given message and the error information from the object appended to it.
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)
β sock β
returns a reference to the underlying IO::Socket object (usually a derived class like IO::Socket::IP or IO::Socket::INET), or undef if it's not connected yet.
β trace β
calls libssh2_trace with the supplied bitmask. to enable all tracing, pass -1 like this:
$ssh2->trace(-1);
a version of libssh2 compiled with tracing support is required. no tracing support, no trace. that's the rule. π
β timeout ( timeout_ms ) β
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. free spirit. π¦
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 it can be fixed, or at least documented! π«Ά
β method ( type [, values... ] ) β
sets or gets a method preference. for a 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_KEXβ key exchange method names. supported values:diffie-hellman-group1-sha1β Diffie-Hellman key exchange with SHA-1 as hash, and Oakley Group 2 (see RFC 2409).diffie-hellman-group14-sha1β Diffie-Hellman key exchange with SHA-1 as hash, and Oakley Group 14 (see RFC 3526).diffie-hellman-group-exchange-sha1β Diffie-Hellman key exchange with SHA-1 as hash, using a safe-prime/generator pair (chosen by server) of arbitrary strength (specified by client) (see IETF draft secsh-dh-group-exchange).
LIBSSH2_METHOD_HOSTKEYβ public key algorithms. supported values:ssh-dssβ based on the Digital Signature Standard (FIPS-186-2).ssh-rsaβ based on PKCS#1 (RFC 3447).
LIBSSH2_METHOD_CRYPT_CSβ encryption algorithm from client to server. supported algorithms:aes256-cbcβ AES in CBC mode, with 256-bit key.rijndael-cbc@lysator.liu.seβ alias foraes256-cbc.aes192-cbcβ AES in CBC mode, with 192-bit key.aes128-cbcβ AES in CBC mode, with 128-bit key.blowfish-cbcβ Blowfish in CBC mode.arcfourβ ARCFOUR stream cipher.cast128-cbcβ CAST-128 in CBC mode.3des-cbcβ three-key 3DES in CBC mode.noneβ no encryption.
LIBSSH2_METHOD_CRYPT_SCβ encryption algorithm from server to client. see theLIBSSH2_METHOD_CRYPT_CSentry above for the supported algorithms.LIBSSH2_METHOD_MAC_CSβ Message Authentication Code (MAC) algorithms from client to server. supported values:hmac-sha1β SHA-1 with 20-byte digest and key length.hmac-sha1-96β SHA-1 with 20-byte key length and 12-byte digest length.hmac-md5β MD5 with 16-byte digest and key length.hmac-md5-96β MD5 with 16-byte key length and 12-byte digest length.hmac-ripemd160β RIPEMD-160 algorithm with 20-byte digest length.hmac-ripemd160@openssh.comβ alias forhmac-ripemd160.noneβ no encryption.
LIBSSH2_METHOD_MAC_SCβ Message Authentication Code (MAC) algorithms from server to client. seeLIBSSH2_METHOD_MAC_CSfor the supported algorithms.LIBSSH2_METHOD_COMP_CSβ compression methods from client to server. supported values:LIBSSH2_METHOD_COMP_SCβ compression methods from server to client. seeLIBSSH2_METHOD_COMP_CSfor the supported compression methods.
β connect ( handle | host [, port] ) β
the argument combinations it accepts are:
- a glob or
IO::*object reference β note that tied file handles are not acceptable. the underlyinglibssh2requires real file handles, bestie. π - host [, port] β in order to handle IPv6 addresses, the optional module
IO::Socket::IPis required. the port number defaults to22.
this method used to accept a Timeout argument. that feature has been replaced by the constructor timeout option β but heads up, it takes milliseconds instead of seconds! so don't get caught slipping. π
β disconnect ( [description [, reason [, language]]] ) β
sends a clean disconnect message to the remote server. the default values are empty strings for description and language, and SSH_DISCONNECT_BY_APPLICATION for the reason. polite exit, we love to see it. π
β hostname β
the name of the remote host given at connect time, or retrieved from the TCP layer.
β port β
the port number of the remote SSH server.
β hostkey_hash ( hash type ) β
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 one of:
LIBSSH2_HOSTKEY_HASH_MD5β MD5 hash, 16 bytes long (requireslibssh2compiled with MD5 support).LIBSSH2_HOSTKEY_HASH_SHA1β SHA1 hash, 20 bytes long.
Note: in previous versions of the module this method was called hostkey.
β remote_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.
β check_hostkey( [policy, [known_hosts_path [, comment] ] ] ) β
looks for the remote host key inside the given known host file. it 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:
Okay so the hostkey policy vibes are giving security check realness π :
LIBSSH2_HOSTKEY_POLICY_STRICTβ Only host keys already present in the known hosts file are accepted. This is the default policy. No cap.LIBSSH2_HOSTKEY_POLICY_ASKβ If the host key is not present in the known hosts file, the user is asked if it should be accepted or not. If accepted, the key is added to the known host file with the given comment. Communication is key, bestie π«ΆLIBSSH2_HOSTKEY_POLICY_TOFUβ Trust On First Use: if the host key is not present in the known hosts file, it is added there and accepted. First impressions are forever β¨LIBSSH2_HOSTKEY_POLICY_ADVISORYβ The key is always accepted, but it is never saved into the known host file. Look but don't touch energy πcallbackβ If a reference to a subroutine is given, it is called when the key is not present in the known hosts file or a different key is found. The arguments passed to the callback are the session object, the matching error ("LIBSSH2_KNOWNHOST_CHECK_FAILURE","LIBSSH2_KNOWNHOST_CHECK_NOTFOUND"or"LIBSSH2_KNOWNHOST_CHECK_MISMATCH") and the comment. It's giving "you've got mail" but for crypto π₯
auth_list ( [username] )
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. So like, it's a vibe, not a rejection π
auth_ok
Returns true when the session is authenticated. Periodt. That's it. That's the method. π
auth_password ( username [, password [, callback ]] )
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. Expired password? Not the vibe. Get a callback, bestie π
auth_password_interact ( username [, callback])
Prompts the user for the password interactively (requires Term::ReadKey). Interactive era π
auth_publickey ( username, publickey_path, privatekey_path [, passphrase ] )
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). OpenSSL said "I got you" π
See also "Supported key formats".
auth_publickey_frommemory ( username, publickey_blob, privatekey_blob [, passphrase ] )
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). Memory keys? In this economy? Slay β¨
auth_hostbased ( username, publickey, privatekey, hostname, [, local username [, passphrase ]] )
Host-based authentication using an optional passphrase. The local username defaults to be the same as the remote username. Lowkey convenient π¦
auth_keyboard ( username, password | callback )
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 Term::ReadKey) Keyboard go brrr β¨οΈ
auth_agent ( username )
Try to authenticate using an SSH agent (requires libssh2 1.2.3). Let the agent handle it πββοΈ
auth ( ... )
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. Main character energy: it tries everything until something works π
The parameters are:
rankβ An optional ranked list of methods to try. The names should be the names of the Net::SSH2 "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.usernamepasswordpublickeyprivatekeyβ"privatekey"and"publickey"are file paths.passphrasehostnamelocal_usernameinteractβ If this option is set to a true value, interactive methods will be enabled.fallbackβ If a password is given but authentication using it fails, the module will fall back to ask the user for another password if this parameter is set to a true value.cb_keyboardβ auth_keyboard callback.cb_passwordβ auth_password callback.
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). Not the deprecated behavior, bestie π
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. So use it while you can, fr fr π«Ά
flag (key, value)
Sets the given session flag.
The currently supported flag values are:
LIBSSH2_FLAG_COMPRESSβ If set before the connection negotiation is performed, compression will be negotiated for this connection. Compression can also be enabled passing option"compress"to the constructor new. Squeeze it in β¨LIBSSH2_FLAG_SIGPIPEβ if set, Net::SSH2/libssh2 will not attempt to block SIGPIPEs but will let them trigger from the underlying socket layer. Let it trigger, honestly π
keepalive_config(want_reply, interval)
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. Just checking in, bestie π«Ά
keepalive_send
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. β οΈ This is giving "do not pass go" energy β οΈ
The usage of this function is discouraged. Not me telling you to avoid it or anything π
channel ( [type, [window size, [packet size]]] )
Creates and returns a new channel object. See Net::SSH2::Channel.
Type, if given, must be "session" (a reminiscence of an old, more generic, but never working wrapping). We don't talk about the old wrapping π
tcpip ( host, port [, shost, sport ] )
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. Informative only, bestie. Don't @ me π
Note that this method does not open a new port on the local machine and forwards incoming connections to the remote side. Read that again. No local port. No cap. π«
listen ( port [, host [, bound port [, queue size ]]] )
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. Listener era activated π§
scp_get ( remote_path [, local_path ] )
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). File handle? Say less. π
scp_put ( local_path [, remote_path ] )
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). Stat method required, bestie. No stat, no chat. π
sftp
Return SecureFTP interface object (see Net::SSH2::SFTP).
Note that SFTP support in libssh2 is pretty rudimentary. You should consider using Net::SFTP::Foreign with the Net::SSH2 backend Net::SFTP::Foreign::Backend::Net_SSH2 instead. Rudimentary? That's a read. π
public_key
Return public key interface object (see Net::SSH2::PublicKey). Public key, public vibe β¨
known_hosts
Returns known hosts interface object (see Net::SSH2::KnownHosts). You already know, bestie π
poll ( timeout, arrayref of hashes )
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. Deprecated. Don't use it. I said what I said. π«
Pass in a timeout in milliseconds and an arrayref of hashes with the following keys:
handleβ May be a Net::SSH2::Channel or Net::SSH2::Listener object, integer file descriptor, or perl file handle.eventsβ Requested events. Combination ofLIBSSH2_POLLFD_*constants (with the POLL prefix stripped if present), or an arrayref of the names ('in', 'hup' etc.).reventsβ Returned events. Returns a hash with the (lowercased) names of the received events ('in', 'hup', etc.) as keys with true values, and a"value"key with the integer value.
Returns undef on error, or the number of active objects. If it works, it works. But also, deprecated. π
block_directions
Get the blocked direction after some method returns "LIBSSH2_ERROR_EAGAIN".
Returns "LIBSSH2_SESSION_BLOCK_INBOUND" or/and "LIBSSH2_SESSION_BLOCK_OUTBOUND". Inbound, outbound, or both? The duality of SSH π
debug ( state )
Class method (affects all Net::SSH2 objects).
Pass 1 to enable, 0 to disable. Debug output is sent to "STDERR". Turn it on and watch the tea spill π΅
blocking ( flag )
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. β οΈ Crash the program? Not the vibe. Be careful, bestie. β οΈ
The ones that can be safely called are "read" and, with some caveats, "write". See "write" in Net::SSH2::Channel. Read: safe. Write: kinda safe. Everything else: enter at your own risk. π¦
Don't hesitate to report any bug you found in that area! If you find a bug, tell someone. You're the main character of that bug report. π
π¦ INTEROPERABILITY AND OTHER KNOWN ISSUES π¦
okay bestie, this is the part where we spill the tea on compatibility and the lil' gremlins you might meet. no cap.
π Protocol versions
The underlying libssh2 library does support version 2 of the SSH protocol exclusively (hopefully, version 1 usage is almost extinct.)
The SFTP client implements version 3 of the SFTP protocol.
π Key formats
Private and public keys can be generated and stored using different formats and cyphers. Which ones are accepted by Net::SSH2 depends on the libssh2 version being used and of the underlying crypto backend it was configured to use at build time (OpenSSL libssl or libgcrypt).
An increasingly common problem is that OpenSSH since version 7.8 (released 2018-8-24) generates keys by default using the format RFC4716 which is not supported by the default crypto backend (libssl).
Keys can be converted inplace to the old PEM format using ssh-keygen(1) as follows:
$ ssh-keygen -p -m PEM -N "" -f ~/.ssh/id_rsa
On Windows, PuTTYgen (which is part of the PuTTY distribution) can be used to convert keys.
Another common issue is that in the last years OpenSSH has incorporated several new cyphers that are not supported by any version of libssh2 yet. Currently the best option from an interoperability standpoint is probably to stick to RSA key usage.
π¨ Security
Nowadays libssh2 development is not thrilling; new versions (even minor ones) are being released just every two or three years. On the other hand security issues are found and reported far more frequently. That means that Net::SSH2/libssh2 could be an easy attack vector.
So, Net::SSH2 should be used only in trusted environments. More specifically, using it to connect to untrusted third party computers over the Internet is probably a very bad idea!
bestie, fr fr, do NOT use this to connect to random sketchy hosts on the internet. that's not a vibe, that's a vulnerability. π
π SEE ALSO π
Net::SSH2::ChannelNet::SSH2::ListenerNet::SSH2::SFTPNet::SSH2::FileNet::SSH2::Dir
LibSSH2 documentation at http://www.libssh2.org.
IETF Secure Shell (secsh) working group at http://www.ietf.org/html.charters/secsh-charter.html.
Net::SSH::Any and Net::SFTP::Foreign integrate nicely with Net::SSH2.
Other Perl modules related to SSH you may find interesting: Net::OpenSSH, Net::SSH::Perl, Net::OpenSSH::Parallel, Net::OpenSSH::Compat.
π COPYRIGHT AND LICENSE π
Copyright (C) 2005 - 2010 by David B. Robins (dbrobins@cpan.org).
Copyright (C) 2010 - 2020 by Rafael Kitover (rkitover@cpan.org).
Copyright (C) 2011 - 2020 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.
okay that's the whole page, bestie. it came from perl v5.42.0, dated 2025-07-25, and it's Net::SSH2(3). slay, you made it to the end. πβ¨
π¦ where this page comes from
- fedora 43: perl-Net-SSH2 0.74-4.fc43 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms