1Net::SSH2(3)          User Contributed Perl Documentation         Net::SSH2(3)
2
3
4

NAME

6       Net::SSH2 - Support for the SSH 2 protocol via libssh2.
7

SYNOPSIS

9         use Net::SSH2;
10
11         my $ssh2 = Net::SSH2->new();
12
13         $ssh2->connect('example.com') or $ssh2->die_with_error;
14
15         $ssh->check_hostkey('ask') or $ssh2->die_with_error;
16
17         if ($ssh2->auth_keyboard('fizban')) {
18             my $chan = $ssh2->channel();
19             $chan->exec('program');
20
21             my $sftp = $ssh2->sftp();
22             my $fh = $sftp->open('/etc/passwd') or $sftp->die_with_error;
23             print $_ while <$fh>;
24         }
25

DESCRIPTION

27       Net::SSH2 is a Perl interface to the libssh2 (<http://www.libssh2.org>)
28       library.  It supports the SSH2 protocol (there is no support for SSH1)
29       with all of the key exchanges, ciphers, and compression of libssh2.
30
31       Even if the module can be compiled and linked against very old versions
32       of the library, nothing below 1.5.0 should really be used (older
33       versions were quite buggy and unreliable) and version 1.7.0 or later is
34       recommended.
35
36   Error handling
37       Unless otherwise indicated, methods return a true value on success and
38       "undef" on failure; use the "error" method to get extended error
39       information.
40
41       Important: methods in Net::SSH2 not backed by libssh2 functions (i.e.
42       "check_hostkey" or SCP related methods) require libssh2 1.7.0 or later
43       in order to set the error state. That means that after any of those
44       methods fails, "error" would not return the real code but just some
45       bogus result when an older version of the library is used.
46
47   Typical usage
48       The typical usage order is as follows:
49
50       1.  Create the SSH2 object calling "new".
51
52       2.  Configure the session if required. For instance, enabling
53           compression or picking some specific encryption methods.
54
55       3.  Establish the SSH connection calling the method "connect".
56
57       4.  Check the remote host public key calling "check_hostkey".
58
59       5.  Authenticate calling the required authentication methods.
60
61       6.  Call "channel" and related methods to create new bidirectional
62           communication channels over the SSH connection.
63
64       7.  Close the connection letting the Net::SSH2 object go out of scope
65           or calling "disconnect" explicitly.
66

CONSTANTS

68       All the constants defined in libssh2 can be imported from Net::SSH2.
69
70       For instance:
71
72          use Net::SSH2 qw(LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE
73                           LIBSSH2_CHANNEL_FLUSH_ALL
74                           LIBSSH2_HOSTKEY_POLICY_ASK);
75
76       Though note that most methods accept the uncommon part of the constant
77       name as a string. For instance the following two method calls are
78       equivalent:
79
80           $channel->ext_data(LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE);
81           $channel->ext_data('merge');
82
83       Tags can be used to import the following constant subsets:
84
85         callback channel error socket trace hash method
86         disconnect policy fx fxf sftp
87
88       The tag "all" can also be used to import all of them.
89

METHODS

91   new ( %options )
92       Create new Net::SSH2 object representing a SSH session.
93
94       The accepted options are as follows:
95
96       timeout
97           Sets the default timeout in milliseconds. See "timeout".
98
99       trace
100           Sets tracing. See "trace".
101
102           Example:
103
104               my $ssh2 = Net::SSH2->new(trace => -1);
105
106           Note that tracing requires a version of libssh2 compiled with
107           debugging support.
108
109       debug
110           Enable debugging. See "debug".
111
112       compress
113           Sets flag "LIBSSH2_FLAG_COMPRESS". See "flag".
114
115       sigpipe
116           Sets flag "LIBSSH2_FLAG_SIGPIPE". See "flag".
117
118   banner ( text )
119       Set the SSH2 banner text sent to the remote host (prepends required
120       "SSH-2.0-").
121
122   version
123       In scalar context, returns libssh2 version/patch e.g. 0.18 or
124       "0.18.0-20071110".  In list context, returns that version plus the
125       numeric version (major, minor, and patch, each encoded as 8 bits, e.g.
126       0x001200 for version 0.18) and the default banner text (e.g.
127       "SSH-2.0-libssh2_0.18.0-20071110").
128
129   error
130       Returns the last error code. In list context, returns (code, error
131       name, error string).
132
133       Note that the returned error value is only meaningful after some other
134       method indicates an error by returning false.
135
136   die_with_error ( [message] )
137       Calls "die" with the given message and the error information from the
138       object appended.
139
140       For instance:
141
142         $ssh2->connect("ajhkfhdklfjhklsjhd", 22)
143             or $ssh2->die_with_error;
144         # dies as:
145         #    Unable to connect to remote host: Invalid argument (-1 LIBSSH2_ERROR_SOCKET_NONE)
146
147   sock
148       Returns a reference to the underlying IO::Socket object (usually a
149       derived class as IO::Socket::IP or IO::Socket::INET), or "undef" if not
150       yet connected.
151
152   trace
153       Calls "libssh2_trace" with supplied bitmask. In order to enable all
154       tracing pass "-1" as follows:
155
156           $ssh2->trace(-1);
157
158       A version of libssh2 compiled with tracing support is required.
159
160   timeout ( timeout_ms )
161       Enables a global timeout (in milliseconds) which will affect every
162       action (requires libssh2 1.2.9 or later).
163
164       By default, or if you set the timeout to zero, Net::SSH2 has no
165       timeout.
166
167       Note that timeout errors may leave the SSH connection in an
168       inconsistent state and further operations may fail or behave
169       incorrectly. Actually, some methods are able to recover after a timeout
170       error and others are not.
171
172       Don't hesitate to report any issue you encounter related to this so
173       that it can be fixed or at least, documented!
174
175   method ( type [, values... ] )
176       Sets or gets a method preference. For get, pass in the type only; to
177       set, pass in either a list of values or a comma-separated string.
178       Values can only be queried after the session is connected.
179
180       The following methods can be set or queried:
181
182       LIBSSH2_METHOD_KEX
183           Key exchange method names. Supported values:
184
185           diffie-hellman-group1-sha1
186               Diffie-Hellman key exchange with SHA-1 as hash, and Oakley
187               Group 2 (see RFC 2409).
188
189           diffie-hellman-group14-sha1
190               Diffie-Hellman key exchange with SHA-1 as hash, and Oakley
191               Group 14 (see RFC 3526).
192
193           diffie-hellman-group-exchange-sha1
194               Diffie-Hellman key exchange with SHA-1 as hash, using a
195               safe-prime/generator pair (chosen by server) of arbitrary
196               strength (specified by client) (see IETF draft secsh-dh-group-
197               exchange).
198
199       LIBSSH2_METHOD_HOSTKEY
200           Public key algorithms. Supported values:
201
202           ssh-dss
203               Based on the Digital Signature Standard (FIPS-186-2).
204
205           ssh-rsa
206               Based on PKCS#1 (RFC 3447).
207
208       LIBSSH2_METHOD_CRYPT_CS
209           Encryption algorithm from client to server. Supported algorithms:
210
211           aes256-cbc
212               AES in CBC mode, with 256-bit key.
213
214           rijndael-cbc@lysator.liu.se
215               Alias for aes256-cbc.
216
217           aes192-cbc
218               AES in CBC mode, with 192-bit key.
219
220           aes128-cbc
221               AES in CBC mode, with 128-bit key.
222
223           blowfish-cbc
224               Blowfish in CBC mode.
225
226           arcfour
227               ARCFOUR stream cipher.
228
229           cast128-cbc
230               CAST-128 in CBC mode.
231
232           3des-cbc
233               Three-key 3DES in CBC mode.
234
235           none
236               No encryption.
237
238       LIBSSH2_METHOD_CRYPT_SC
239           Encryption algorithm from server to client. See the
240           "LIBSSH2_METHOD_CRYPT_CS" entry above for supported algorithms.
241
242       LIBSSH2_METHOD_MAC_CS
243           Message Authentication Code (MAC) algorithms from client to server.
244           Supported values:
245
246           hmac-sha1
247               SHA-1 with 20-byte digest and key length.
248
249           hmac-sha1-96
250               SHA-1 with 20-byte key length and 12-byte digest length.
251
252           hmac-md5
253               MD5 with 16-byte digest and key length.
254
255           hmac-md5-96
256               MD5 with 16-byte key length and 12-byte digest length.
257
258           hmac-ripemd160
259               RIPEMD-160 algorithm with 20-byte digest length.
260
261           hmac-ripemd160@openssh.com
262               Alias for hmac-ripemd160.
263
264           none
265               No encryption.
266
267       LIBSSH2_METHOD_MAC_SC
268           Message Authentication Code (MAC) algorithms from server to client.
269           See LIBSSH2_METHOD_MAC_CS for supported algorithms.
270
271       LIBSSH2_METHOD_COMP_CS
272           Compression methods from client to server. Supported values:
273
274           zlib
275               The "zlib" compression method as described in RFC 1950 and RFC
276               1951.
277
278           none
279               No compression
280
281       LIBSSH2_METHOD_COMP_SC
282           Compression methods from server to client. See
283           LIBSSH2_METHOD_COMP_CS for supported compression methods.
284
285   connect ( handle | host [, port])
286       The argument combinations accepted are as follows:
287
288       a glob or "IO::*" object reference
289           Note that tied file handles are not acceptable. The underlying
290           libssh2 requires real file handles.
291
292       host [, port]
293           In order to handle IPv6 addresses the optional module
294           IO::Socket::IP is required.
295
296           The port number defaults to 22.
297
298       This method used to accept a "Timeout" argument. That feature has been
299       replaced by the constructor "timeout" option but note that it takes
300       milliseconds instead of seconds!
301
302   disconnect ( [description [, reason [, language]]] )
303       Sends a clean disconnect message to the remote server. Default values
304       are empty strings for description and language, and
305       "SSH_DISCONNECT_BY_APPLICATION" for the reason.
306
307   hostname
308       The name of the remote host given at connect time or retrieved from the
309       TCP layer.
310
311   port
312       The port number of the remote SSH server.
313
314   hostkey_hash ( hash type )
315       Returns a hash of the host key; note that the key is raw data and may
316       contain nulls or control characters.
317
318       The type may be as follows:
319
320       LIBSSH2_HOSTKEY_HASH_MD5
321           MD5 hash, 16 bytes long (requires libssh2 compiled with MD5
322           support).
323
324       LIBSSH2_HOSTKEY_HASH_SHA1
325           SHA1 hash, 20 bytes long.
326
327       Note: in previous versions of the module this method was called
328       "hostkey".
329
330   remote_hostkey
331       Returns the public key from the remote host and its type which is one
332       of "LIBSSH2_HOSTKEY_TYPE_RSA", "LIBSSH2_HOSTKEY_TYPE_DSS", or
333       "LIBSSH2_HOSTKEY_TYPE_UNKNOWN".
334
335   check_hostkey( [policy, [known_hosts_path [, comment] ] ] )
336       Looks for the remote host key inside the given known host file
337       (defaults to "~/.ssh/known_hosts").
338
339       On success, this method returns the result of the call done under the
340       hood to "Net::SSH2::KnownHost::check" (i.e.
341       "LIBSSH2_KNOWNHOST_CHECK_MATCH", "LIBSSH2_KNOWNHOST_CHECK_FAILURE",
342       "LIBSSH2_KNOWNHOST_CHECK_NOTFOUND" or
343       "LIBSSH2_KNOWNHOST_CHECK_MISMATCH").
344
345       On failure it returns "undef".
346
347       The accepted policies are as follows:
348
349       LIBSSH2_HOSTKEY_POLICY_STRICT
350           Only host keys already present in the known hosts file are
351           accepted.
352
353           This is the default policy.
354
355       LIBSSH2_HOSTKEY_POLICY_ASK
356           If the host key is not present in the known hosts file, the user is
357           asked if it should be accepted or not.
358
359           If accepted, the key is added to the known host file with the given
360           comment.
361
362       LIBSSH2_HOSTKEY_POLICY_TOFU
363           Trust On First Use: if the host key is not present in the known
364           hosts file, it is added there and accepted.
365
366       LIBSSH2_HOSTKEY_POLICY_ADVISORY
367           The key is always accepted, but it is never saved into the known
368           host file.
369
370       callback
371           If a reference to a subroutine is given, it is called when the key
372           is not present in the known hosts file or a different key is found.
373           The arguments passed to the callback are the session object, the
374           matching error ("LIBSSH2_KNOWNHOST_CHECK_FAILURE",
375           "LIBSSH2_KNOWNHOST_CHECK_NOTFOUND" or
376           "LIBSSH2_KNOWNHOST_CHECK_MISMATCH") and the comment.
377
378   auth_list ( [username] )
379       Returns the authentication methods accepted by the server. In scalar
380       context the methods are returned as a comma separated string.
381
382       When the server accepted an unauthenticated session for the given
383       username, this method returns "undef" but "auth_ok" returns true.
384
385   auth_ok
386       Returns true when the session is authenticated.
387
388   auth_password ( username [, password [, callback ]] )
389       Authenticates using a password.
390
391       If the password has expired, if a callback code reference was given,
392       it's called as "callback($self, $username)" and should return a
393       password.  If no callback is provided, LIBSSH2_ERROR_PASSWORD_EXPIRED
394       is returned.
395
396   auth_password_interact ( username [, callback])
397       Prompts the user for the password interactively (requires
398       Term::ReadKey).
399
400   auth_publickey ( username, publickey_path, privatekey_path [, passphrase ]
401       )
402       Authenticate using the given private key and an optional passphrase.
403
404       When libssh2 is compiled using OpenSSL as the crypto backend, passing
405       this method "undef" as the public key argument is acceptable (OpenSSL
406       is able to extract the public key from the private one).
407
408       See also "Supported key formats".
409
410   auth_publickey_frommemory ( username, publickey_blob, privatekey_blob [,
411       passphrase ] )
412       Authenticate using the given public/private key and an optional
413       passphrase. The keys must be PEM encoded (requires libssh2 1.6.0 or
414       later with the OpenSSL backend).
415
416   auth_hostbased ( username, publickey, privatekey, hostname, [, local
417       username [, passphrase ]] )
418       Host-based authentication using an optional passphrase. The local
419       username defaults to be the same as the remote username.
420
421   auth_keyboard ( username, password | callback )
422       Authenticate using "keyboard-interactive". Takes either a password, or
423       a callback code reference which is invoked as "callback->(self,
424       username, name, instruction, prompt...)" (where each prompt is a hash
425       with "text" and "echo" keys, signifying the prompt text and whether the
426       user input should be echoed, respectively) which should return an array
427       of responses.
428
429       If only a username is provided, the default callback will handle
430       standard interactive responses (requires Term::ReadKey)
431
432   auth_agent ( username )
433       Try to authenticate using an SSH agent (requires libssh2 1.2.3).
434
435   auth ( ... )
436       This is a general, prioritizing authentication mechanism that can use
437       any of the previous methods. You provide it some parameters and
438       (optionally) a ranked list of methods you want considered (defaults to
439       all). It will remove any unsupported methods or methods for which it
440       doesn't have parameters (e.g. if you don't give it a public key, it
441       can't use publickey or hostkey), and try the rest, returning whichever
442       one succeeded or "undef" if they all failed. If a parameter is passed
443       with an "undef" value, a default value will be supplied if possible.
444
445       The parameters are:
446
447       rank
448           An optional ranked list of methods to try.  The names should be the
449           names of the Net::SSH2 "auth" methods, e.g. "keyboard" or
450           "publickey", with the addition of "keyboard-auto" for automated
451           "keyboard-interactive" and "password-interact" which prompts the
452           user for the password interactively.
453
454       username
455       password
456       publickey
457       privatekey
458           "privatekey" and "publickey" are file paths.
459
460       passphrase
461       hostname
462       local_username
463       interact
464           If this option is set to a true value, interactive methods will be
465           enabled.
466
467       fallback
468           If a password is given but authentication using it fails, the
469           module will fall back to ask the user for another password if this
470           parameter is set to a true value.
471
472       cb_keyboard
473           auth_keyboard callback.
474
475       cb_password
476           auth_password callback.
477
478       For historical reasons and in order to maintain backward compatibility
479       with older versions of the module, when the "password" argument is
480       given, it is also used as the passphrase (and a deprecation warning
481       generated).
482
483       In order to avoid that behaviour the "passphrase" argument must be also
484       passed (it could be "undef"). For instance:
485
486         $ssh2->auth(username => $user,
487                     privatekey => $privatekey_path,
488                     publickey => $publickey_path,
489                     password => $password,
490                     passphrase => undef);
491
492       This work around will be removed in a not too distant future version of
493       the module.
494
495   flag (key, value)
496       Sets the given session flag.
497
498       The currently supported flag values are:
499
500       LIBSSH2_FLAG_COMPRESS
501           If set before the connection negotiation is performed, compression
502           will be negotiated for this connection.
503
504           Compression can also be enabled passing option "compress" to the
505           constructor new.
506
507       LIBSSH2_FLAG_SIGPIPE
508           if set, Net::SSH2/libssh2 will not attempt to block SIGPIPEs but
509           will let them trigger from the underlying socket layer.
510
511   keepalive_config(want_reply, interval)
512       Set how often keepalive messages should be sent.
513
514       "want_reply" indicates whether the keepalive messages should request a
515       response from the server. "interval" is number of seconds that can pass
516       without any I/O.
517
518   keepalive_send
519       Send a keepalive message if needed.
520
521       On failure returns undef. On success returns how many seconds you can
522       sleep after this call before you need to call it again.
523
524       Note that the underlying libssh2 function "libssh2_keepalive_send" can
525       not recover from EAGAIN errors. If this method fails with such error,
526       the SSH connection may become corrupted.
527
528       The usage of this function is discouraged.
529
530   channel ( [type, [window size, [packet size]]] )
531       Creates and returns a new channel object. See Net::SSH2::Channel.
532
533       Type, if given, must be "session" (a reminiscence of an old, more
534       generic, but never working wrapping).
535
536   tcpip ( host, port [, shost, sport ] )
537       Creates a TCP connection from the remote host to the given host:port,
538       returning a new channel.
539
540       The "shost" and "sport" arguments are merely informative and passed to
541       the remote SSH server as the origin of the connection. They default to
542       127.0.0.1:22.
543
544       Note that this method does not open a new port on the local machine and
545       forwards incoming connections to the remote side.
546
547   listen ( port [, host [, bound port [, queue size ]]] )
548       Sets up a TCP listening port on the remote host.  Host defaults to
549       0.0.0.0; if bound port is provided, it should be a scalar reference in
550       which the bound port is returned. Queue size specifies the maximum
551       number of queued connections allowed before the server refuses new
552       connections.
553
554       Returns a new Net::SSH2::Listener object.
555
556   scp_get ( remote_path [, local_path ] )
557       Retrieve a file with SCP. Local path defaults to basename of remote.
558
559       Alternatively, "local_path" may be an already open file handle or an
560       IO::Handle object (e.g. IO::File, IO::Scalar).
561
562   scp_put ( local_path [, remote_path ] )
563       Send a file with SCP. Remote path defaults to same as local.
564
565       Alternatively, "local_path" may be an already open file handle or a
566       reference to a IO::Handle object (it must have a valid stat method).
567
568   sftp
569       Return SecureFTP interface object (see Net::SSH2::SFTP).
570
571       Note that SFTP support in libssh2 is pretty rudimentary. You should
572       consider using Net::SFTP::Foreign with the Net::SSH2 backend
573       Net::SFTP::Foreign::Backend::Net_SSH2 instead.
574
575   public_key
576       Return public key interface object (see Net::SSH2::PublicKey).
577
578   known_hosts
579       Returns known hosts interface object (see Net::SSH2::KnownHosts).
580
581   poll ( timeout, arrayref of hashes )
582       Deprecated: the poll functionality in libssh2 is deprecated and its
583       usage disregarded. Session methods "sock" and "block_directions" can be
584       used instead to integrate Net::SSH2 inside an external event loop.
585
586       Pass in a timeout in milliseconds and an arrayref of hashes with the
587       following keys:
588
589       handle
590           May be a Net::SSH2::Channel or Net::SSH2::Listener object, integer
591           file descriptor, or perl file handle.
592
593       events
594           Requested events.  Combination of LIBSSH2_POLLFD_* constants (with
595           the POLL prefix stripped if present), or an arrayref of the names
596           ('in', 'hup' etc.).
597
598       revents
599           Returned events.  Returns a hash with the (lowercased) names of the
600           received events ('in', 'hup', etc.) as keys with true values, and a
601           "value" key with the integer value.
602
603       Returns undef on error, or the number of active objects.
604
605   block_directions
606       Get the blocked direction after some method returns
607       "LIBSSH2_ERROR_EAGAIN".
608
609       Returns "LIBSSH2_SESSION_BLOCK_INBOUND" or/and
610       "LIBSSH2_SESSION_BLOCK_OUTBOUND".
611
612   debug ( state )
613       Class method (affects all Net::SSH2 objects).
614
615       Pass 1 to enable, 0 to disable. Debug output is sent to "STDERR".
616
617   blocking ( flag )
618       Enable or disable blocking.
619
620       A good number of the methods in "Net::SSH2"/"libssh2" can not work in
621       non-blocking mode. Some of them may just forcibly enable blocking
622       during its execution. A few may even corrupt the SSH session or crash
623       the program.
624
625       The ones that can be safely called are "read" and, with some caveats,
626       "write". See "write" in Net::SSH2::Channel.
627
628       Don't hesitate to report any bug you found in that area!
629

INTEROPERABILITY AND OTHER KNOWN ISSUES

631   Protocol versions
632       The underlaying "libssh2" library does support version 2 of the SSH
633       protocol exclusively (hopefully, version 1 usage is almost extinct).
634
635       The SFTP client implements version 3 of the SFTP protocol.
636
637   Key formats
638       Private and public keys can be generated and stored using different
639       formats and cyphers. Which ones are accepted by "Net::SSH2" depends on
640       the libssh2 version being used and of the underlying crypto backend
641       (OpenSSL "libssl" or "libgcrypt") it was configured to use at build
642       time.
643
644       An increassingly common problem is that OpenSSH since version 7.8
645       (released 2018-8-24) generates keys by default using the format RFC4716
646       which is not supported by "libssl", the default crypto backend.
647
648       Keys can be converted inplace to the old PEM format using ssh-keygen(1)
649       as follows:
650
651         $ ssh-keygen -p -m PEM -N "" -f ~/.ssh/id_rsa
652
653       On Windows, PuTTYgen (which is part of the PuTTY distribution) can be
654       used to convert keys.
655
656       Another common issue is that in the last years OpenSSH has incorporated
657       several new cyphers that are not supported by any version of "libssh2"
658       yet (though the incomming 1.8.1 may aliviate the situation). Currently
659       the best option from an interoperability standpoint is probably to
660       stick to RSA key usage.
661
662   Security
663       Nowadays "libssh2" development is not thrilling; new versions (even
664       minor ones) are being released just every two or three years. On the
665       other hand security issues are found and reported far more frequently.
666       That means that "Net::SSH2"/"libssh2" could be an easy attack vector.
667
668       So, Net::SSH2 must be used with care only in trusted environments.
669
670       More specifically, using it to connect to untrusted third party
671       computers over the Internet may be a very bad idea!
672

SEE ALSO

674       Net::SSH2::Channel, Net::SSH2::Listener, Net::SSH2::SFTP,
675       Net::SSH2::File, Net::SSH2::Dir.
676
677       LibSSH2 documentation at <http://www.libssh2.org>.
678
679       IETF Secure Shell (secsh) working group at
680       <http://www.ietf.org/html.charters/secsh-charter.html>.
681
682       Net::SSH::Any and Net::SFTP::Foreign integrate nicely with Net::SSH2.
683
684       Other Perl modules related to SSH you may find interesting:
685       Net::OpenSSH, Net::SSH::Perl, Net::OpenSSH::Parallel,
686       Net::OpenSSH::Compat.
687
689       Copyright (C) 2005 - 2010 by David B. Robins (dbrobins@cpan.org).
690
691       Copyright (C) 2010 - 2016 by Rafael Kitover (rkitover@cpan.org).
692
693       Copyright (C) 2011 - 2019 by Salvador FandiƱo (salva@cpan.org).
694
695       All rights reserved.
696
697       This library is free software; you can redistribute it and/or modify it
698       under the same terms as Perl itself, either Perl version 5.8.0 or, at
699       your option, any later version of Perl 5 you may have available.
700
701
702
703perl v5.28.1                      2019-03-17                      Net::SSH2(3)
Impressum