1Net::SSH2(3) User Contributed Perl Documentation Net::SSH2(3)
2
3
4
6 Net::SSH2 - Support for the SSH 2 protocol via libssh2.
7
9 use Net::SSH2;
10
11 my $ssh2 = Net::SSH2->new();
12
13 $ssh2->connect('example.com')
14 or $ssh2->die_with_error;
15
16 $ssh->check_hostkey('ask')
17 or $ssh2->die_with_error;
18
19 $ssh->auth_publickey($ENV{USER}, "$ENV{HOME}/.ssh/id_rsa.pub", "$ENV{HOME}/.ssh/id_rsa")
20 or $ssh->die_with_error;
21
22 my $chan = $ssh2->channel()
23 or $ssh2->die_with_error;
24
25 $chan->exec('ls')
26 or $ssh2->die_with_error;
27
28 print while <$chan>;
29
30 print "EXIT CODE: ", $chan->exit_status, "\n";
31
32 $chan->close;
33
34 my $sftp = $ssh2->sftp()
35 or $ssh2->die_with_error;;
36
37 my $fh = $sftp->open('/etc/passwd')
38 or $sftp->die_with_error;
39
40 print while <$fh>;
41
43 Net::SSH2 is a Perl interface to the libssh2 (<http://www.libssh2.org>)
44 library. It supports the SSH2 protocol (there is no support for SSH1)
45 with all of the key exchanges, ciphers, and compression of libssh2.
46
47 Even if the module can be compiled and linked against very old versions
48 of the library, nothing below 1.5.0 should really be used (older
49 versions were quite buggy and unreliable) and version 1.7.0 or later is
50 recommended.
51
52 Error handling
53 Unless otherwise indicated, methods return a true value on success and
54 "undef" on failure; use the "error" method to get extended error
55 information.
56
57 Important: methods in Net::SSH2 not backed by libssh2 functions (i.e.
58 "check_hostkey" or SCP related methods) require libssh2 1.7.0 or later
59 in order to set the error state. That means that after any of those
60 methods fails, "error" would not return the real code but just some
61 bogus result when an older version of the library is used.
62
63 Typical usage
64 The typical usage order is as follows:
65
66 1. Create the SSH2 object calling "new".
67
68 2. Configure the session if required. For instance, enabling
69 compression or picking some specific encryption methods.
70
71 3. Establish the SSH connection calling the method "connect".
72
73 4. Check the remote host public key calling "check_hostkey".
74
75 5. Authenticate calling the required authentication methods.
76
77 6. Call "channel" and related methods to create new bidirectional
78 communication channels over the SSH connection.
79
80 7. Close the connection letting the Net::SSH2 object go out of scope
81 or calling "disconnect" explicitly.
82
84 All the constants defined in libssh2 can be imported from Net::SSH2.
85
86 For instance:
87
88 use Net::SSH2 qw(LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE
89 LIBSSH2_CHANNEL_FLUSH_ALL
90 LIBSSH2_HOSTKEY_POLICY_ASK);
91
92 Though note that most methods accept the uncommon part of the constant
93 name as a string. For instance the following two method calls are
94 equivalent:
95
96 $channel->ext_data(LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE);
97 $channel->ext_data('merge');
98
99 Tags can be used to import the following constant subsets:
100
101 callback channel error socket trace hash method
102 disconnect policy fx fxf sftp
103
104 The tag "all" can also be used to import all of them.
105
107 new ( %options )
108 Create new Net::SSH2 object representing a SSH session.
109
110 The accepted options are as follows:
111
112 timeout
113 Sets the default timeout in milliseconds. See "timeout".
114
115 trace
116 Sets tracing. See "trace".
117
118 Example:
119
120 my $ssh2 = Net::SSH2->new(trace => -1);
121
122 Note that tracing requires a version of libssh2 compiled with
123 debugging support.
124
125 debug
126 Enable debugging. See "debug".
127
128 compress
129 Sets flag "LIBSSH2_FLAG_COMPRESS". See "flag".
130
131 sigpipe
132 Sets flag "LIBSSH2_FLAG_SIGPIPE". See "flag".
133
134 banner ( text )
135 Set the SSH2 banner text sent to the remote host (prepends required
136 "SSH-2.0-").
137
138 version
139 In scalar context, returns libssh2 version/patch e.g. 0.18 or
140 "0.18.0-20071110". In list context, returns that version plus the
141 numeric version (major, minor, and patch, each encoded as 8 bits, e.g.
142 0x001200 for version 0.18) and the default banner text (e.g.
143 "SSH-2.0-libssh2_0.18.0-20071110").
144
145 error
146 Returns the last error code. In list context, returns (code, error
147 name, error string).
148
149 Note that the returned error value is only meaningful after some other
150 method indicates an error by returning false.
151
152 die_with_error ( [message] )
153 Calls "die" with the given message and the error information from the
154 object appended.
155
156 For instance:
157
158 $ssh2->connect("ajhkfhdklfjhklsjhd", 22)
159 or $ssh2->die_with_error;
160 # dies as:
161 # Unable to connect to remote host: Invalid argument (-1 LIBSSH2_ERROR_SOCKET_NONE)
162
163 sock
164 Returns a reference to the underlying IO::Socket object (usually a
165 derived class as IO::Socket::IP or IO::Socket::INET), or "undef" if not
166 yet connected.
167
168 trace
169 Calls "libssh2_trace" with supplied bitmask. In order to enable all
170 tracing pass -1 as follows:
171
172 $ssh2->trace(-1);
173
174 A version of libssh2 compiled with tracing support is required.
175
176 timeout ( timeout_ms )
177 Enables a global timeout (in milliseconds) which will affect every
178 action (requires libssh2 1.2.9 or later).
179
180 By default, or if you set the timeout to zero, Net::SSH2 has no
181 timeout.
182
183 Note that timeout errors may leave the SSH connection in an
184 inconsistent state and further operations may fail or behave
185 incorrectly. Actually, some methods are able to recover after a timeout
186 error and others are not.
187
188 Don't hesitate to report any issue you encounter related to this so
189 that it can be fixed or at least, documented!
190
191 method ( type [, values... ] )
192 Sets or gets a method preference. For get, pass in the type only; to
193 set, pass in either a list of values or a comma-separated string.
194 Values can only be queried after the session is connected.
195
196 The following methods can be set or queried:
197
198 LIBSSH2_METHOD_KEX
199 Key exchange method names. Supported values:
200
201 diffie-hellman-group1-sha1
202 Diffie-Hellman key exchange with SHA-1 as hash, and Oakley
203 Group 2 (see RFC 2409).
204
205 diffie-hellman-group14-sha1
206 Diffie-Hellman key exchange with SHA-1 as hash, and Oakley
207 Group 14 (see RFC 3526).
208
209 diffie-hellman-group-exchange-sha1
210 Diffie-Hellman key exchange with SHA-1 as hash, using a
211 safe-prime/generator pair (chosen by server) of arbitrary
212 strength (specified by client) (see IETF draft secsh-dh-group-
213 exchange).
214
215 LIBSSH2_METHOD_HOSTKEY
216 Public key algorithms. Supported values:
217
218 ssh-dss
219 Based on the Digital Signature Standard (FIPS-186-2).
220
221 ssh-rsa
222 Based on PKCS#1 (RFC 3447).
223
224 LIBSSH2_METHOD_CRYPT_CS
225 Encryption algorithm from client to server. Supported algorithms:
226
227 aes256-cbc
228 AES in CBC mode, with 256-bit key.
229
230 rijndael-cbc@lysator.liu.se
231 Alias for aes256-cbc.
232
233 aes192-cbc
234 AES in CBC mode, with 192-bit key.
235
236 aes128-cbc
237 AES in CBC mode, with 128-bit key.
238
239 blowfish-cbc
240 Blowfish in CBC mode.
241
242 arcfour
243 ARCFOUR stream cipher.
244
245 cast128-cbc
246 CAST-128 in CBC mode.
247
248 3des-cbc
249 Three-key 3DES in CBC mode.
250
251 none
252 No encryption.
253
254 LIBSSH2_METHOD_CRYPT_SC
255 Encryption algorithm from server to client. See the
256 "LIBSSH2_METHOD_CRYPT_CS" entry above for supported algorithms.
257
258 LIBSSH2_METHOD_MAC_CS
259 Message Authentication Code (MAC) algorithms from client to server.
260 Supported values:
261
262 hmac-sha1
263 SHA-1 with 20-byte digest and key length.
264
265 hmac-sha1-96
266 SHA-1 with 20-byte key length and 12-byte digest length.
267
268 hmac-md5
269 MD5 with 16-byte digest and key length.
270
271 hmac-md5-96
272 MD5 with 16-byte key length and 12-byte digest length.
273
274 hmac-ripemd160
275 RIPEMD-160 algorithm with 20-byte digest length.
276
277 hmac-ripemd160@openssh.com
278 Alias for hmac-ripemd160.
279
280 none
281 No encryption.
282
283 LIBSSH2_METHOD_MAC_SC
284 Message Authentication Code (MAC) algorithms from server to client.
285 See LIBSSH2_METHOD_MAC_CS for supported algorithms.
286
287 LIBSSH2_METHOD_COMP_CS
288 Compression methods from client to server. Supported values:
289
290 zlib
291 The "zlib" compression method as described in RFC 1950 and RFC
292 1951.
293
294 none
295 No compression
296
297 LIBSSH2_METHOD_COMP_SC
298 Compression methods from server to client. See
299 LIBSSH2_METHOD_COMP_CS for supported compression methods.
300
301 connect ( handle | host [, port])
302 The argument combinations accepted are as follows:
303
304 a glob or "IO::*" object reference
305 Note that tied file handles are not acceptable. The underlying
306 libssh2 requires real file handles.
307
308 host [, port]
309 In order to handle IPv6 addresses the optional module
310 IO::Socket::IP is required.
311
312 The port number defaults to 22.
313
314 This method used to accept a "Timeout" argument. That feature has been
315 replaced by the constructor "timeout" option but note that it takes
316 milliseconds instead of seconds!
317
318 disconnect ( [description [, reason [, language]]] )
319 Sends a clean disconnect message to the remote server. Default values
320 are empty strings for description and language, and
321 "SSH_DISCONNECT_BY_APPLICATION" for the reason.
322
323 hostname
324 The name of the remote host given at connect time or retrieved from the
325 TCP layer.
326
327 port
328 The port number of the remote SSH server.
329
330 hostkey_hash ( hash type )
331 Returns a hash of the host key; note that the key is raw data and may
332 contain nulls or control characters.
333
334 The type may be as follows:
335
336 LIBSSH2_HOSTKEY_HASH_MD5
337 MD5 hash, 16 bytes long (requires libssh2 compiled with MD5
338 support).
339
340 LIBSSH2_HOSTKEY_HASH_SHA1
341 SHA1 hash, 20 bytes long.
342
343 Note: in previous versions of the module this method was called
344 "hostkey".
345
346 remote_hostkey
347 Returns the public key from the remote host and its type which is one
348 of "LIBSSH2_HOSTKEY_TYPE_RSA", "LIBSSH2_HOSTKEY_TYPE_DSS", or
349 "LIBSSH2_HOSTKEY_TYPE_UNKNOWN".
350
351 check_hostkey( [policy, [known_hosts_path [, comment] ] ] )
352 Looks for the remote host key inside the given known host file
353 (defaults to "~/.ssh/known_hosts").
354
355 On success, this method returns the result of the call done under the
356 hood to "Net::SSH2::KnownHost::check" (i.e.
357 "LIBSSH2_KNOWNHOST_CHECK_MATCH", "LIBSSH2_KNOWNHOST_CHECK_FAILURE",
358 "LIBSSH2_KNOWNHOST_CHECK_NOTFOUND" or
359 "LIBSSH2_KNOWNHOST_CHECK_MISMATCH").
360
361 On failure it returns "undef".
362
363 The accepted policies are as follows:
364
365 LIBSSH2_HOSTKEY_POLICY_STRICT
366 Only host keys already present in the known hosts file are
367 accepted.
368
369 This is the default policy.
370
371 LIBSSH2_HOSTKEY_POLICY_ASK
372 If the host key is not present in the known hosts file, the user is
373 asked if it should be accepted or not.
374
375 If accepted, the key is added to the known host file with the given
376 comment.
377
378 LIBSSH2_HOSTKEY_POLICY_TOFU
379 Trust On First Use: if the host key is not present in the known
380 hosts file, it is added there and accepted.
381
382 LIBSSH2_HOSTKEY_POLICY_ADVISORY
383 The key is always accepted, but it is never saved into the known
384 host file.
385
386 callback
387 If a reference to a subroutine is given, it is called when the key
388 is not present in the known hosts file or a different key is found.
389 The arguments passed to the callback are the session object, the
390 matching error ("LIBSSH2_KNOWNHOST_CHECK_FAILURE",
391 "LIBSSH2_KNOWNHOST_CHECK_NOTFOUND" or
392 "LIBSSH2_KNOWNHOST_CHECK_MISMATCH") and the comment.
393
394 auth_list ( [username] )
395 Returns the authentication methods accepted by the server. In scalar
396 context the methods are returned as a comma separated string.
397
398 When the server accepted an unauthenticated session for the given
399 username, this method returns "undef" but "auth_ok" returns true.
400
401 auth_ok
402 Returns true when the session is authenticated.
403
404 auth_password ( username [, password [, callback ]] )
405 Authenticates using a password.
406
407 If the password has expired, if a callback code reference was given,
408 it's called as "callback($self, $username)" and should return a
409 password. If no callback is provided, LIBSSH2_ERROR_PASSWORD_EXPIRED
410 is returned.
411
412 auth_password_interact ( username [, callback])
413 Prompts the user for the password interactively (requires
414 Term::ReadKey).
415
416 auth_publickey ( username, publickey_path, privatekey_path [, passphrase ]
417 )
418 Authenticate using the given private key and an optional passphrase.
419
420 When libssh2 is compiled using OpenSSL as the crypto backend, passing
421 this method "undef" as the public key argument is acceptable (OpenSSL
422 is able to extract the public key from the private one).
423
424 See also "Supported key formats".
425
426 auth_publickey_frommemory ( username, publickey_blob, privatekey_blob [,
427 passphrase ] )
428 Authenticate using the given public/private key and an optional
429 passphrase. The keys must be PEM encoded (requires libssh2 1.6.0 or
430 later with the OpenSSL backend).
431
432 auth_hostbased ( username, publickey, privatekey, hostname, [, local
433 username [, passphrase ]] )
434 Host-based authentication using an optional passphrase. The local
435 username defaults to be the same as the remote username.
436
437 auth_keyboard ( username, password | callback )
438 Authenticate using "keyboard-interactive". Takes either a password, or
439 a callback code reference which is invoked as "callback->(self,
440 username, name, instruction, prompt...)" (where each prompt is a hash
441 with "text" and "echo" keys, signifying the prompt text and whether the
442 user input should be echoed, respectively) which should return an array
443 of responses.
444
445 If only a username is provided, the default callback will handle
446 standard interactive responses (requires Term::ReadKey)
447
448 auth_agent ( username )
449 Try to authenticate using an SSH agent (requires libssh2 1.2.3).
450
451 auth ( ... )
452 This is a general, prioritizing authentication mechanism that can use
453 any of the previous methods. You provide it some parameters and
454 (optionally) a ranked list of methods you want considered (defaults to
455 all). It will remove any unsupported methods or methods for which it
456 doesn't have parameters (e.g. if you don't give it a public key, it
457 can't use publickey or hostkey), and try the rest, returning whichever
458 one succeeded or "undef" if they all failed. If a parameter is passed
459 with an "undef" value, a default value will be supplied if possible.
460
461 The parameters are:
462
463 rank
464 An optional ranked list of methods to try. The names should be the
465 names of the Net::SSH2 "auth" methods, e.g. "keyboard" or
466 "publickey", with the addition of "keyboard-auto" for automated
467 "keyboard-interactive" and "password-interact" which prompts the
468 user for the password interactively.
469
470 username
471 password
472 publickey
473 privatekey
474 "privatekey" and "publickey" are file paths.
475
476 passphrase
477 hostname
478 local_username
479 interact
480 If this option is set to a true value, interactive methods will be
481 enabled.
482
483 fallback
484 If a password is given but authentication using it fails, the
485 module will fall back to ask the user for another password if this
486 parameter is set to a true value.
487
488 cb_keyboard
489 auth_keyboard callback.
490
491 cb_password
492 auth_password callback.
493
494 For historical reasons and in order to maintain backward compatibility
495 with older versions of the module, when the "password" argument is
496 given, it is also used as the passphrase (and a deprecation warning
497 generated).
498
499 In order to avoid that behaviour the "passphrase" argument must be also
500 passed (it could be "undef"). For instance:
501
502 $ssh2->auth(username => $user,
503 privatekey => $privatekey_path,
504 publickey => $publickey_path,
505 password => $password,
506 passphrase => undef);
507
508 This work around will be removed in a not too distant future version of
509 the module.
510
511 flag (key, value)
512 Sets the given session flag.
513
514 The currently supported flag values are:
515
516 LIBSSH2_FLAG_COMPRESS
517 If set before the connection negotiation is performed, compression
518 will be negotiated for this connection.
519
520 Compression can also be enabled passing option "compress" to the
521 constructor new.
522
523 LIBSSH2_FLAG_SIGPIPE
524 if set, Net::SSH2/libssh2 will not attempt to block SIGPIPEs but
525 will let them trigger from the underlying socket layer.
526
527 keepalive_config(want_reply, interval)
528 Set how often keepalive messages should be sent.
529
530 "want_reply" indicates whether the keepalive messages should request a
531 response from the server. "interval" is number of seconds that can pass
532 without any I/O.
533
534 keepalive_send
535 Send a keepalive message if needed.
536
537 On failure returns undef. On success returns how many seconds you can
538 sleep after this call before you need to call it again.
539
540 Note that the underlying libssh2 function "libssh2_keepalive_send" can
541 not recover from EAGAIN errors. If this method fails with such error,
542 the SSH connection may become corrupted.
543
544 The usage of this function is discouraged.
545
546 channel ( [type, [window size, [packet size]]] )
547 Creates and returns a new channel object. See Net::SSH2::Channel.
548
549 Type, if given, must be "session" (a reminiscence of an old, more
550 generic, but never working wrapping).
551
552 tcpip ( host, port [, shost, sport ] )
553 Creates a TCP connection from the remote host to the given host:port,
554 returning a new channel.
555
556 The "shost" and "sport" arguments are merely informative and passed to
557 the remote SSH server as the origin of the connection. They default to
558 127.0.0.1:22.
559
560 Note that this method does not open a new port on the local machine and
561 forwards incoming connections to the remote side.
562
563 listen ( port [, host [, bound port [, queue size ]]] )
564 Sets up a TCP listening port on the remote host. Host defaults to
565 0.0.0.0; if bound port is provided, it should be a scalar reference in
566 which the bound port is returned. Queue size specifies the maximum
567 number of queued connections allowed before the server refuses new
568 connections.
569
570 Returns a new Net::SSH2::Listener object.
571
572 scp_get ( remote_path [, local_path ] )
573 Retrieve a file with SCP. Local path defaults to basename of remote.
574
575 Alternatively, "local_path" may be an already open file handle or an
576 IO::Handle object (e.g. IO::File, IO::Scalar).
577
578 scp_put ( local_path [, remote_path ] )
579 Send a file with SCP. Remote path defaults to same as local.
580
581 Alternatively, "local_path" may be an already open file handle or a
582 reference to a IO::Handle object (it must have a valid stat method).
583
584 sftp
585 Return SecureFTP interface object (see Net::SSH2::SFTP).
586
587 Note that SFTP support in libssh2 is pretty rudimentary. You should
588 consider using Net::SFTP::Foreign with the Net::SSH2 backend
589 Net::SFTP::Foreign::Backend::Net_SSH2 instead.
590
591 public_key
592 Return public key interface object (see Net::SSH2::PublicKey).
593
594 known_hosts
595 Returns known hosts interface object (see Net::SSH2::KnownHosts).
596
597 poll ( timeout, arrayref of hashes )
598 Deprecated: the poll functionality in libssh2 is deprecated and its
599 usage disregarded. Session methods "sock" and "block_directions" can be
600 used instead to integrate Net::SSH2 inside an external event loop.
601
602 Pass in a timeout in milliseconds and an arrayref of hashes with the
603 following keys:
604
605 handle
606 May be a Net::SSH2::Channel or Net::SSH2::Listener object, integer
607 file descriptor, or perl file handle.
608
609 events
610 Requested events. Combination of LIBSSH2_POLLFD_* constants (with
611 the POLL prefix stripped if present), or an arrayref of the names
612 ('in', 'hup' etc.).
613
614 revents
615 Returned events. Returns a hash with the (lowercased) names of the
616 received events ('in', 'hup', etc.) as keys with true values, and a
617 "value" key with the integer value.
618
619 Returns undef on error, or the number of active objects.
620
621 block_directions
622 Get the blocked direction after some method returns
623 "LIBSSH2_ERROR_EAGAIN".
624
625 Returns "LIBSSH2_SESSION_BLOCK_INBOUND" or/and
626 "LIBSSH2_SESSION_BLOCK_OUTBOUND".
627
628 debug ( state )
629 Class method (affects all Net::SSH2 objects).
630
631 Pass 1 to enable, 0 to disable. Debug output is sent to "STDERR".
632
633 blocking ( flag )
634 Enable or disable blocking.
635
636 A good number of the methods in "Net::SSH2"/"libssh2" can not work in
637 non-blocking mode. Some of them may just forcibly enable blocking
638 during its execution. A few may even corrupt the SSH session or crash
639 the program.
640
641 The ones that can be safely called are "read" and, with some caveats,
642 "write". See "write" in Net::SSH2::Channel.
643
644 Don't hesitate to report any bug you found in that area!
645
647 Protocol versions
648 The underlying "libssh2" library does support version 2 of the SSH
649 protocol exclusively (hopefully, version 1 usage is almost extinct.)
650
651 The SFTP client implements version 3 of the SFTP protocol.
652
653 Key formats
654 Private and public keys can be generated and stored using different
655 formats and cyphers. Which ones are accepted by "Net::SSH2" depends on
656 the libssh2 version being used and of the underlying crypto backend it
657 was configured to use at build time (OpenSSL "libssl" or "libgcrypt").
658
659 An increasingly common problem is that OpenSSH since version 7.8
660 (released 2018-8-24) generates keys by default using the format RFC4716
661 which is not supported by the default crypto backend ("libssl").
662
663 Keys can be converted inplace to the old PEM format using ssh-keygen(1)
664 as follows:
665
666 $ ssh-keygen -p -m PEM -N "" -f ~/.ssh/id_rsa
667
668 On Windows, PuTTYgen (which is part of the PuTTY distribution) can be
669 used to convert keys.
670
671 Another common issue is that in the last years OpenSSH has incorporated
672 several new cyphers that are not supported by any version of "libssh2"
673 yet. Currently the best option from an interoperability standpoint is
674 probably to stick to RSA key usage.
675
676 Security
677 Nowadays "libssh2" development is not thrilling; new versions (even
678 minor ones) are being released just every two or three years. On the
679 other hand security issues are found and reported far more frequently.
680 That means that "Net::SSH2"/"libssh2" could be an easy attack vector.
681
682 So, Net::SSH2 should be used only in trusted environments. More
683 specifically, using it to connect to untrusted third party computers
684 over the Internet is probably a very bad idea!
685
687 Net::SSH2::Channel, Net::SSH2::Listener, Net::SSH2::SFTP,
688 Net::SSH2::File, Net::SSH2::Dir.
689
690 LibSSH2 documentation at <http://www.libssh2.org>.
691
692 IETF Secure Shell (secsh) working group at
693 <http://www.ietf.org/html.charters/secsh-charter.html>.
694
695 Net::SSH::Any and Net::SFTP::Foreign integrate nicely with Net::SSH2.
696
697 Other Perl modules related to SSH you may find interesting:
698 Net::OpenSSH, Net::SSH::Perl, Net::OpenSSH::Parallel,
699 Net::OpenSSH::Compat.
700
702 Copyright (C) 2005 - 2010 by David B. Robins (dbrobins@cpan.org).
703
704 Copyright (C) 2010 - 2020 by Rafael Kitover (rkitover@cpan.org).
705
706 Copyright (C) 2011 - 2020 by Salvador FandiƱo (salva@cpan.org).
707
708 All rights reserved.
709
710 This library is free software; you can redistribute it and/or modify it
711 under the same terms as Perl itself, either Perl version 5.8.0 or, at
712 your option, any later version of Perl 5 you may have available.
713
714
715
716perl v5.38.0 2023-07-21 Net::SSH2(3)