1Net::SSH::Perl(3) User Contributed Perl Documentation Net::SSH::Perl(3)
2
3
4
6 Net::SSH::Perl - Perl client Interface to SSH
7
9 use Net::SSH::Perl;
10 my $ssh = Net::SSH::Perl->new($host);
11 $ssh->login($user, $pass);
12 my($stdout, $stderr, $exit) = $ssh->cmd($cmd);
13
15 Net::SSH::Perl is an all-Perl module implementing an SSH (Secure Shell)
16 client. It is compatible with both the SSH-1 and SSH-2 protocols.
17
18 Net::SSH::Perl enables you to simply and securely execute commands on
19 remote machines, and receive the STDOUT, STDERR, and exit status of
20 that remote command. It contains built-in support for various methods
21 of authenticating with the server (password authentication, RSA
22 challenge-response authentication, etc.). It completely implements the
23 I/O buffering, packet transport, and user authentication layers of the
24 SSH protocol, and makes use of external Perl libraries (in the Crypt::
25 family of modules) to handle encryption of all data sent across the
26 insecure network. It can also read your existing SSH configuration
27 files (/etc/ssh_config, etc.), RSA identity files, Ed25519 identity
28 files, known hosts files, etc.
29
30 One advantage to using Net::SSH::Perl over wrapper-style
31 implementations of ssh clients is that it saves on process overhead:
32 you no longer need to fork and execute a separate process in order to
33 connect to an sshd. Depending on the amount of time and memory needed
34 to fork a process, this win can be quite substantial; particularly if
35 you're running in a persistent Perl environment (mod_perl, for
36 example), where forking a new process is a drain on process and memory
37 resources.
38
39 It also simplifies the process of using password-based authentications;
40 when writing a wrapper around ssh you probably need to use Expect to
41 control the ssh client and give it your password. Net::SSH::Perl has
42 built-in support for the authentication protocols, so there's no longer
43 any hassle of communicating with any external processes.
44
45 The SSH2 protocol support (present in Net::SSH::Perl as of version
46 1.00) is compatible with the SSH2 implementation in OpenSSH, and should
47 also be fully compatible with the "official" SSH implementation. If you
48 find an SSH2 implementation that is not compatible with Net::SSH::Perl,
49 please let me know (email address down in AUTHOR & COPYRIGHTS); it
50 turns out that some SSH2 implementations have subtle differences from
51 others. AES-CTR ("aes256-ctr", "aes192-ctr", and "aes128-ctr") and
52 Chacha20-Poly1305 ciphers are currently supported for SSH2 encryption.
53 Deprecated ciphers AES-CBC ("aes256-cbc", "aes192-cbc", and
54 "aes128-cbc") 3DES ("3des-cbc"), Blowfish ("blowfish-cbc"), and RC4
55 ("arcfour") are available but not enabled by default. One can enable
56 them by using the Ciphers options parameter. For example:
57
58 options => [ "Ciphers +aes256-cbc" ]
59
60 Using the + notation will append a cipher to the default ciphers list.
61
62 Integrity checking is performed by the "hmac-sha2-256",
63 "hmac-sha2-512", "hmac-sha2-256-etm@openssh.com", or
64 "hmac-sha2-512-etm@openssh.com" algorithms. The deprecated "hmac-sha1"
65 or "hmac-md5" algorithms are available but not enabled by default.
66 Many older SSH server installations still use hmac-sha1 as the main
67 accepted MAC algorithm. To enable this, use the following options
68 parameter:
69
70 options => [ "MACs +hmac-sha1" ]
71
72 Compression, if requested, is limited to Zlib.
73
74 Supported server host key algorithms are "ssh-ed25519", "rsa-sha2-512",
75 "rsa-sha2-256", "ecdsa-sha2-nistp521", "ecdsa-sha2-nistp384",
76 "ecdsa-sha2-nistp256", and "ssh-rsa". Deprecated "ssh-dss" is
77 supported but not enabled by default. It can be enabled with the
78 options parameter:
79
80 options => [ "HostKeyAlgorithms +ssh-dss" ]
81
82 Supported SSH2 public key authentication algorithms are the same.
83
84 Supported Key Exchange (KEX) algorithms are
85 "diffie-hellman-group1-sha1", "diffie-hellman-group14-sha1",
86 c<diffie-hellman-group14-sha256>, "diffie-hellman-group16-sha512",
87 "diffie-hellman-group18-sha512",
88 "diffie-hellman-group-exchange-sha256",
89 "diffie-hellman-group-exchange-sha1", and
90 "curve25519-sha256@libssh.org"/"curve25519-sha256". The
91 "diffie-hellman-group1-sha1" algorithm is disabled by default, but can
92 be activated via the options parameter:
93
94 options => [ "KexAlgorithms +diffie-hellman-group1-sha1" ]
95
96 If you're looking for SFTP support, take a look at Net::SFTP, which
97 provides a full-featured Perl implementation of SFTP, and sits on top
98 of Net::SSH::Perl. SFTP requires the usage of the SSH2 protocol.
99
101 Usage of Net::SSH::Perl is very simple.
102
103 Net::SSH::Perl->new($host, %params)
104 To set up a new connection, call the new method, which connects to
105 $host and returns a Net::SSH::Perl object.
106
107 new accepts the following named parameters in %params:
108
109 • protocol
110
111 The protocol you wish to use for the connection: should be either
112 2, 1, '1,2' or '2,1'. The first two say, quite simply, "only use
113 this version of the protocol" (SSH-2 or SSH-1, respectively). The
114 latter two specify that either protocol can be used, but that one
115 protocol (the first in the comma-separated list) is preferred over
116 the other.
117
118 For this reason, it's "safer" to use the latter two protocol
119 specifications, because they ensure that either way, you'll be able
120 to connect; if your server doesn't support the first protocol
121 listed, the second will be used. (Presumably your server will
122 support at least one of the two protocols. :)
123
124 The default value is '1,2', for compatibility with OpenSSH; this
125 means that the client will use SSH-1 if the server supports SSH-1.
126 Of course, you can always override this using a user/global
127 configuration file, or through using this constructor argument.
128
129 • cipher
130
131 Specifies the name of the encryption cipher that you wish to use
132 for this connection. This must be one of the supported ciphers;
133 specifying an unsupported cipher will give you an error when you
134 enter algorithm negotiation (in either SSH-1 or SSH-2).
135
136 In SSH-1, the supported cipher names are IDEA, DES, DES3, and
137 Blowfish; in SSH-2, the supported ciphers are aes256-ctr,
138 aes192-ctr, aes128-ctr, chacha20-poly1305@openssh.com. arcfour,
139 blowfish-cbc, and 3des-cbc are deprecated and are not enabled by
140 default. aes256-cbc, aes192-cbc, and aes128-cbc are also supported
141 but not enabled by default as CBC is no longer considered secure.
142
143 The default SSH-1 cipher is IDEA; the default SSH-2 ciphers are
144 aes256-ctr, aes192-ctr, aes128-ctr, chacha20-poly1305@openssh.com.
145
146 • ciphers
147
148 Like cipher, this is a method of setting the cipher you wish to use
149 for a particular SSH connection; but this corresponds to the
150 Ciphers configuration option, where cipher corresponds to Cipher.
151 This also applies only in SSH-2.
152
153 This should be a comma-separated list of SSH-2 cipher names; the
154 list of cipher names is listed above in cipher.
155
156 This defaults to:
157 chacha20-poly1305@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr.
158
159 • port
160
161 The port of the sshd daemon to which you wish to connect; if not
162 specified, this is assumed to be the default ssh port.
163
164 • debug
165
166 Set to a true value if you want debugging messages printed out
167 while the connection is being opened. These can be helpful in
168 trying to determine connection problems, etc. The messages are
169 similar (and in some cases exact) to those written out by the ssh
170 client when you use the -v option.
171
172 Defaults to false.
173
174 • interactive
175
176 Set to a true value if you're using Net::SSH::Perl interactively.
177 This is used in determining whether or not to display password
178 prompts, for example. It's basically the inverse of the BatchMode
179 parameter in ssh configuration.
180
181 Defaults to false.
182
183 • privileged
184
185 Set to a true value if you want to bind to a privileged port
186 locally. You'll need this if you plan to use Rhosts or Rhosts-RSA
187 authentication, because the remote server requires the client to
188 connect on a privileged port. Of course, to bind to a privileged
189 port you'll need to be root.
190
191 If you don't provide this parameter, and Net::SSH::Perl detects
192 that you're running as root, this will automatically be set to
193 true. Otherwise it defaults to false.
194
195 • identity_files
196
197 A list of identity files to be used in pubkey authentication. The
198 value of this argument should be a reference to an array of
199 strings, each string identifying the location of an identity file.
200 Each identity file will be tested against the server until the
201 client finds one that authenticates successfully.
202
203 If you don't provide this, SSH1 authentication defaults to using
204 $ENV{HOME}/.ssh/identity, and SSH2 authentication defaults to the
205 three files $ENV{HOME}/.ssh/id_ed25519, $ENV{HOME}/.ssh/id_ecdsa,
206 and $ENV{HOME}/.ssh/id_rsa.
207
208 • strict_host_key_checking
209
210 This corresponds to the StrictHostKeyChecking ssh configuration
211 option. Allowed values are no, yes, or ask. no disables host key
212 checking, e.g., if you connect to a virtual host that answers to
213 multiple IP addresses. yes or ask enable it, and when it fails in
214 interactive mode, you are asked whether to continue. The host is
215 then added to the list of known hosts.
216
217 • compression
218
219 If set to a true value, compression is turned on for the session
220 (assuming that the server supports it).
221
222 Compression is off by default.
223
224 Note that compression requires that you have the Compress::Zlib
225 module installed on your system. If the module can't be loaded
226 successfully, compression is disabled; you'll receive a warning
227 stating as much if you having debugging on (debug set to 1), and
228 you try to turn on compression.
229
230 • compression_level
231
232 Specifies the compression level to use if compression is enabled
233 (note that you must provide both the compression and
234 compression_level arguments to set the level; providing only this
235 argument will not turn on encryption).
236
237 This setting is only applicable to SSH-1; the compression level for
238 SSH-2 Zlib compression is always set to 6.
239
240 The default value is 6.
241
242 • use_pty
243
244 Set this to 1 if you want to request a pseudo tty on the remote
245 machine. This is really only useful if you're setting up a shell
246 connection (see the shell method, below); and in that case, unless
247 you've explicitly declined a pty (by setting use_pty to 0), this
248 will be set automatically to 1. In other words, you probably won't
249 need to use this, often.
250
251 The default is 1 if you're starting up a shell, and 0 otherwise.
252
253 • terminal_mode_string
254
255 Specify the POSIX terminal mode string to send when use_pty is set.
256 By default the only mode set is the VEOF character to 0x04 (opcode
257 5, value 0x00000004). See RFC 4254 section 8 for complete details
258 on this value.
259
260 • no_append_veof
261
262 (SSH-2 only) Set this to 1 if you specified use_pty and do not want
263 Ctrl-D (0x04) appended twice to the end of your input string. On
264 most systems, these bytes cause the terminal driver to return "EOF"
265 when standard input is read. Without them, many programs that read
266 from standard input will hang after consuming all the data on
267 STDIN.
268
269 No other modifications are made to input data. If your data
270 contains 0x04 bytes, you may need to escape them.
271
272 Set this to 0 if you have raw terminal data to specify on standard
273 input, and you have terminated it correctly.
274
275 • options
276
277 Used to specify additional options to the configuration settings;
278 useful for specifying options for which there is no separate
279 constructor argument. This is analogous to the -o command line flag
280 to the ssh program.
281
282 If used, the value should be a reference to a list of option
283 directives in the format used in the config file. For example:
284
285 my $ssh = Net::SSH::Perl->new("host", options => [
286 "BatchMode yes", "RhostsAuthentication no" ]);
287
288 Available options are:
289
290 BindAddress
291 Host
292 BatchMode
293 ChallengeResponseAuthentication
294 CheckHostIP
295 Cipher
296 Ciphers*
297 Compression
298 CompressionLevel
299 DSAAuthentication
300 FingerprintHash
301 GlobalKnownHostsFile
302 HashKnownHosts
303 HostKeyAlgorithms*
304 HostName
305 IdentityFile
306 KexAlgorithms*
307 MACs*
308 NumberOfPasswordPrompts
309 PasswordAuthentication
310 PasswordPromptHost
311 PasswordPromptLogin
312 Port
313 Protocol
314 RhostsAuthentication
315 RhostsRSAAuthentication
316 RSAAuthentication
317 StrictHostKeyChecking
318 UpdateHostKeys
319 UsePrivilegedPort
320 User
321 UserKnownHostsFile
322
323 * Indicates the +/- wildcard notation may be used.
324
325 For example:
326
327 MACs +hmac-sha1
328
329 will add hmac-sha1 to the default MACs list.
330
331 Or:
332
333 Ciphers +aes*-cbc
334
335 will add aes128-cbc, aes192-cbc, and aes256-cbc to the default
336 Ciphers
337
338 While:
339
340 KexAlgorithms -*-sha512
341
342 will remove all algorithms that end in -sha512 from the default
343 list.
344
345 $ssh->login([ $user [, $password [, $suppress_shell ] ] ])
346 Sets the username and password to be used when authenticating with the
347 sshd daemon. The username $user is required for all authentication
348 protocols (to identify yourself to the remote server), but if you don't
349 supply it the username of the user executing the program is used.
350
351 The password $password is needed only for password authentication (it's
352 not used for passphrases on encrypted RSA/DSA identity files, though
353 perhaps it should be). And if you're running in an interactive session
354 and you've not provided a password, you'll be prompted for one.
355
356 By default, Net::SSH::Perl will open a channel with a shell on it. This
357 is usually what you want. If you are tunneling another protocol over
358 SSH, however, you may want to prevent this behavior. Passing a true
359 value in $suppress_shell will prevent the shell channel from being
360 opened (SSH2 only).
361
362 ($out, $err, $exit) = $ssh->cmd($cmd, [ $stdin ])
363 Runs the command $cmd on the remote server and returns the stdout,
364 stderr, and exit status of that command.
365
366 If $stdin is provided, it's supplied to the remote command $cmd on
367 standard input.
368
369 NOTE: the SSH-1 protocol does not support running multiple commands per
370 connection, unless those commands are chained together so that the
371 remote shell can evaluate them. Because of this, a new socket
372 connection is created each time you call cmd, and disposed of
373 afterwards. In other words, this code:
374
375 my $ssh = Net::SSH::Perl->new("host1");
376 $ssh->login("user1", "pass1");
377
378 $ssh->cmd("foo");
379 $ssh->cmd("bar");
380
381 will actually connect to the sshd on the first invocation of cmd, then
382 disconnect; then connect again on the second invocation of cmd, then
383 disconnect again.
384
385 Note that this does not apply to the SSH-2 protocol. SSH-2 fully
386 supports running more than one command over the same connection.
387
388 $ssh->shell
389 Opens up an interactive shell on the remote machine and connects it to
390 your STDIN. This is most effective when used with a pseudo tty;
391 otherwise you won't get a command line prompt, and it won't look much
392 like a shell. For this reason--unless you've specifically declined
393 one--a pty will be requested from the remote machine, even if you
394 haven't set the use_pty argument to new (described above).
395
396 This is really only useful in an interactive program.
397
398 In addition, you'll probably want to set your terminal to raw input
399 before calling this method. This lets Net::SSH::Perl process each
400 character and send it off to the remote machine, as you type it.
401
402 To do so, use Term::ReadKey in your program:
403
404 use Term::ReadKey;
405 ReadMode('raw');
406 $ssh->shell;
407 ReadMode('restore');
408
409 In fact, you may want to place the "restore" line in an END block, in
410 case your program exits prior to reaching that line.
411
412 If you need an example, take a look at eg/pssh, which uses almost this
413 exact code to implement an ssh shell.
414
415 $ssh->register_handler($packet_type, $subref [, @args ])
416 Registers an anonymous subroutine handler $subref to handle packets of
417 type $packet_type during the client loop. The subroutine will be called
418 when packets of type $packet_type are received, and in addition to the
419 standard arguments (see below), will receive any additional arguments
420 in @args, if specified.
421
422 The client loop is entered after the client has sent a command to the
423 remote server, and after any STDIN data has been sent; it consists of
424 reading packets from the server (STDOUT packets, STDERR packets, etc.)
425 until the server sends the exit status of the command executed
426 remotely. At this point the client exits the client loop and
427 disconnects from the server.
428
429 When you call the cmd method, the client loop by default simply sticks
430 STDOUT packets into a scalar variable and returns that value to the
431 caller. It does the same for STDERR packets, and for the process exit
432 status. (See the docs for cmd).
433
434 You can, however, override that default behavior, and instead process
435 the data itself as it is sent to the client. You do this by calling the
436 register_handler method and setting up handlers to be called at
437 specific times.
438
439 The behavior of the register_handler method differs between the
440 Net::SSH::Perl SSH-1 and SSH-2 implementations. This is so because of
441 the differences between the protocols (all client-server communications
442 in SSH-2 go through the channel mechanism, which means that input
443 packets are processed differently).
444
445 • SSH-1 Protocol
446
447 In the SSH-1 protocol, you should call register_handler with two
448 arguments: a packet type $packet_type and a subroutine reference
449 $subref. Your subroutine will receive as arguments the
450 Net::SSH::Perl::SSH1 object (with an open connection to the ssh3),
451 and a Net::SSH::Perl::Packet object, which represents the packet
452 read from the server. It will also receive any additional arguments
453 @args that you pass to register_handler; this can be used to give
454 your callback functions access to some of your otherwise private
455 variables, if desired. $packet_type should be an integer constant;
456 you can import the list of constants into your namespace by
457 explicitly loading the Net::SSH::Perl::Constants module:
458
459 use Net::SSH::Perl::Constants qw( :msg );
460
461 This will load all of the MSG constants into your namespace so that
462 you can use them when registering the handler. To do that, use this
463 method. For example:
464
465 $ssh->register_handler(SSH_SMSG_STDOUT_DATA, sub {
466 my($ssh, $packet) = @_;
467 print "I received this: ", $packet->get_str;
468 });
469
470 To learn about the methods that you can call on the packet object,
471 take a look at the Net::SSH::Perl::Packet docs, as well as the
472 Net::SSH::Perl::Buffer docs (the get_* and put_* methods).
473
474 Obviously, writing these handlers requires some knowledge of the
475 contents of each packet. For that, read through the SSH RFC, which
476 explains each packet type in detail. There's a get_* method for
477 each datatype that you may need to read from a packet.
478
479 Take a look at eg/remoteinteract.pl for an example of interacting
480 with a remote command through the use of register_handler.
481
482 • SSH-2 Protocol
483
484 In the SSH-2 protocol, you call register_handler with two
485 arguments: a string identifying the type of handler you wish to
486 create, and a subroutine reference. The "string" should be, at this
487 point, either "stdout" or "stderr"; any other string will be
488 silently ignored. "stdout" denotes that you wish to handle STDOUT
489 data sent from the server, and "stderr" that you wish to handle
490 STDERR data.
491
492 Your subroutine reference will be passed two arguments: a
493 Net::SSH::Perl::Channel object that represents the open channel on
494 which the data was sent, and a Net::SSH::Perl::Buffer object
495 containing data read from the server. In addition to these two
496 arguments, the callback will be passed any additional arguments
497 @args that you passed to register_handler; this can be used to give
498 your callback functions to otherwise private variables, if desired.
499
500 This illustrates the two main differences between the SSH-1 and
501 SSH-2 implementations. The first difference is that, as mentioned
502 above, all communication between server and client is done through
503 channels, which are built on top of the main connection between
504 client and server. Multiple channels are multiplexed over the same
505 connection. The second difference is that, in SSH-1, you are
506 processing the actual packets as they come in; in SSH-2, the
507 packets have already been processed somewhat, and their contents
508 stored in buffers--you are processing those buffers.
509
510 The above example (the I received this example) of using
511 register_handler in SSH-1 would look like this in SSH-2:
512
513 $ssh->register_handler("stdout", sub {
514 my($channel, $buffer) = @_;
515 print "I received this: ", $buffer->bytes;
516 });
517
518 As you can see, it's quite similar to the form used in SSH-1, but
519 with a few important differences, due to the differences mentioned
520 above between SSH-1 and SSH-2.
521
523 Your basic SSH needs will hopefully be met by the methods listed above.
524 If they're not, however, you may want to use some of the additional
525 methods listed here. Some of these are aimed at end-users, while others
526 are probably more useful for actually writing an authentication module,
527 or a cipher, etc.
528
529 $ssh->config
530 Returns the Net::SSH::Perl::Config object managing the configuration
531 data for this SSH object. This is constructed from data passed in to
532 the constructor new (see above), merged with data read from the user
533 and system configuration files. See the Net::SSH::Perl::Config docs for
534 details on methods you can call on this object (you'll probably be more
535 interested in the get and set methods).
536
537 $ssh->sock
538 Returns the socket connection to sshd. If your client is not connected,
539 dies.
540
541 $ssh->debug($msg)
542 If debugging is turned on for this session (see the debug parameter to
543 the new method, above), writes $msg to "STDERR". Otherwise nothing is
544 done.
545
546 $ssh->incoming_data
547 Incoming data buffer, an object of type Net::SSH::Perl::Buffer.
548 Returns the buffer object.
549
550 The idea behind this is that we our socket is non-blocking, so we
551 buffer input and periodically check back to see if we've read a full
552 packet. If we have a full packet, we rip it out of the incoming data
553 buffer and process it, returning it to the caller who presumably asked
554 for it.
555
556 This data "belongs" to the underlying packet layer in
557 Net::SSH::Perl::Packet. Unless you really know what you're doing you
558 probably don't want to disturb that data.
559
560 $ssh->session_id
561 Returns the session ID, which is generated from the server's host and
562 server keys, and from the check bytes that it sends along with the
563 keys. The server may require the session ID to be passed along in other
564 packets, as well (for example, when responding to RSA challenges).
565
566 $packet = $ssh->packet_start($packet_type)
567 Starts building a new packet of type $packet_type. This is just a handy
568 method for lazy people. Internally it calls
569 Net::SSH::Perl::Packet::new, so take a look at those docs for more
570 details.
571
573 For samples/tutorials, take a look at the scripts in eg/ in the
574 distribution directory.
575
576 Please report bugs at: https://github.com/lkinley/Net-SSH-Perl/issues
577
579 Development on V2 by Lance Kinley lkinley@rythmos.com
580
581 Previous maintainers were: David Robins, dbrobins@cpan.org Dave Rolsky,
582 autarch@urth.org.
583
584 Originally written by Benjamin Trott.
585
587 Copyright (c) 2015-2017 Rythmos, Inc. Copyright (c) 2001-2003 Benjamin
588 Trott, Copyright (c) 2003-2008 David Rolsky. Copyright (c) David
589 Robins. All rights reserved. This program is free software; you can
590 redistribute it and/or modify it under the same terms as Perl itself.
591
592 The full text of the license can be found in the LICENSE file included
593 with this module.
594
595
596
597perl v5.34.0 2021-07-22 Net::SSH::Perl(3)