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

NAME

6       Net::OpenSSH - Perl SSH client package implemented on top of OpenSSH
7

SYNOPSIS

9         use Net::OpenSSH;
10
11         my $ssh = Net::OpenSSH->new($host);
12         $ssh->error and
13           die "Couldn't establish SSH connection: ". $ssh->error;
14
15         $ssh->system("ls /tmp") or
16           die "remote command failed: " . $ssh->error;
17
18         my @ls = $ssh->capture("ls");
19         $ssh->error and
20           die "remote ls command failed: " . $ssh->error;
21
22         my ($out, $err) = $ssh->capture2("find /root");
23         $ssh->error and
24           die "remote find command failed: " . $ssh->error;
25
26         my ($rin, $pid) = $ssh->pipe_in("cat >/tmp/foo") or
27           die "pipe_in method failed: " . $ssh->error;
28
29         print $rin "hello\n";
30         close $rin;
31
32         my ($rout, $pid) = $ssh->pipe_out("cat /tmp/foo") or
33           die "pipe_out method failed: " . $ssh->error;
34
35         while (<$rout>) { print }
36         close $rout;
37
38         my ($in, $out ,$pid) = $ssh->open2("foo");
39         my ($pty, $pid) = $ssh->open2pty("foo");
40         my ($in, $out, $err, $pid) = $ssh->open3("foo");
41         my ($pty, $err, $pid) = $ssh->open3pty("login");
42
43         my $sftp = $ssh->sftp();
44         $sftp->error and die "SFTP failed: " . $sftp->error;
45

DESCRIPTION

47       Net::OpenSSH is a secure shell client package implemented on top of
48       OpenSSH binary client ("ssh").
49
50   Under the hood
51       This package is implemented around the multiplexing feature found in
52       later versions of OpenSSH. That feature allows one to run several
53       sessions over a single SSH connection (OpenSSH 4.1 was the first one to
54       provide all the required functionality).
55
56       When a new Net::OpenSSH object is created, the OpenSSH "ssh" client is
57       run in master mode, establishing a persistent (for the lifetime of the
58       object) connection to the server.
59
60       Then, every time a new operation is requested a new "ssh" process is
61       started in slave mode, effectively reusing the master SSH connection to
62       send the request to the remote side.
63
64   Net::OpenSSH Vs. Net::SSH::.* modules
65       Why should you use Net::OpenSSH instead of any of the other Perl SSH
66       clients available?
67
68       Well, this is my (biased) opinion:
69
70       Net::SSH::Perl is not well maintained nowadays (update: a new
71       maintainer has stepped in so this situation could change!!!), requires
72       a bunch of modules (some of them very difficult to install) to be
73       acceptably efficient and has an API that is limited in some ways.
74
75       Net::SSH2 is much better than Net::SSH::Perl, but not completely stable
76       yet. It can be very difficult to install on some specific operating
77       systems and its API is also limited, in the same way as Net::SSH::Perl.
78
79       Using Net::SSH::Expect, in general, is a bad idea. Handling interaction
80       with a shell via Expect in a generic way just can not be reliably done.
81
82       Net::SSH is just a wrapper around any SSH binary commands available on
83       the machine. It can be very slow as they establish a new SSH connection
84       for every operation performed.
85
86       In comparison, Net::OpenSSH is a pure perl module that does not have
87       any mandatory dependencies (obviously, besides requiring OpenSSH
88       binaries).
89
90       Net::OpenSSH has a very perlish interface. Most operations are
91       performed in a fashion very similar to that of the Perl builtins and
92       common modules (e.g. IPC::Open2).
93
94       It is also very fast. The overhead introduced by launching a new ssh
95       process for every operation is not appreciable (at least on my Linux
96       box). The bottleneck is the latency intrinsic to the protocol, so
97       Net::OpenSSH is probably as fast as an SSH client can be.
98
99       Being based on OpenSSH is also an advantage: a proved, stable, secure
100       (to paranoid levels), inseparably and well maintained implementation of
101       the SSH protocol is used.
102
103       On the other hand, Net::OpenSSH does not work on Windows, not even
104       under Cygwin.
105
106       Net::OpenSSH specifically requires the OpenSSH SSH client (AFAIK, the
107       multiplexing feature is not available from any other SSH client).
108       However, note that it will interact with any server software, not just
109       servers running OpenSSH "sshd".
110
111       For password authentication, IO::Pty has to be installed. Other modules
112       and binaries are also required to implement specific functionality (for
113       instance Net::SFTP::Foreign, Expect or rsync(1)).
114
115       Net::OpenSSH and Net::SSH2 do not support version 1 of the SSH
116       protocol.
117

API

119   Optional arguments
120       Almost all methods in this package accept as first argument an optional
121       reference to a hash containing parameters ("\%opts"). For instance,
122       these two method calls are equivalent:
123
124         my $out1 = $ssh->capture(@cmd);
125         my $out2 = $ssh->capture({}, @cmd);
126
127   Error handling
128       Most methods return undef (or an empty list) to indicate failure.
129
130       The "error" method can always be used to explicitly check for errors.
131       For instance:
132
133         my ($output, $errput) = $ssh->capture2({timeout => 1}, "find /");
134         $ssh->error and die "ssh failed: " . $ssh->error;
135
136   Net::OpenSSH methods
137       These are the methods provided by the package:
138
139       Net::OpenSSH->new($host, %opts)
140           Creates a new SSH master connection
141
142           $host can be a hostname or an IP address. It may also contain the
143           name of the user, her password and the TCP port number where the
144           server is listening:
145
146              my $ssh1 = Net::OpenSSH->new('jack@foo.bar.com');
147              my $ssh2 = Net::OpenSSH->new('jack:secret@foo.bar.com:10022');
148              my $ssh3 = Net::OpenSSH->new('jsmith@2001:db8::1428:57ab'); # IPv6
149
150           IPv6 addresses may optionally be enclosed in brackets:
151
152              my $ssh4 = Net::OpenSSH->new('jsmith@[::1]:1022');
153
154           This method always succeeds in returning a new object. Error
155           checking has to be performed explicitly afterwards:
156
157             my $ssh = Net::OpenSSH->new($host, %opts);
158             $ssh->error and die "Can't ssh to $host: " . $ssh->error;
159
160           If you have problems getting Net::OpenSSH to connect to the remote
161           host read the troubleshooting chapter near the end of this
162           document.
163
164           Accepted options:
165
166           user => $user_name
167               Login name
168
169           port => $port
170               TCP port number where the server is running
171
172           password => $password
173               User given password for authentication.
174
175               Note that using password authentication in automated scripts is
176               a very bad idea. When possible, you should use public key
177               authentication instead.
178
179           passphrase => $passphrase
180               Uses given passphrase to open private key.
181
182           key_path => $private_key_path
183               Uses the key stored on the given file path for authentication.
184
185           gateway => $gateway
186               If the given argument is a gateway object as returned by
187               "find_gateway" in Net::OpenSSH::Gateway method, use it to
188               connect to the remote host.
189
190               If it is a hash reference, call the "find_gateway" method
191               first.
192
193               For instance, the following code fragments are equivalent:
194
195                 my $gateway = Net::OpenSSH::Gateway->find_gateway(
196                         proxy => 'http://proxy.corporate.com');
197                 $ssh = Net::OpenSSH->new($host, gateway => $gateway);
198
199               and
200
201                 $ssh = Net::OpenSSH->new($host,
202                         gateway => { proxy => 'http://proxy.corporate.com'});
203
204           proxy_command => $proxy_command
205               Use the given command to establish the connection to the remote
206               host (see "ProxyCommand" on ssh_config(5)).
207
208           batch_mode => 1
209               Disables querying the user for password and passphrases.
210
211           ctl_dir => $path
212               Directory where the SSH master control socket will be created.
213
214               This directory and its parents must be writable only by the
215               current effective user or root, otherwise the connection will
216               be aborted to avoid insecure operation.
217
218               By default "~/.libnet-openssh-perl" is used.
219
220           ctl_path => $path
221               Path to the SSH master control socket.
222
223               Usually this option should be avoided as the module is able to
224               pick an unused socket path by itself. An exception to that rule
225               is when the "external_master" feature is enabled.
226
227               Note that the length of the path is usually limited to between
228               92 and 108 bytes, depending of the underlying operating system.
229
230           ssh_cmd => $cmd
231               Name or full path to OpenSSH "ssh" binary. For instance:
232
233                 my $ssh = Net::OpenSSH->new($host, ssh_cmd => '/opt/OpenSSH/bin/ssh');
234
235           scp_cmd => $cmd
236               Name or full path to OpenSSH "scp" binary.
237
238               By default it is inferred from the "ssh" one.
239
240           rsync_cmd => $cmd
241               Name or full path to "rsync" binary. Defaults to "rsync".
242
243           remote_shell => $name
244               Name of the remote shell. Used to select the argument quoter
245               backend.
246
247           timeout => $timeout
248               Maximum acceptable time that can elapse without network traffic
249               or any other event happening on methods that are not immediate
250               (for instance, when establishing the master SSH connection or
251               inside methods "capture", "system", "scp_get", etc.).
252
253               See also "Timeouts".
254
255           kill_ssh_on_timeout => 1
256               This option tells Net::OpenSSH to kill the local slave SSH
257               process when some operation times out.
258
259               See also "Timeouts".
260
261           strict_mode => 0
262               By default, the connection will be aborted if the path to the
263               socket used for multiplexing is found to be non-secure (for
264               instance, when any of the parent directories is writable by
265               other users).
266
267               This option can be used to disable that feature. Use with
268               care!!!
269
270           async => 1
271               By default, the constructor waits until the multiplexing socket
272               is available. That option can be used to defer the waiting
273               until the socket is actually used.
274
275               For instance, the following code connects to several remote
276               machines in parallel:
277
278                 my (%ssh, %ls);
279                 # multiple connections are established in parallel:
280                 for my $host (@hosts) {
281                     $ssh{$host} = Net::OpenSSH->new($host, async => 1);
282                 }
283                 # then to run some command in all the hosts (sequentially):
284                 for my $host (@hosts) {
285                     $ssh{$host}->system('ls /');
286                 }
287
288           connect => 0
289               Do not launch the master SSH process yet.
290
291           master_opts => [...]
292               Additional options to pass to the "ssh" command when
293               establishing the master connection. For instance:
294
295                 my $ssh = Net::OpenSSH->new($host,
296                     master_opts => [-o => "ProxyCommand corkscrew httpproxy 8080 $host"]);
297
298           default_ssh_opts => [...]
299               Default slave SSH command line options for "open_ex" and
300               derived methods.
301
302               For instance:
303
304                 my $ssh = Net::OpenSSH->new($host,
305                     default_ssh_opts => [-o => "ConnectionAttempts=0"]);
306
307           forward_agent => 1
308           forward_agent => 'always'
309               Enables forwarding of the authentication agent.
310
311               When "always" is passed as the argument, agent forwarding will
312               be enabled by default in all the channels created from the
313               object. Otherwise, it will have to be explicitly requested when
314               calling the channel creating methods (i.e. "open_ex" and its
315               derivations).
316
317               This option can not be used when passing a passphrase (via
318               "passphrase") to unlock the login private key.
319
320               Note that Net::OpenSSH will not run "ssh-agent" for you. This
321               has to be done ahead of time and the environment variable
322               "SSH_AUTH_SOCK" set pointing to the proper place.
323
324           forward_X11 => 1
325               Enables forwarding of the X11 protocol
326
327           default_stdin_fh => $fh
328           default_stdout_fh => $fh
329           default_stderr_fh => $fh
330               Default I/O streams for "open_ex" and derived methods
331               (currently, that means any method but "pipe_in" and "pipe_out"
332               and I plan to remove those exceptions soon!).
333
334               For instance:
335
336                 open my $stderr_fh, '>>', '/tmp/$host.err' or die ...;
337                 open my $stdout_fh, '>>', '/tmp/$host.log' or die ...;
338
339                 my $ssh = Net::OpenSSH->new($host, default_stderr_fh => $stderr_fh,
340                                                    default_stdout_fh => $stdout_fh);
341                 $ssh->error and die "SSH connection failed: " . $ssh->error;
342
343                 $ssh->scp_put("/foo/bar*", "/tmp")
344                   or die "scp failed: " . $ssh->error;
345
346           default_stdin_file = $fn
347           default_stdout_file = $fn
348           default_stderr_file = $fn
349               Opens the given file names and use them as the defaults.
350
351           master_stdout_fh => $fh
352           master_stderr_fh => $fh
353               Redirect corresponding stdio streams of the master SSH process
354               to given filehandles.
355
356           master_stdout_discard => $bool
357           master_stderr_discard => $bool
358               Discard corresponding stdio streams.
359
360           expand_vars => $bool
361               Activates variable expansion inside command arguments and file
362               paths.
363
364               See "Variable expansion" below.
365
366           vars => \%vars
367               Initial set of variables.
368
369           external_master => 1
370               Instead of launching a new OpenSSH client in master mode, the
371               module tries to reuse an already existent one. "ctl_path" must
372               also be passed when this option is set. See also
373               "get_ctl_path".
374
375               Example:
376
377                 $ssh = Net::OpenSSH->new('foo', external_master => 1, ctl_path = $path);
378
379               When "external_master" is set, the hostname argument becomes
380               optional (0.0.0.0 is passed to OpenSSH which does not use it at
381               all).
382
383           default_encoding => $encoding
384           default_stream_encoding => $encoding
385           default_argument_encoding => $encoding
386               Set default encodings. See "Data encoding".
387
388           password_prompt => $string
389           password_prompt => $re
390               By default, when using password authentication, the module
391               expects the remote side to send a password prompt matching
392               "/[?:]/".
393
394               This option can be used to override that default for the rare
395               cases when a different prompt is used.
396
397               Examples:
398
399                  password_prompt => ']'; # no need to escape ']'
400                  password_prompt => qr/[:?>]/;
401
402           login_handler => \&custom_login_handler
403               Some remote SSH server may require a custom
404               login/authentication interaction not natively supported by
405               Net::OpenSSH. In that cases, you can use this option to replace
406               the default login logic.
407
408               The callback will be invoked repeatedly as
409               "custom_login_handler($ssh, $pty, $data)" where $ssh is the
410               current Net::OpenSSH object, "pty" a IO::Pty object attached to
411               the slave "ssh" process tty and $data a reference to an scalar
412               you can use at will.
413
414               The login handler must return 1 after the login process has
415               completed successfully or 0 in case it still needs to do
416               something else. If some error happens, it must die.
417
418               Note, that blocking operations should not be performed inside
419               the login handler (at least if you want the "async" and
420               "timeout" features to work).
421
422               See also the sample script "login_handler.pl" in the "examples"
423               directory.
424
425               Usage of this option is incompatible with the "password" and
426               "passphrase" options, you will have to handle password or
427               passphrases from the custom handler yourself.
428
429           master_setpgrp => 1
430               When this option is set, the master process is run as a
431               different process group. As a consequence it will not die when
432               the user presses Ctrl-C at the terminal.
433
434               In order to allow the master SSH process to request any
435               information from the user, the module may set it as the
436               terminal controlling process while the connection is
437               established (using "tcsetpgrp" in POSIX). Afterwards, the
438               terminal controlling process is reset.
439
440               This feature is highly experimental. Report any problems you
441               may find, please.
442
443           master_pty_force => 1
444               By default, Net::OpenSSH attaches the master SSH process to a
445               pty only when some kind of interactive authentication is
446               requested. If this flag is set a pty will be attached always.
447
448               That allows to get better diagnostics for some kind of errors
449               (as for instance, bad host keys) and also allows to retrieve
450               the pty log using get_master_pty_log.
451
452       $ssh->error
453           Returns the error condition for the last performed operation.
454
455           The returned value is a dualvar as $! (see "$!" in perlvar) that
456           renders an informative message when used in string context or an
457           error number in numeric context (error codes appear in
458           Net::OpenSSH::Constants).
459
460       $ssh->get_master_pty_log
461           In order to handle password authentication or entering the
462           passphrase for a private key, Net::OpenSSH may run the master SSH
463           process attached to a pty.
464
465           In that case and after a constructor call returns a connection
466           failure error, this method can be called to retrieve the output
467           captured at the pty (the log is discarded when the connection is
468           established successfully).
469
470           Any data consumed from the pty by custom login handlers will be
471           missing from the the returned log.
472
473       $ssh->get_user
474       $ssh->get_host
475       $ssh->get_port
476           Return the corresponding SSH login parameters.
477
478       $ssh->get_ctl_path
479           Returns the path to the socket where the OpenSSH master process
480           listens for new multiplexed connections.
481
482       ($in, $out, $err, $pid) = $ssh->open_ex(\%opts, @cmd)
483           Note: this is a low level method which, probably, you do not need
484           to use!
485
486           That method starts the command @cmd on the remote machine creating
487           new pipes for the IO channels as specified on the %opts hash.
488
489           If @cmd is omitted, the remote user shell is run.
490
491           Returns four values, the first three ($in, $out and $err)
492           correspond to the local side of the pipes created (they can be
493           undef) and the fourth ($pid) to the PID of the new SSH slave
494           process. An empty list is returned on failure.
495
496           Note that "waitpid" has to be used afterwards to reap the slave SSH
497           process.
498
499           Accepted options:
500
501           stdin_pipe => 1
502               Creates a new pipe and connects the reading side to the stdin
503               stream of the remote process. The writing side is returned as
504               the first value ($in).
505
506           stdin_pty => 1
507               Similar to "stdin_pipe", but instead of a regular pipe it uses
508               a pseudo-tty (pty).
509
510               Note that on some operating systems (e.g. HP-UX, AIX), ttys are
511               not reliable. They can overflow when large chunks are written
512               or when data is written faster than it is read.
513
514           stdin_fh => $fh
515               Duplicates $fh and uses it as the stdin stream of the remote
516               process.
517
518           stdin_file => $filename
519           stdin_file => \@open_args
520               Opens the file of the given name for reading and uses it as the
521               remote process stdin stream.
522
523               If an array reference is passed its contents are used as the
524               arguments for the underlying open call. For instance:
525
526                 $ssh->system({stdin_file => ['-|', 'gzip -c -d file.gz']}, $rcmd);
527
528           stdin_discard => 1
529               Uses /dev/null as the remote process stdin stream.
530
531           stdout_pipe => 1
532               Creates a new pipe and connects the writing side to the stdout
533               stream of the remote process. The reading side is returned as
534               the second value ($out).
535
536           stdout_pty => 1
537               Connects the stdout stream of the remote process to the pseudo-
538               pty. This option requires "stdin_pty" to be also set.
539
540           stdout_fh => $fh
541               Duplicates $fh and uses it as the stdout stream of the remote
542               process.
543
544           stdout_file => $filename
545           stdout_file => \@open_args
546               Opens the file of the given filename and redirect stdout there.
547
548           stdout_discard => 1
549               Uses /dev/null as the remote process stdout stream.
550
551           stdinout_socket => 1
552               Creates a new socketpair, attaches the stdin an stdout streams
553               of the slave SSH process to one end and returns the other as
554               the first value ($in) and undef for the second ($out).
555
556               Example:
557
558                 my ($socket, undef, undef, $pid) = $ssh->open_ex({stdinout_socket => 1},
559                                                                  '/bin/netcat $dest');
560
561               See also "open2socket".
562
563           stdinout_dpipe => $cmd
564           stdinout_dpipe => \@cmd
565               Runs the given command locally attaching its stdio streams to
566               those of the remote SSH command. Conceptually it is equivalent
567               to the dpipe(1) shell command.
568
569           stderr_pipe => 1
570               Creates a new pipe and connects the writing side to the stderr
571               stream of the remote process. The reading side is returned as
572               the third value ($err).
573
574               Example:
575
576                 my $pid = $ssh->open_ex({stdinout_dpipe => 'vncviewer -stdio'},
577                                         x11vnc => '-inetd');
578
579           stderr_fh => $fh
580               Duplicates $fh and uses it as the stderr stream of the remote
581               process.
582
583           stderr_file => $filename
584               Opens the file of the given name and redirects stderr there.
585
586           stderr_to_stdout => 1
587               Makes stderr point to stdout.
588
589           tty => $bool
590               Tells "ssh" to allocate a pseudo-tty for the remote process. By
591               default, a tty is allocated if remote command stdin stream is
592               attached to a tty.
593
594               When this flag is set and stdin is not attached to a tty, the
595               ssh master and slave processes may generate spurious warnings
596               about failed tty operations. This is caused by a bug present in
597               older versions of OpenSSH.
598
599           close_slave_pty => 0
600               When a pseudo pty is used for the stdin stream, the slave side
601               is automatically closed on the parent process after forking the
602               ssh command.
603
604               This option disables that feature, so that the slave pty can be
605               accessed on the parent process as "$pty->slave". It will have
606               to be explicitly closed (see IO::Pty)
607
608           quote_args => $bool
609               See "Shell quoting" below.
610
611           remote_shell => $shell
612               Sets the remote shell. Allows one to change the argument
613               quoting mechanism in a per-command fashion.
614
615               This may be useful when interacting with a Windows machine
616               where argument parsing may be done at the command level in
617               custom ways.
618
619               Example:
620
621                 $ssh->system({remote_shell => 'MSWin'}, echo => $line);
622                 $ssh->system({remote_shell => 'MSCmd,MSWin'}, type => $file);
623
624           forward_agent => $bool
625               Enables/disables forwarding of the authentication agent.
626
627               This option can only be used when agent forwarding has been
628               previously requested on the constructor.
629
630           forward_X11 => $bool
631               Enables/disables forwarding of the X11 protocol.
632
633               This option can only be used when X11 forwarding has been
634               previously requested on the constructor.
635
636           ssh_opts => \@opts
637               List of extra options for the "ssh" command.
638
639               This feature should be used with care, as the given options are
640               not checked in any way by the module, and they could interfere
641               with it.
642
643           tunnel => $bool
644               Instead of executing a command in the remote host, this option
645               instruct Net::OpenSSH to create a TCP tunnel. The arguments
646               become the target IP and port or the remote path for an Unix
647               socket.
648
649               Example:
650
651                 my ($in, $out, undef, $pid) = $ssh->open_ex({tunnel => 1}, $IP, $port);
652                 my ($in, $out, undef, $pid) = $ssh->open_ex({tunnel => 1}, $socket_path);
653
654               See also "Tunnels".
655
656           subsystem => $bool
657               Request a connection to a SSH subsystem. The name of the
658               subsystem must be passed as an argument, as in the following
659               example:
660
661                 my $s = $ssh->open2socket({subsystem => 1}, 'netconf');
662
663           encoding => $encoding
664           argument_encoding => $encoding
665               Set encodings. See "Data encoding".
666
667           Usage example:
668
669             # similar to IPC::Open2 open2 function:
670             my ($in_pipe, $out_pipe, undef, $pid) =
671                 $ssh->open_ex( { stdin_pipe => 1,
672                                  stdout_pipe => 1 },
673                                @cmd )
674                 or die "open_ex failed: " . $ssh->error;
675             # do some IO through $in/$out
676             # ...
677             waitpid($pid);
678
679       setpgrp => 1
680           Calls "setpgrp" after forking the child process. As a result it
681           will not die when the user presses Ctrl+C at the console. See also
682           "setpgrp" in perlfunc.
683
684           Using this option without also setting "master_setpgrp" on the
685           constructor call is mostly useless as the signal will be delivered
686           to the master process and all the remote commands aborted.
687
688           This feature is experimental.
689
690       $ssh->system(\%opts, @cmd)
691           Runs the command @cmd on the remote machine.
692
693           Returns true on success, undef otherwise.
694
695           The error status is set to "OSSH_SLAVE_CMD_FAILED" when the remote
696           command exits with a non zero code (the code is available from $?,
697           see "$?" in perlvar).
698
699           Example:
700
701             $ssh->system('ls -R /')
702               or die "ls failed: " . $ssh->error";
703
704           As for "system" builtin, "SIGINT" and "SIGQUIT" signals are
705           blocked.  (see "system" in perlfunc). Also, setting $SIG{CHLD} to
706           "IGNORE" or to a custom signal handler will interfere with this
707           method.
708
709           Accepted options:
710
711           stdin_data => $input
712           stdin_data => \@input
713               Sends the given data through the stdin stream to the remote
714               process.
715
716               For example, the following code creates a file on the remote
717               side:
718
719                 $ssh->system({stdin_data => \@data}, "cat >/tmp/foo")
720                   or die "unable to write file: " . $ssh->error;
721
722           timeout => $timeout
723               The operation is aborted after $timeout seconds elapsed without
724               network activity.
725
726               See also "Timeouts".
727
728           async => 1
729               Does not wait for the child process to exit. The PID of the new
730               process is returned.
731
732               Note that when this option is combined with "stdin_data", the
733               given data will be transferred to the remote side before
734               returning control to the caller.
735
736               See also the "spawn" method documentation below.
737
738           stdin_fh => $fh
739           stdin_discard => $bool
740           stdout_fh => $fh
741           stdout_discard => $bool
742           stderr_fh => $fh
743           stderr_discard => $bool
744           stderr_to_stdout => $bool
745           stdinout_dpipe => $cmd
746           tty => $bool
747               See the "open_ex" method documentation for an explanation of
748               these options.
749
750           stdin_keep_open => $bool
751               When "stdin_data" is given, the module closes the stdin stream
752               once all the data has been sent. Unfortunately, some SSH buggy
753               servers fail to handle this event correctly and close the
754               channel prematurely.
755
756               As a workaround, when this flag is set the stdin is left open
757               until the remote process terminates.
758
759       $ok = $ssh->test(\%opts, @cmd);
760           Runs the given command and returns its success/failure exit status
761           as 1 or 0 respectively. Returns undef when something goes wrong in
762           the SSH layer.
763
764           Error status is not set to OSSH_SLAVE_CMD_FAILED when the remote
765           command exits with a non-zero code.
766
767           By default this method discards the remote command "stdout" and
768           "sterr" streams.
769
770           Usage example:
771
772             if ($ssh->test(ps => -C => $executable)) {
773               say "$executable is running on remote machine"
774             }
775             else {
776               die "something got wrong: ". $ssh->error if $ssh->error;
777
778               say "$executable is not running on remote machine"
779             }
780
781           This method support the same set of options as "system", except
782           "async" and "tunnel".
783
784       $output = $ssh->capture(\%opts, @cmd);
785       @output = $ssh->capture(\%opts, @cmd);
786           This method is conceptually equivalent to the perl backquote
787           operator (e.g. "`ls`"): it runs the command on the remote machine
788           and captures its output.
789
790           In scalar context returns the output as a scalar. In list context
791           returns the output broken into lines (it honors $/, see "$/" in
792           perlvar).
793
794           The exit status of the remote command is returned in $?.
795
796           When an error happens while capturing (for instance, the operation
797           times out), the partial captured output will be returned. Error
798           conditions have to be explicitly checked using the "error" method.
799           For instance:
800
801             my $output = $ssh->capture({ timeout => 10 },
802                                        "echo hello; sleep 20; echo bye");
803             $ssh->error and
804                 warn "operation didn't complete successfully: ". $ssh->error;
805             print $output;
806
807           Setting $SIG{CHLD} to a custom signal handler or to "IGNORE" will
808           interfere with this method.
809
810           Accepted options:
811
812           stdin_data => $input
813           stdin_data => \@input
814           stdin_keep_open => $bool
815               See the "system" method documentation for an explanation of
816               these options.
817
818           timeout => $timeout
819               See "Timeouts".
820
821           stdin_fh => $fh
822           stdin_discard => $bool
823           stderr_fh => $fh
824           stderr_discard => $bool
825           stderr_to_stdout => $bool
826           tty => $bool
827               See the "open_ex" method documentation for an explanation of
828               these options.
829
830       ($output, $errput) = $ssh->capture2(\%opts, @cmd)
831           captures the output sent to both stdout and stderr by @cmd on the
832           remote machine.
833
834           Setting $SIG{CHLD} to a custom signal handler or to "IGNORE" will
835           also interfere with this method.
836
837           The accepted options are:
838
839           stdin_data => $input
840           stdin_data => \@input
841           stdin_keep_open => $bool
842               See the "system" method documentation for an explanation of
843               these options.
844
845           timeout => $timeout
846               See "Timeouts".
847
848           stdin_fh => $fh
849           stdin_discard => $bool
850           tty => $bool
851               See the "open_ex" method documentation for an explanation of
852               these options.
853
854       ($in, $pid) = $ssh->pipe_in(\%opts, @cmd)
855           This method is similar to the following Perl "open" call
856
857             $pid = open $in, '|-', @cmd
858
859           but running @cmd on the remote machine (see "open" in perlfunc).
860
861           No options are currently accepted.
862
863           There is no need to perform a waitpid on the returned PID as it
864           will be done automatically by perl when $in is closed.
865
866           Example:
867
868             my ($in, $pid) = $ssh->pipe_in('cat >/tmp/fpp')
869                 or die "pipe_in failed: " . $ssh->error;
870             print $in $_ for @data;
871             close $in or die "close failed";
872
873       ($out, $pid) = $ssh->pipe_out(\%opts, @cmd)
874           Reciprocal to previous method, it is equivalent to
875
876             $pid = open $out, '-|', @cmd
877
878           running @cmd on the remote machine.
879
880           No options are currently accepted.
881
882       ($in, $out, $pid) = $ssh->open2(\%opts, @cmd)
883       ($pty, $pid) = $ssh->open2pty(\%opts, @cmd)
884       ($socket, $pid) = $ssh->open2socket(\%opts, @cmd)
885       ($in, $out, $err, $pid) = $ssh->open3(\%opts, @cmd)
886       ($pty, $err, $pid) = $ssh->open3pty(\%opts, @cmd)
887           Shortcuts around "open_ex" method.
888
889       $pid = $ssh->spawn(\%opts, @_)
890           Another "open_ex" shortcut, it launches a new remote process in the
891           background and returns the PID of the local slave SSH process.
892
893           At some later point in your script, "waitpid" should be called on
894           the returned PID in order to reap the slave SSH process.
895
896           For instance, you can run some command on several hosts in parallel
897           with the following code:
898
899             my %conn = map { $_ => Net::OpenSSH->new($_, async => 1) } @hosts;
900             my @pid;
901             for my $host (@hosts) {
902                 open my($fh), '>', "/tmp/out-$host.txt"
903                   or die "unable to create file: $!";
904                 push @pid, $conn{$host}->spawn({stdout_fh => $fh}, $cmd);
905             }
906
907             waitpid($_, 0) for @pid;
908
909           Note that "spawn" should not be used to start detached remote
910           processes that may survive the local program (see also the "FAQ"
911           about running remote processes detached).
912
913       ($socket, $pid) = $ssh->open_tunnel(\%opts, $dest_host, $port)
914       ($socket, $pid) = $ssh->open_tunnel(\%opts, $socket_path)
915           Similar to "open2socket", but instead of running a command, it
916           opens a TCP tunnel to the given address. See also "Tunnels".
917
918       $out = $ssh->capture_tunnel(\%opts, $dest_host, $port)
919       @out = $ssh->capture_tunnel(\%opts, $dest_host, $port)
920           Similar to "capture", but instead of running a command, it opens a
921           TCP tunnel.
922
923           Example:
924
925             $out = $ssh->capture_tunnel({stdin_data => join("\r\n",
926                                                             "GET / HTTP/1.0",
927                                                             "Host: www.perl.org",
928                                                             "", "") },
929                                         'www.perl.org', 80)
930
931           See also "Tunnels".
932
933       $ssh->scp_get(\%opts, $remote1, $remote2,..., $local_dir_or_file)
934       $ssh->scp_put(\%opts, $local, $local2,..., $remote_dir_or_file)
935           These two methods are wrappers around the "scp" command that allow
936           transfers of files to/from the remote host using the existing SSH
937           master connection.
938
939           When transferring several files, the target argument must point to
940           an existing directory. If only one file is to be transferred, the
941           target argument can be a directory or a file name or can be
942           omitted. For instance:
943
944             $ssh->scp_get({glob => 1}, '/var/tmp/foo*', '/var/tmp/bar*', '/tmp');
945             $ssh->scp_put('/etc/passwd');
946
947           Both "scp_get" and "scp_put" methods return a true value when all
948           the files are transferred correctly, otherwise they return undef.
949
950           Accepted options:
951
952           quiet => 0
953               By default, "scp" is called with the quiet flag "-q" enabled in
954               order to suppress progress information. This option allows one
955               to re-enable the progress indication bar.
956
957           verbose => 1
958               Calls "scp" with the "-v" flag.
959
960           recursive => 1
961               Copies files and directories recursively.
962
963           glob => 1
964               Enables expansion of shell metacharacters in the sources list
965               so that wildcards can be used to select files.
966
967           glob_flags => $flags
968               Second argument passed to File::Glob::bsd_glob function. Only
969               available for "scp_put" method.
970
971           copy_attrs => 1
972               Copies modification and access times and modes from the
973               original files.
974
975           bwlimit => $Kbits
976               Limits the used bandwidth, specified in Kbit/s.
977
978           timeout => $secs
979               The transfer is aborted if the connection does not finish
980               before the given timeout elapses. See also "Timeouts".
981
982           async => 1
983               Does not wait for the "scp" command to finish. When this option
984               is used, the method returns the PID of the child "scp" process.
985
986               For instance, it is possible to transfer files to several hosts
987               in parallel as follows:
988
989                 use Errno;
990                 my (%pid, %ssh);
991                 for my $host (@hosts) {
992                   $ssh{$host} = Net::OpenSSH->new($host, async => 1);
993                 }
994                 for my $host (@hosts) {
995                   $pid{$host} = $ssh{$host}->scp_put({async => 1}, $local_fn, $remote_fn)
996                     or warn "scp_put to $host failed: " . $ssh{$host}->error . "\n";
997                 }
998                 for my $host (@hosts) {
999                   if (my $pid = $pid{$host}) {
1000                     if (waitpid($pid, 0) > 0) {
1001                       my $exit = ($? >> 8);
1002                       $exit and warn "transfer of file to $host failed ($exit)\n";
1003                     }
1004                     else {
1005                       redo if ($! == EINTR);
1006                       warn "waitpid($pid) failed: $!\n";
1007                     }
1008                   }
1009                 }
1010
1011           stdout_fh => $fh
1012           stderr_fh => $fh
1013           stderr_to_stdout => 1
1014               These options are passed unchanged to method "open_ex",
1015               allowing capture of the output of the "scp" program.
1016
1017               Note that "scp" will not generate progress reports unless its
1018               stdout stream is attached to a tty.
1019
1020           ssh_opts => \@opts
1021               List of extra options for the "ssh" command.
1022
1023               This feature should be used with care, as the given options are
1024               not checked in any way by the module, and they could interfere
1025               with it.
1026
1027       $ssh->rsync_get(\%opts, $remote1, $remote2,..., $local_dir_or_file)
1028       $ssh->rsync_put(\%opts, $local1, $local2,..., $remote_dir_or_file)
1029           These methods use "rsync" over SSH to transfer files from/to the
1030           remote machine.
1031
1032           They accept the same set of options as the "scp" ones.
1033
1034           Any unrecognized option will be passed as an argument to the
1035           "rsync" command (see rsync(1)). Underscores can be used instead of
1036           dashes in "rsync" option names.
1037
1038           For instance:
1039
1040             $ssh->rsync_get({exclude => '*~',
1041                              verbose => 1,
1042                              safe_links => 1},
1043                             '/remote/dir', '/local/dir');
1044
1045       $sftp = $ssh->sftp(%sftp_opts)
1046           Creates a new Net::SFTP::Foreign object for SFTP interaction that
1047           runs through the ssh master connection.
1048
1049       @call = $ssh->make_remote_command(\%opts, @cmd)
1050       $call = $ssh->make_remote_command(\%opts, @cmd)
1051           This method returns the arguments required to execute a command on
1052           the remote machine via SSH. For instance:
1053
1054             my @call = $ssh->make_remote_command(ls => "/var/log");
1055             system @call;
1056
1057           In scalar context, returns the arguments quoted and joined into one
1058           string:
1059
1060             my $remote = $ssh->make_remote_comand("cd /tmp/ && tar xf -");
1061             system "tar cf - . | $remote";
1062
1063           The options accepted are as follows:
1064
1065           tty => $bool
1066               Enables/disables allocation of a tty on the remote side.
1067
1068           forward_agent => $bool
1069               Enables/disables forwarding of authentication agent.
1070
1071               This option can only be used when agent forwarding has been
1072               previously requested on the constructor.
1073
1074           tunnel => 1
1075               Return a command to create a connection to some TCP server
1076               reachable from the remote host. In that case the arguments are
1077               the destination address and port. For instance:
1078
1079                 $cmd = $ssh->make_remote_command({tunnel => 1}, $host, $port);
1080
1081           subsystem => 1
1082               Return a command for invoking a SSH subsystem (i.e. SFTP or
1083               netconf). In that case the only argument is the subsystem name.
1084
1085       $ssh->wait_for_master($async)
1086           When the connection has been established by calling the constructor
1087           with the "async" option, this call allows one to advance the
1088           process.
1089
1090           If $async is true, it will perform any work that can be done
1091           immediately without waiting (for instance, entering the password or
1092           checking for the existence of the multiplexing socket) and then
1093           return. If a false value is given, it will finalize the connection
1094           process and wait until the multiplexing socket is available.
1095
1096           It returns a true value after the connection has been successfully
1097           established. False is returned if the connection process fails or
1098           if it has not yet completed (then, the "error" method can be used
1099           to distinguish between both cases).
1100
1101           From version 0.64 upwards, undef is returned when the master is
1102           still in an unstable state (login, killing, etc.) and 0 when it is
1103           in a stable state (running, stopped or gone).
1104
1105       $ssh->check_master
1106           This method runs several checks to ensure that the master
1107           connection is still alive.
1108
1109       $ssh->shell_quote(@args)
1110           Returns the list of arguments quoted so that they will be restored
1111           to their original form when parsed by the remote shell.
1112
1113           In scalar context returns the list of arguments quoted and joined.
1114
1115           Usually this task is done automatically by the module. See "Shell
1116           quoting" below.
1117
1118           This method can also be used as a class method.
1119
1120           Example:
1121
1122             my $quoted_args = Net::OpenSSH->shell_quote(@args);
1123             system('ssh', '--', $host, $quoted_args);
1124
1125       $ssh->shell_quote_glob(@args)
1126           This method is like the previous "shell_quote" but leaves wildcard
1127           characters unquoted.
1128
1129           It can be used as a class method also.
1130
1131       $ssh->set_expand_vars($bool)
1132           Enables/disables variable expansion feature (see "Variable
1133           expansion").
1134
1135       $ssh->get_expand_vars
1136           Returns current state of variable expansion feature.
1137
1138       $ssh->set_var($name, $value)
1139       $ssh->get_var($name, $value)
1140           These methods allow one to change and to retrieve the value of the
1141           given name.
1142
1143       $ssh->get_master_pid
1144           Returns the PID of the master SSH process
1145
1146       $ssh->master_exited
1147           This methods allows one to tell the module that the master process
1148           has exited when we get its PID from some external wait or waitpid
1149           call. For instance:
1150
1151             my $ssh = Net::OpenSSH->new('foo', async => 1);
1152
1153             # create new processes
1154             # ...
1155
1156             # rip them...
1157             my $master_pid = $ssh->master_pid;
1158             while ((my $pid = wait) > 0) {
1159               if ($pid == $master_pid) {
1160                 $ssh->master_exited;
1161               }
1162             }
1163
1164           If your program rips the master process and this method is not
1165           called, the OS could reassign the PID to a new unrelated process
1166           and the module would try to kill it at object destruction time.
1167
1168       $ssh->disconnect($async)
1169           Shuts down the SSH connection.
1170
1171           Usually, you don't need to call this method explicitly, but just
1172           let the Net::OpenSSH object go out of scope.
1173
1174           If "async" is true, it doesn't wait for the SSH connection to
1175           terminate. In that case, "wait_for_master" must be called
1176           repeatedly until the shutdown sequence terminates (See the
1177           "AnyEvent" integration section below).
1178
1179       $ssh->restart($async)
1180           Restarts the SSH session closing any open connection and creating a
1181           new one. Any open channel would also be killed.
1182
1183           Note that calling this method may request again the password or
1184           passphrase from the user.
1185
1186           In asynchronous mode, this method requires the connection to be
1187           terminated before it gets called. Afterwards, "wait_for_master"
1188           should be called repeaptly until the new connection is stablished.
1189           For instance:
1190
1191             my $async = 1;
1192             $ssh->disconnect($async);
1193             while (1) {
1194               defined $ssh->wait_for_master($async) # returns 0 when the
1195                                                     # disconnect process
1196                                                     # finishes
1197                 and last;
1198               do_something_else();
1199             }
1200             $ssh->restart($async);
1201             while (1) {
1202               defined $ssh->wait_for_master($async)
1203                 and last;
1204               do_something_else();
1205             }
1206
1207       $pid = $ssh->sshfs_import(\%opts, $remote_fs, $local_mnt_point)
1208       $pid = $ssh->sshfs_export(\%opts, $local_fs, $remote_mnt_point)
1209           These methods use sshfs(1) to import or export a file system
1210           through the SSH connection.
1211
1212           They return the $pid of the "sshfs" process or of the slave "ssh"
1213           process used to proxy it. Killing that process unmounts the file
1214           system, though, it may be probably better to use fusermount(1).
1215
1216           The options accepted are as follows:
1217
1218           ssh_opts => \@ssh_opts
1219               Options passed to the slave "ssh" process.
1220
1221           sshfs_opts => \@sshfs_opts
1222               Options passed to the "sshfs" command. For instance, to mount
1223               the file system in read-only mode:
1224
1225                 my $pid = $ssh->sshfs_export({sshfs_opts => [-o => 'ro']},
1226                                              "/", "/mnt/foo");
1227
1228           Note that this command requires a recent version of "sshfs" to work
1229           (at the time of writing, it requires the yet unreleased version
1230           available from the FUSE git repository!).
1231
1232           See also the sshfs(1) man page and the "sshfs" and FUSE web sites
1233           at <https://github.com/libfuse/sshfs> and
1234           <https://github.com/libfuse/libfuse> respectively.
1235
1236       $or = $ssh->object_remote(@args)
1237           Returns an Object::Remote::Connection instance running on top of
1238           the Net::OpenSSH connection.
1239
1240           Example:
1241
1242              my $or = $ssh->object_remote;
1243              my $hostname = Sys::Hostname->can::on($or, 'hostname');
1244              say $hostname->();
1245
1246           See also Object::Remote.
1247
1248       $any = $ssh->any(%opts)
1249           Wraps the current object inside a Net::SSH::Any one.
1250
1251           Example:
1252
1253             my $any = $ssh->any;
1254             my $content = $any->scp_get_content("my-file.txt");
1255
1256       $pid = $ssh->disown_master
1257           Under normal operation Net::OpenSSH controls the life-time of the
1258           master "ssh" process and when the object is destroyed the master
1259           process and any connection running over it are terminated.
1260
1261           In some (rare) cases, it is desirable to let the master process and
1262           all the running connections survive. Calling this method does just
1263           that, it tells Net::OpenSSH object that the master process is not
1264           its own anymore.
1265
1266           The return value is the PID of the master process.
1267
1268           Note also that disowning the master process does not affect the
1269           operation of the module in any other regard.
1270
1271           For instance:
1272
1273             # See examples/sshfs_mount.pl for a working program
1274             my $ssh = Net::OpenSSH->new($host);
1275             my $sshfs_pid = $ssh->sshfs_import("/home/foo", "my-remote-home");
1276             $ssh->disown_master;
1277             $ssh->stop; # tells the master to stop accepting requests
1278             exit(0);
1279
1280   Shell quoting
1281       By default, when invoking remote commands, this module tries to mimic
1282       perl "system" builtin in regard to argument processing. Quoting
1283       "system" in perlfunc:
1284
1285         Argument processing varies depending on the number of arguments.  If
1286         there is more than one argument in LIST, or if LIST is an array with
1287         more than one value, starts the program given by the first element
1288         of the list with arguments given by the rest of the list.  If there
1289         is only one scalar argument, the argument is checked for shell
1290         metacharacters, and if there are any, the entire argument is passed
1291         to the system's command shell for parsing (this is "/bin/sh -c" on
1292         Unix platforms, but varies on other platforms).
1293
1294       Take for example Net::OpenSSH "system" method:
1295
1296         $ssh->system("ls -l *");
1297         $ssh->system('ls', '-l', '/');
1298
1299       The first call passes the argument unchanged to ssh and it is executed
1300       in the remote side through the shell which interprets metacharacters.
1301
1302       The second call escapes any shell metacharacters so that, effectively,
1303       it is equivalent to calling the command directly and not through the
1304       shell.
1305
1306       Under the hood, as the Secure Shell protocol does not provide for this
1307       mode of operation and always spawns a new shell where it runs the given
1308       command, Net::OpenSSH quotes any shell metacharacters in the command
1309       list.
1310
1311       All the methods that invoke a remote command (system, open_ex, etc.)
1312       accept the option "quote_args" that allows one to force/disable shell
1313       quoting.
1314
1315       For instance:
1316
1317         $ssh->system({quote_args => 1}, "/path with spaces/bin/foo");
1318
1319       will correctly handle the spaces in the program path.
1320
1321       The shell quoting mechanism implements some extensions (for instance,
1322       performing redirections to /dev/null on the remote side) that can be
1323       disabled with the option "quote_args_extended":
1324
1325         $ssh->system({ stderr_discard => 1,
1326                        quote_args => 1, quote_args_extended => 0 },
1327                      @cmd);
1328
1329       The option "quote_args" can also be used to disable quoting when more
1330       than one argument is passed. For instance, to get some pattern expanded
1331       by the remote shell:
1332
1333         $ssh->system({quote_args => 0}, 'ls', '-l', "/tmp/files_*.dat");
1334
1335       The method "shell_quote" can be used to selectively quote some
1336       arguments and leave others untouched:
1337
1338         $ssh->system({quote_args => 0},
1339                      $ssh->shell_quote('ls', '-l'),
1340                      "/tmp/files_*.dat");
1341
1342       When the glob option is set in "scp" and "rsync" file transfer methods,
1343       an alternative quoting method which knows about file wildcards and
1344       passes them unquoted is used. The set of wildcards recognized currently
1345       is the one supported by bash(1).
1346
1347       Another way to selectively use quote globing or fully disable quoting
1348       for some specific arguments is to pass them as scalar references or
1349       double scalar references respectively. In practice, that means
1350       prepending them with one or two backslashes. For instance:
1351
1352         # quote the last argument for globing:
1353         $ssh->system('ls', '-l', \'/tmp/my files/filed_*dat');
1354
1355         # append a redirection to the remote command
1356         $ssh->system('ls', '-lR', \\'>/tmp/ls-lR.txt');
1357
1358         # expand remote shell variables and glob in the same command:
1359         $ssh->system('tar', 'czf', \\'$HOME/out.tgz', \'/var/log/server.*.log');
1360
1361       As shell quoting is a tricky matter, I expect bugs to appear in this
1362       area. You can see how "ssh" is called, and the quoting used setting the
1363       following debug flag:
1364
1365         $Net::OpenSSH::debug |= 16;
1366
1367       By default, the module assumes the remote shell is some variant of a
1368       POSIX or Bourne shell ("bash", "dash", "ksh", etc.). If this is not the
1369       case, the construction option "remote_shell" can be used to select an
1370       alternative quoting mechanism.
1371
1372       For instance:
1373
1374         $ssh = Net::OpenSSH->new($host, remote_shell => 'csh');
1375         $ssh->system(echo => "hard\n to\n  quote\n   argument!");
1376
1377       Currently there are quoters available for POSIX (Bourne) compatible
1378       shells, "csh" and the two Windows variants "MSWin" (for servers using
1379       Win32::CreateProcess, see Net::OpenSSH::ShellQuoter::MSWin) and "MSCmd"
1380       (for servers using "cmd.exe", see Net::OpenSSH::ShellQuoter::MSCmd).
1381
1382       In any case, you can always do the quoting yourself and pass the quoted
1383       remote command as a single string:
1384
1385         # for VMS
1386         $ssh->system('DIR/SIZE NFOO::USERS:[JSMITH.DOCS]*.TXT;0');
1387
1388       Note that the current quoting mechanism does not handle possible
1389       aliases defined by the remote shell. In that case, to force execution
1390       of the command instead of the alias, the full path to the command must
1391       be used.
1392
1393   Timeouts
1394       In order to stop remote processes when they timeout, the ideal approach
1395       would be to send them signals through the SSH connection as specified
1396       by the protocol standard.
1397
1398       Unfortunately OpenSSH does not implement that feature so Net::OpenSSH
1399       has to use other imperfect approaches:
1400
1401       ā€¢   close slave I/O streams
1402
1403           Closing the STDIN and STDOUT streams of the unresponsive remote
1404           process will effectively deliver a SIGPIPE when it tries to access
1405           any of them.
1406
1407           Remote processes may not access STDIN or STDOUT and even then,
1408           Net::OpenSSH can only close these channels when it is capturing
1409           them, so this approach does not always work.
1410
1411       ā€¢   killing the local SSH slave process
1412
1413           This action may leave the remote process running, creating a remote
1414           orphan so Net::OpenSSH does not use it unless the construction
1415           option "kill_ssh_on_timeout" is set.
1416
1417       Luckily, future versions of OpenSSH will support signaling remote
1418       processes via the mux channel.
1419
1420   Variable expansion
1421       The variable expansion feature allows one to define variables that are
1422       expanded automatically inside command arguments and file paths.
1423
1424       This feature is disabled by default. It is intended to be used with
1425       Net::OpenSSH::Parallel and other similar modules.
1426
1427       Variables are delimited by a pair of percent signs ("%"), for instance
1428       "%HOST%". Also, two consecutive percent signs are replaced by a single
1429       one.
1430
1431       The special variables "HOST", "USER" and "PORT" are maintained
1432       internally by the module and take the obvious values.
1433
1434       Variable expansion is performed before shell quoting (see "Shell
1435       quoting").
1436
1437       Some usage example:
1438
1439         my $ssh = Net::OpenSSH->new('server.foo.com', expand_vars => 1);
1440         $ssh->set_var(ID => 42);
1441         $ssh->system("ls >/tmp/ls.out-%HOST%-%ID%");
1442
1443       will redirect the output of the "ls" command to
1444       "/tmp/ls.out-server.foo.com-42" on the remote host.
1445
1446   Tunnels
1447       Besides running commands on the remote host, Net::OpenSSH also allows
1448       one to tunnel TCP connections to remote machines reachable from the SSH
1449       server.
1450
1451       That feature is made available through the "tunnel" option of the
1452       "open_ex" method, and also through wrapper methods "open_tunnel" and
1453       "capture_tunnel" and most others where it makes sense.
1454
1455       Example:
1456
1457         $ssh->system({tunnel => 1,
1458                       stdin_data => "GET / HTTP/1.0\r\n\r\n",
1459                       stdout_file => "/tmp/$server.res"},
1460                      $server, 80)
1461             or die "unable to retrieve page: " . $ssh->error;
1462
1463       or capturing the output of several requests in parallel:
1464
1465         my @pids;
1466         for (@servers) {
1467           my $pid = $ssh->spawn({tunnel => 1,
1468                                  stdin_file => "/tmp/request.req",
1469                                  stdout_file => "/tmp/$_.res"},
1470                                 $_, 80);
1471           if ($pid) {
1472             push @pids, $pid;
1473           }
1474           else {
1475             warn "unable to spawn tunnel process to $_: " . $ssh->error;
1476           }
1477         }
1478         waitpid ($_, 0) for (@pids);
1479
1480       Under the hood, in order to create a tunnel, a new "ssh" process is
1481       spawned with the option "-W${address}:${port}" (available from OpenSSH
1482       5.4 and upwards) making it redirect its stdio streams to the remote
1483       given address. Unlike when "ssh" "-L" options is used to create
1484       tunnels, no TCP port is opened on the local machine at any time so this
1485       is a perfectly secure operation.
1486
1487       The PID of the new process is returned by the named methods. It must be
1488       reaped once the pipe or socket handlers for the local side of the
1489       tunnel have been closed.
1490
1491       OpenSSH 5.4 or later is required for the tunnels functionality to work.
1492       Also, note that tunnel forwarding may be administratively forbidden at
1493       the server side (see sshd(8) and sshd_config(5) or the documentation
1494       provided by your SSH server vendor).
1495
1496       Tunnels targeting UNIX sockets
1497
1498       When connecting to hosts running a recent version of OpenSSH sshd, it
1499       is also possible to open connections targeting Unix sockets.
1500
1501       For instance:
1502
1503         my $response = $ssh->capture({tunnel => 1, stdin_data => $request },
1504                                      "/tmp/socket-foo");
1505
1506       Currently, this feature requires a patched OpenSSH ssh client. The
1507       patch is available as
1508       "patches/openssh-fwd-stdio-to-streamlocal-1.patch".
1509
1510       Port forwarding
1511
1512       Net::OpenSSH does not offer direct support for handling port
1513       forwardings between server and client. But that can be done easily
1514       anyway passing custom SSH options to its methods.
1515
1516       For instance, tunnel creation options can be passed to the constructor:
1517
1518         my $ssh = Net::OpenSSH->new(...
1519                           master_opts => -Llocalhost:1234:localhost:3306');
1520
1521       The port forwardings can also be changed for a running SSH connection
1522       using a Control command:
1523
1524           # setting up a tunnel:
1525           $ssh->system({ssh_opts => ['-O','forward',
1526                                      '-L127.0.0.1:12345:127.0.0.1:3306']});
1527
1528           # canceling it:
1529           $ssh->system({ssh_opts => ['-O', 'cancel',
1530                                      '-L127.0.0.1:12345:127.0.0.1:3306']});
1531
1532   Data encoding
1533       Net::OpenSSH has some support for transparently converting the data
1534       send or received from the remote server to Perl internal unicode
1535       representation.
1536
1537       The methods supporting that feature are those that move data from/to
1538       Perl data structures (e.g. "capture", "capture2", "capture_tunnel" and
1539       methods supporting the "stdin_data" option). Data accessed through
1540       pipes, sockets or redirections is not affected by the encoding options.
1541
1542       It is also possible to set the encoding of the command and arguments
1543       passed to the remote server on the command line.
1544
1545       By default, if no encoding option is given on the constructor or on the
1546       method calls, Net::OpenSSH will not perform any encoding
1547       transformation, effectively processing the data as "latin1".
1548
1549       When data can not be converted between the Perl internal representation
1550       and the selected encoding inside some Net::OpenSSH method, it will fail
1551       with an "OSSH_ENCODING_ERROR" error.
1552
1553       The supported encoding options are as follows:
1554
1555       stream_encoding => $encoding
1556           sets the encoding of the data send and received on capture methods.
1557
1558       argument_encoding => $encoding
1559           sets the encoding of the command line arguments
1560
1561       encoding => $encoding
1562           sets both "argument_encoding" and "stream_encoding".
1563
1564       The constructor also accepts "default_encoding",
1565       "default_stream_encoding" and "default_argument_encoding" that set the
1566       defaults.
1567
1568   Diverting "new"
1569       When a code ref is installed at $Net::OpenSSH::FACTORY, calls to new
1570       will be diverted through it.
1571
1572       That feature can be used to transparently implement connection caching,
1573       for instance:
1574
1575         my $old_factory = $Net::OpenSSH::FACTORY;
1576         my %cache;
1577
1578         sub factory {
1579           my ($class, %opts) = @_;
1580           my $signature = join("\0", $class, map { $_ => $opts{$_} }, sort keys %opts);
1581           my $old = $cache{signature};
1582           return $old if ($old and $old->error != OSSH_MASTER_FAILED);
1583           local $Net::OpenSSH::FACTORY = $old_factory;
1584           $cache{$signature} = $class->new(%opts);
1585         }
1586
1587         $Net::OpenSSH::FACTORY = \&factory;
1588
1589       ... and I am sure it can be abused in several other ways!
1590

3rd PARTY MODULE INTEGRATION

1592   Expect
1593       Sometimes you would like to use Expect to control some program running
1594       in the remote host. You can do it as follows:
1595
1596         my ($pty, $pid) = $ssh->open2pty(@cmd)
1597             or die "unable to run remote command @cmd";
1598         my $expect = Expect->init($pty);
1599
1600       Then, you will be able to use the new Expect object in $expect as
1601       usual.
1602
1603   Net::Telnet
1604       This example is adapted from Net::Telnet documentation:
1605
1606         my ($pty, $pid) = $ssh->open2pty({stderr_to_stdout => 1})
1607           or die "unable to start remote shell: " . $ssh->error;
1608         my $telnet = Net::Telnet->new(-fhopen => $pty,
1609                                       -prompt => '/.*\$ $/',
1610                                       -telnetmode => 0,
1611                                       -cmd_remove_mode => 1,
1612                                       -output_record_separator => "\r");
1613
1614         $telnet->waitfor(-match => $telnet->prompt,
1615                          -errmode => "return")
1616           or die "login failed: " . $telnet->lastline;
1617
1618         my @lines = $telnet->cmd("who");
1619
1620         ...
1621
1622         $telnet->close;
1623         waitpid($pid, 0);
1624
1625   mod_perl and mod_perl2
1626       mod_perl and mod_perl2 tie STDIN and STDOUT to objects that are not
1627       backed up by real file descriptors at the operating system level.
1628       Net::OpenSSH will fail if any of these handles is used explicitly or
1629       implicitly when calling some remote command.
1630
1631       The work-around is to redirect them to "/dev/null" or to some file:
1632
1633         open my $def_in, '<', '/dev/null' or die "unable to open /dev/null";
1634         my $ssh = Net::OpenSSH->new($host,
1635                                     default_stdin_fh => $def_in);
1636
1637         my $out = $ssh->capture($cmd1);
1638         $ssh->system({stdout_discard => 1}, $cmd2);
1639         $ssh->system({stdout_to_file => '/tmp/output'}, $cmd3);
1640
1641       Also, note that from a security stand point, running "ssh" from inside
1642       the web server process is not a great idea. An attacker exploiting some
1643       Apache bug would be able to access the SSH keys and passwords and gain
1644       unlimited access to the remote systems.
1645
1646       If you can, use a queue (as TheSchwartz) or any other mechanism to
1647       execute the ssh commands from another process running under a different
1648       user account.
1649
1650       At a minimum, ensure that "~www-data/.ssh" (or similar) is not
1651       accessible through the web server!
1652
1653   Net::SFTP::Foreign
1654       See method "sftp".
1655
1656   Net::SSH::Any
1657       See method "any".
1658
1659   Object::Remote
1660       See method "object_remote".
1661
1662   AnyEvent (and similar frameworks)
1663       Net::OpenSSH provides all the functionality required to be integrated
1664       inside event oriented programming framework such as AnyEvent or
1665       IO::Async in the following way:
1666
1667       1. Create a disconnected Net::OpenSSH object:
1668               my $ssh = Net::OpenSSH->new($host, async => 1, ...);
1669
1670       2. Let the object connect to the remote host:
1671           Use a timer to call the "wait_for_master" method in async mode
1672           repeatedly until it returns a true value indicating success.
1673
1674           Also, the object error state needs to be checked after every call
1675           in order to detect failed connections. For instance:
1676
1677             my $ssh = Net::OpenSSH->new(..., async => 1);
1678             my $w;
1679             $w = AE::timer 0.1, 0.1, sub {
1680               if ($ssh->wait_for_master(1)) {
1681                 # the connection has been established!
1682                 # remote commands can be run now
1683                 undef $w;
1684                 on_ssh_success(...);
1685               }
1686               elsif ($ssh->error) {
1687                 # connection can not be established
1688                 undef $w;
1689                 on_ssh_failure(...);
1690               }
1691             }
1692
1693       3. Use the event framework to launch the remote processes:
1694           Call Net::OpenSSH "make_remote_command" to construct commands which
1695           can be run using the framework regular facilities for launching
1696           external commands.
1697
1698           Error checking should also be performed at this point because the
1699           SSH connection could be broken.
1700
1701           For instance:
1702
1703             if (defined(my $cmd = $ssh->make_remote_command(echo => 'hello!')) {
1704               AnyEvent::Util::run_cmd($cmd, %run_cmd_opts);
1705             }
1706             else {
1707               # something went wrong!
1708             }
1709
1710           Alternatively, any of the "open*" methods provided by Net::OpenSSH
1711           could also be used to launch remote commands.
1712
1713       4. When finished, disconnect asynchronously
1714           After initiating an asynchronous disconnect with disconnect(1),
1715           repeatedly call "wait_for_master" until you get a defined but false
1716           value:
1717
1718             $ssh->disconnect(1);
1719
1720             my $w; $w = AE::timer 0.1, 0.1, sub {
1721               my $res = $ssh->wait_for_master(1);
1722
1723               if (defined $res && !$res) {
1724                 undef $w;
1725                 undef $ssh;
1726               }
1727             };
1728
1729           Be careful not to let the $ssh object go out of scope until the
1730           disconnection has finished, otherwise its destructor will wait and
1731           block your program until the disconnection has completed.
1732
1733   Other modules
1734       CPAN contains several modules that rely on SSH to perform their duties
1735       as for example IPC::PerlSSH or GRID::Machine.
1736
1737       Often, it is possible to instruct them to go through a Net::OpenSSH
1738       multiplexed connection employing some available constructor option. For
1739       instance:
1740
1741         use Net::OpenSSH;
1742         use IPC::PerlIPC;
1743         my $ssh = Net::OpenSSH->new(...);
1744         $ssh->error and die "unable to connect to remote host: " . $ssh->error;
1745         my @cmd = $ssh->make_remote_command('/usr/bin/perl');
1746         my $ipc = IPC::PerlSSH->new(Command => \@cmd);
1747         my @r = $ipc->eval('...');
1748
1749       or...
1750
1751         use GRID::Machine;
1752         ...
1753         my @cmd = $ssh->make_remote_command('/usr/bin/perl');
1754         my $grid = GRID::Machine->new(command => \@cmd);
1755         my $r = $grid->eval('print "hello world!\n"');
1756
1757       In other cases, some kind of plugin mechanism is provided by the 3rd
1758       party modules to allow for different transports. The method "open2" may
1759       be used to create a pair of pipes for transport in these cases.
1760

TROUBLESHOOTING

1762       Usually, Net::OpenSSH works out of the box, but when it fails, some
1763       users have a hard time finding the cause of the problem. This mini
1764       troubleshooting guide should help you to find and solve it.
1765
1766       1 - check the error message
1767           Add in your script, after the Net::OpenSSH constructor call, an
1768           error check:
1769
1770             $ssh = Net::OpenSSH->new(...);
1771             $ssh->error and die "SSH connection failed: " . $ssh->error;
1772
1773           The error message will tell what has gone wrong.
1774
1775       2 - Check the connection parameters
1776           Believe it or not, passing bad parameters to Net::OpenSSH turns to
1777           be one of the top causes of failures so check that you are using
1778           the right parameters.
1779
1780           Specifically, if you are obtaining them from the outside, ensure
1781           that they don't have extra spaces or new lines attached (do you
1782           need to "chomp"?).
1783
1784           Passwords and URIs may contain "$" or "@" characters. If you have
1785           then hardcoded in your script, check that those are quoted properly
1786           (and BTW, use "strict").
1787
1788       3 - OpenSSH version
1789           Ensure that you have a version of "ssh" recent enough:
1790
1791             $ ssh -V
1792             OpenSSH_5.1p1 Debian-5, OpenSSL 0.9.8g 19 Oct 2007
1793
1794           OpenSSH version 4.1 was the first to support the multiplexing
1795           feature and is the minimal required by the module to work. I advise
1796           you to use the latest OpenSSH (currently 7.5).
1797
1798           The "ssh_cmd" constructor option lets you select the "ssh" binary
1799           to use. For instance:
1800
1801             $ssh = Net::OpenSSH->new($host,
1802                                      ssh_cmd => "/opt/OpenSSH/5.8/bin/ssh")
1803
1804           Some hardware vendors (e.g. Sun, err... Oracle) include custom
1805           versions of OpenSSH bundled with the operating system. In
1806           principle, Net::OpenSSH should work with these SSH clients as long
1807           as they are derived from some version of OpenSSH recent enough.
1808           Anyway, my advise is to use the real OpenSSH software if you can!
1809
1810       4 - run ssh from the command line
1811           Check you can connect to the remote host using the same parameters
1812           you are passing to Net::OpenSSH. In particular, ensure that you are
1813           running "ssh" as the same local user.
1814
1815           If you are running your script from a web server, the user would
1816           probably be "www", "apache" or something alike.
1817
1818           Common problems are:
1819
1820           ā€¢   Remote host public key not present in known_hosts file.
1821
1822               The SSH protocol uses public keys to identify the remote hosts
1823               so that they can not be supplanted by some malicious third
1824               parties.
1825
1826               For OpenSSH, usually the server public key is stored in
1827               "/etc/ssh/ssh_host_dsa_key.pub" or in
1828               "/etc/ssh/ssh_host_rsa_key.pub" and that key should be copied
1829               into the "~/.ssh/known_hosts" file in the local machine (other
1830               SSH implementations may use other file locations).
1831
1832               Maintaining the server keys when several hosts and clients are
1833               involved may be somewhat inconvenient, so most SSH clients, by
1834               default, when a new connection is established to a host whose
1835               key is not in the "known_hosts" file, show the key and ask the
1836               user if he wants the key copied there.
1837
1838           ā€¢   Wrong remote host public key in known_hosts file.
1839
1840               This is another common problem that happens when some server is
1841               replaced or reinstalled from scratch and its public key changes
1842               becoming different to that installed on the "known_hosts" file.
1843
1844               The easiest way to solve that problem is to remove the old key
1845               from the "known_hosts" file by hand using any editor and then
1846               to connect to the server replying "yes" when asked to save the
1847               new key.
1848
1849           ā€¢   Wrong permissions for the "~/.ssh" directory or its contents.
1850
1851               OpenSSH client performs several checks on the access
1852               permissions of the "~/.ssh" directory and its contents and
1853               refuses to use them when misconfigured. See the FILES section
1854               from the ssh(1) man page.
1855
1856           ā€¢   Incorrect settings for password or public key authentication.
1857
1858               Check that you are using the right password or that the user
1859               public key is correctly installed on the server.
1860
1861       5 - security checks on the multiplexing socket
1862           Net::OpenSSH performs some security checks on the directory where
1863           the multiplexing socket is going to be placed to ensure that it can
1864           not be accessed by other users.
1865
1866           The default location for the multiplexing socket is under
1867           "~/.libnet-openssh-perl". It can be changed using the "ctl_dir" and
1868           "ctl_path" constructor arguments.
1869
1870           The requirements for that directory and all its parents are:
1871
1872           ā€¢   They have to be owned by the user executing the script or by
1873               root
1874
1875           ā€¢   Their permission masks must be 0755 or more restrictive, so
1876               nobody else has permissions to perform write operations on
1877               them.
1878
1879           The constructor option "strict_mode" disables these security
1880           checks, but you should not use it unless you understand its
1881           implications.
1882
1883       6 - file system must support sockets
1884           Some file systems (as for instance FAT or AFS) do not support
1885           placing sockets inside them.
1886
1887           Ensure that the "ctl_dir" path does not lay into one of those file
1888           systems.
1889

DEBUGGING

1891       Debugging of Net::OpenSSH internals is controlled through the variable
1892       $Net::OpenSSH::debug. Every bit of this variable activates debugging of
1893       some subsystem as follows:
1894
1895       bit 1 - errors
1896           Dumps changes on the internal object attribute where errors are
1897           stored.
1898
1899       bit 2 - ctl_path
1900           Dumps information about ctl_path calculation and the tests
1901           performed on that directory in order to decide if it is secure to
1902           place the multiplexing socket inside.
1903
1904       bit 4 - connecting
1905           Dumps information about the establishment of new master
1906           connections.
1907
1908       bit 8 - commands and arguments
1909           Dumps the command and arguments for every system/exec call.
1910
1911       bit 16 - command execution
1912           Dumps information about the progress of command execution.
1913
1914       bit 32 - destruction
1915           Dumps information about the destruction of Net::OpenSSH objects and
1916           the termination of the SSH master processes.
1917
1918       bit 64 - IO loop
1919           Dumps information about the progress of the IO loop on capture
1920           operations.
1921
1922       bit 128 - IO hexdumps
1923           Generates hexdumps of the information that travels through the SSH
1924           streams inside capture operations.
1925
1926       bit 512 - OS tracing of the master process
1927           Use the module Net::OpenSSH::OSTracer to trace the SSH master
1928           process at the OS level.
1929
1930       For instance, in order to activate all the debugging flags, you can
1931       use:
1932
1933         $Net::OpenSSH::debug = ~0;
1934
1935       Note that the meaning of the flags and the information generated is
1936       only intended for debugging of the module and may change without notice
1937       between releases.
1938
1939       If you are using password authentication, enabling debugging for
1940       IO::Tty may also show interesting information:
1941
1942           $IO::Tty::DEBUG = 1;
1943
1944       Finally, by default debugging output is sent to "STDERR". You can
1945       override it pointing $Net::OpenSSH::debug_fh to a different file
1946       handle. For instance:
1947
1948         BEGIN {
1949           open my $out, '>', '/tmp/debug.txt' or warn $!;
1950           $Net::OpenSSH::debug_fh = $out;
1951           $Net::OpenSSH::debug = -1;
1952         }
1953

SECURITY

1955       Q: Is this module secure?
1956
1957       A: Well, it tries to be!
1958
1959       From a security standpoint the aim of this module is to be as secure as
1960       OpenSSH, your operating system, your shell and in general your
1961       environment allow it to be.
1962
1963       It does not take any shortcut just to make your life easier if that
1964       means lowering the security level (for instance, disabling
1965       "StrictHostKeyChecking" by default).
1966
1967       In code supporting features that are not just proxied to OpenSSH, the
1968       module tries to keep the same standards of security as OpenSSH (for
1969       instance, checking directory and file permissions when placing the
1970       multiplexing socket).
1971
1972       On the other hand, and keeping with OpenSSH philosophy, the module lets
1973       you disable most (all?) of those security measures. But just because it
1974       lets you do it it doesn't mean it is a good idea to do so!!!
1975
1976       If you are a novice programmer or SSH user, and googling you have just
1977       found some flag that you don't understand but that seems to magically
1978       solve your connection problems... well, believe me, it is probably a
1979       bad idea to use it. Ask somebody how really knows first!
1980
1981       Just to make thinks clear, if your code contains any of the keywords
1982       from the (non-exclusive) list below and you don't know why, you are
1983       probably wrecking the security of the SSH protocol:
1984
1985         strict_mode
1986         StrictHostKeyChecking
1987         UserKnownHostsFile
1988
1989       Other considerations related to security you may like to know are as
1990       follows:
1991
1992       Taint mode
1993           The module supports working in taint mode.
1994
1995           If you are in an exposed environment, you should probably enable it
1996           for your script in order to catch any unchecked command for being
1997           executed in the remote side.
1998
1999       Web environments
2000           It is a bad idea to establish SSH connections from your webserver
2001           because if it becomes compromised in any way, the attacker would be
2002           able to use the credentials from your script to connect to the
2003           remote host and do anything he wishes there.
2004
2005       Command quoting
2006           The module can quote commands and arguments for you in a flexible
2007           and powerful way.
2008
2009           This is a feature you should use as it reduces the possibility of
2010           some attacker being able to inject and run arbitrary commands on
2011           the remote machine (and even for scripts that are not exposed it is
2012           always advisable to enable argument quoting).
2013
2014           Having said that, take into consideration that argument-quoting is
2015           just a hack to emulate the invoke-without-a-shell feature of Perl
2016           builtins such as "system" and alike. There may be bugs(*) on the
2017           quoting code, your particular shell may have different quoting
2018           rules with unhandled corner cases or whatever. If your script is
2019           exposed to the outside, you should check your inputs and restrict
2020           what you accept as valid.
2021
2022           [* even if this is one of the parts of the module more intensively
2023           tested!]
2024
2025       Shellshock
2026           (see Shellshock
2027           <http://en.wikipedia.org/wiki/Shellshock_%28software_bug%29>)
2028
2029           When executing local commands, the module always avoids calling the
2030           shell so in this way it is not affected by Shellshock.
2031
2032           Unfortunately, some commands ("scp", "rsync" and "ssh" when the
2033           "ProxyCommand" option is used) invoke other commands under the hood
2034           using the user shell. That opens the door to local Shellshock
2035           exploitation.
2036
2037           On the remote side invocation of the shell is unavoidable due to
2038           the protocol design.
2039
2040           By default, SSH does not forward environment variables but some
2041           Linux distributions explicitly change the default OpenSSH
2042           configuration to enable forwarding and acceptance of some specific
2043           ones (for instance "LANG" and "LC_*" on Debian and derivatives,
2044           Fedora does alike) and this also opens the door to Shellshock
2045           exploitation.
2046
2047           Note that the shell used to invoke commands is not "/bin/sh" but
2048           the user shell as configured in "/etc/passwd", PAM or whatever
2049           authentication subsystem is used by the local or remote operating
2050           system. Debian users, don't think you are not affected because your
2051           "/bin/sh" points to "dash"!
2052

FAQ

2054       Frequent questions about the module:
2055
2056       Connecting to switches, routers, etc.
2057           Q: I can not get the method "system", "capture", etc., to work when
2058           connecting to some router, switch, etc. What I am doing wrong?
2059
2060           A: Roughly, the SSH protocol allows for two modes of operation:
2061           command mode and interactive mode.
2062
2063           Command mode is designed to run single commands on the remote host.
2064           It opens a SSH channel between both hosts, asks the remote computer
2065           to run some given command and when it finishes, the channel is
2066           closed. It is what you get, for instance, when you run something
2067           as...
2068
2069             $ ssh my.unix.box cat foo.txt
2070
2071           ... and it is also the way Net::OpenSSH runs commands on the remote
2072           host.
2073
2074           Interactive mode launches a shell on the remote hosts with its
2075           stdio streams redirected to the local ones so that the user can
2076           transparently interact with it.
2077
2078           Some devices (as probably the one you are using) do not run an
2079           standard, general purpose shell (e.g. "bash", "csh" or "ksh") but
2080           some custom program specially targeted and limited to the task of
2081           configuring the device.
2082
2083           Usually, the SSH server running on these devices does not support
2084           command mode. It unconditionally attaches the restricted shell to
2085           any incoming SSH connection and waits for the user to enter
2086           commands through the redirected stdin stream.
2087
2088           The only way to work-around this limitation is to make your script
2089           talk to the restricted shell (1-open a new SSH session, 2-wait for
2090           the shell prompt, 3-send a command, 4-read the output until you get
2091           to the shell prompt again, repeat from 3). The best tool for this
2092           task is probably Expect, used alone or combined with Net::OpenSSH
2093           (see "Expect").
2094
2095           There are some devices that support command mode but that only
2096           accept one command per connection. In that cases, using Expect is
2097           also probably the best option.
2098
2099           Nowadays, there is a new player, Net::CLI::Interact that may be
2100           more suitable than Expect, and Net::Appliance::Session for working
2101           specifically with network devices.
2102
2103       Connection fails
2104           Q: I am unable to make the module connect to the remote host...
2105
2106           A: Have you read the troubleshooting section? (see
2107           "TROUBLESHOOTING").
2108
2109       Disable StrictHostKeyChecking
2110           Q: Why is "ssh" not run with "StrictHostKeyChecking=no"?
2111
2112           A: Using "StrictHostKeyChecking=no" relaxes the default security
2113           level of SSH and it will be relatively easy to end with a
2114           misconfigured SSH (for instance, when "known_hosts" is unwritable)
2115           that could be forged to connect to a bad host in order to perform
2116           man-in-the-middle attacks, etc.
2117
2118           I advice you to do not use that option unless you fully understand
2119           its implications from a security point of view.
2120
2121           If you want to use it anyway, past it to the constructor:
2122
2123             $ssh = Net::OpenSSH->new($host,
2124                      master_opts => [-o => "StrictHostKeyChecking=no"],
2125                      ...);
2126
2127       child process STDIN/STDOUT/STDERR is not a real system file handle
2128           Q: Calls to "system", "capture", etc. fail with the previous error,
2129           what's happening?
2130
2131           A: The reported stdio stream is closed or is not attached to a real
2132           file handle (e.g. it is a tied handle). Redirect it to "/dev/null"
2133           or to a real file:
2134
2135             my $out = $ssh->capture({stdin_discard => 1, stderr_to_stdout => 1},
2136                                     $cmd);
2137
2138           See also the mod_perl entry above.
2139
2140       Solaris (and AIX and probably others)
2141           Q: I was trying Net::OpenSSH on Solaris and seem to be running into
2142           an issue...
2143
2144           A: The SSH client bundled with Solaris is an early fork of OpenSSH
2145           that does not provide the multiplexing functionality required by
2146           Net::OpenSSH. You will have to install the OpenSSH client.
2147
2148           Precompiled packages are available from Sun Freeware
2149           (<http://www.sunfreeware.com>). There, select your OS version an
2150           CPU architecture, download the OpenSSH package and its dependencies
2151           and install them. Note that you do not need to configure Solaris to
2152           use the OpenSSH server "sshd".
2153
2154           Ensure that OpenSSH client is in your path before the system "ssh"
2155           or alternatively, you can hardcode the full path into your scripts
2156           as follows:
2157
2158             $ssh = Net::OpenSSH->new($host,
2159                                      ssh_cmd => '/usr/local/bin/ssh');
2160
2161           AIX and probably some other unixen, also bundle SSH clients lacking
2162           the multiplexing functionality and require installation of the real
2163           OpenSSH.
2164
2165       Can not change working directory
2166           Q: I want to run some command inside a given remote directory but I
2167           am unable to change the working directory. For instance:
2168
2169             $ssh->system('cd /home/foo/bin');
2170             $ssh->systen('ls');
2171
2172           does not list the contents of "/home/foo/bin".
2173
2174           What am I doing wrong?
2175
2176           A: Net::OpenSSH (and, for that matter, all the SSH modules
2177           available from CPAN but Net::SSH::Expect) run every command in a
2178           new session so most shell builtins that are run for its side
2179           effects become useless (e.g. "cd", "export", "ulimit", "umask",
2180           etc., usually, you can list them running "help" from the shell).
2181
2182           A work around is to combine several commands in one, for instance:
2183
2184             $ssh->system('cd /home/foo/bin && ls');
2185
2186           Note the use of the shell "&&" operator instead of ";" in order to
2187           abort the command as soon as any of the subcommands fail.
2188
2189           Also, several commands can be combined into one while still using
2190           the multi-argument quoting feature as follows:
2191
2192             $ssh->system(@cmd1, \\'&&', @cmd2, \\'&&', @cmd3, ...);
2193
2194       Running detached remote processes
2195           Q: I need to be able to ssh into several machines from my script,
2196           launch a process to run in the background there, and then return
2197           immediately while the remote programs keep running...
2198
2199           A: If the remote systems run some Unix/Linux variant, the right
2200           approach is to use nohup(1) that will disconnect the remote process
2201           from the stdio streams and to ask the shell to run the command on
2202           the background. For instance:
2203
2204             $ssh->system("nohup $long_running_command &");
2205
2206           Also, it may be possible to demonize the remote program. If it is
2207           written in Perl you can use App::Daemon for that (actually, there
2208           are several CPAN modules that provided that kind of functionality).
2209
2210           In any case, note that you should not use "spawn" for that.
2211
2212       MaxSessions server limit reached
2213           Q: I created an $ssh object and then fork a lot children processes
2214           which use this object. When the children number is bigger than
2215           "MaxSessions" as defined in sshd configuration (defaults to 10),
2216           trying to fork new remote commands will prompt the user for the
2217           password.
2218
2219           A: When the slave SSH client gets a response from the remote
2220           servers saying that the maximum number of sessions for the current
2221           connection has been reached, it fall backs to open a new direct
2222           connection without going through the multiplexing socket.
2223
2224           To stop that for happening, the following hack can be used:
2225
2226             $ssh = Net::OpenSSH->new(host,
2227                 default_ssh_opts => ['-oConnectionAttempts=0'],
2228                 ...);
2229
2230       Running remote commands with sudo
2231           Q: How can I run remote commands using "sudo" to become root first?
2232
2233           A: The simplest way is to tell "sudo" to read the password from
2234           stdin with the "-S" flag and to do not use cached credentials with
2235           the "-k" flag. You may also like to use the "-p" flag to tell
2236           "sudo" to print an empty prompt. For instance:
2237
2238             my @out = $ssh->capture({ stdin_data => "$sudo_passwd\n" },
2239                                     'sudo', '-Sk',
2240                                     '-p', '',
2241                                     '--',
2242                                     @cmd);
2243
2244           If the version of sudo installed on the remote host does not
2245           support the "-S" flag (it tells sudo to read the password from its
2246           STDIN stream), you can do it as follows:
2247
2248             my @out = $ssh->capture({ tty => 1,
2249                                       stdin_data => "$sudo_passwd\n" },
2250                                     'sudo', '-k',
2251                                     '-p', '',
2252                                     '--',
2253                                     @cmd);
2254
2255           This may generate an spurious and harmless warning from the SSH
2256           master connection (because we are requesting allocation of a tty on
2257           the remote side and locally we are attaching it to a regular pair
2258           of pipes).
2259
2260           If for whatever reason the methods described above fail, you can
2261           always revert to using Expect to talk to the remote "sudo". See the
2262           "examples/expect.pl" script from this module distribution.
2263

SEE ALSO

2265       OpenSSH client documentation ssh(1), ssh_config(5), the project web
2266       <http://www.openssh.org> and its FAQ
2267       <http://www.openbsd.org/openssh/faq.html>. scp(1) and rsync(1). The
2268       OpenSSH Wikibook <http://en.wikibooks.org/wiki/OpenSSH>.
2269
2270       Net::OpenSSH::Gateway for detailed instruction about how to get this
2271       module to connect to hosts through proxies and other SSH gateway
2272       servers.
2273
2274       Core perl documentation perlipc, "open" in perlfunc, "waitpid" in
2275       perlfunc.
2276
2277       IO::Pty to known how to use the pseudo tty objects returned by several
2278       methods on this package.
2279
2280       Net::SFTP::Foreign provides a compatible SFTP implementation.
2281
2282       Expect can be used to interact with commands run through this module on
2283       the remote machine (see also the "expect.pl" and <autosudo.pl> scripts
2284       in the examples directory).
2285
2286       SSH::OpenSSH::Parallel is an advanced scheduler that allows one to run
2287       commands in remote hosts in parallel. It is obviously based on
2288       Net::OpenSSH.
2289
2290       SSH::Batch allows one to run remote commands in parallel in a cluster.
2291       It is build on top on "Net::OpenSSH" also.
2292
2293       Other Perl SSH clients: Net::SSH::Perl, Net::SSH2, Net::SSH,
2294       Net::SSH::Expect, Net::SCP, Net::SSH::Mechanize.
2295
2296       Net::OpenSSH::Compat is a package offering a set of compatibility
2297       layers for other SSH modules on top of Net::OpenSSH.
2298
2299       IPC::PerlSSH, GRID::Machine allow execution of Perl code in remote
2300       machines through SSH.
2301
2302       SSH::RPC implements an RPC mechanism on top of SSH using Net::OpenSSH
2303       to handle the connections.
2304
2305       Net::CLI::Interact allows one to interact with remote shells and other
2306       services. It is specially suited for interaction with network
2307       equipment. The phrasebook approach it uses is very clever. You may also
2308       like to check the other modules <https://metacpan.org/author/OLIVER>
2309       from its author, Oliver Gorwits.
2310

BUGS AND SUPPORT

2312   Experimental features
2313       Support for the "restart" feature is experimental.
2314
2315       Object::Remote integration is highly experimental.
2316
2317       Support for tunnels targeting Unix sockets is highly experimental.
2318
2319       Support for the "setpgrp" feature is highly experimental.
2320
2321       Support for the gateway feature is highly experimental and mostly
2322       stalled.
2323
2324       Support for taint mode is experimental.
2325
2326   Known issues
2327       Net::OpenSSH does not work on Windows. OpenSSH multiplexing feature
2328       requires passing file handles through sockets, something that is not
2329       supported by any version of Windows.
2330
2331       It does not work on VMS either... well, probably, it does not work on
2332       anything not resembling a modern Linux/Unix OS.
2333
2334       Old versions of OpenSSH "ssh" may leave stdio streams in non-blocking
2335       mode. That can result on failures when writing to "STDOUT" or "STDERR"
2336       after using the module. In order to work-around this issue, Perl
2337       "fcntl" in perlfunc can be used to unset the non-blocking flag:
2338
2339         use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
2340         my $flags = fcntl(STDOUT, F_GETFL, 0);
2341         fcntl(STDOUT, F_SETFL, $flags & ~O_NONBLOCK);
2342
2343   Reporting bugs and asking for help
2344       To report bugs send an email to the address that appear below or use
2345       the CPAN bug tracking system at <http://rt.cpan.org>.
2346
2347       Post questions related to how to use the module in PerlMonks
2348       <http://perlmonks.org/>, you will probably get faster responses than if
2349       you address me directly and I visit PerlMonks quite often, so I will
2350       see your question anyway.
2351
2352   Commercial support
2353       Commercial support, professional services and custom software
2354       development around this module are available through my current
2355       company. Drop me an email with a rough description of your requirements
2356       and we will get back to you ASAP.
2357
2358   My wishlist
2359       If you like this module and you are feeling generous, take a look at my
2360       Amazon Wish List: <http://amzn.com/w/1WU1P6IR5QZ42>.
2361
2362       Also consider contributing to the OpenSSH project this module builds
2363       upon: <http://www.openssh.org/donations.html>.
2364

TODO

2366       - Tests for "scp_*", "rsync_*" and "sftp" methods
2367
2368       - Make "pipe_in" and "pipe_out" methods "open_ex" based
2369
2370       - "auto_discard_streams" feature for mod_perl2 and similar environments
2371
2372       - Refactor open_ex support for multiple commands, maybe just keeping
2373         tunnel, ssh and raw
2374
2375       Send your feature requests, ideas or any feedback, please!
2376

CONTRIBUTING CODE

2378       The source code of this module is hosted at GitHub:
2379       <http://github.com/salva/p5-Net-OpenSSH>.
2380
2381       Code contributions to the module are welcome but you should obey the
2382       following rules:
2383
2384       Only Perl 5.8.4 required
2385           Yes, that's pretty old, but Net::OpenSSH is intended to be also
2386           used by system administrators that sometimes have to struggle with
2387           old systems. The reason to pick 5.8.4 is that it has been the
2388           default perl on Solaris for a long time.
2389
2390       Avoid the "All the world's a Linux PC" syndrome
2391           The module should work on any (barely) sane Unix or Linux operating
2392           system. Specially, it should not be assumed that the over-featured
2393           GNU utilities and toolchain are available.
2394
2395       Dependencies are optional
2396           In order to make the module very easy to install, no mandatory
2397           dependencies on other CPAN modules are allowed.
2398
2399           Optional modules, that are loaded only on demand, are acceptable
2400           when they are used for adding new functionality (as it is done, for
2401           instance, with IO::Pty).
2402
2403           Glue code for integration with 3rd party modules is also allowed
2404           (as it is done with Expect).
2405
2406           Usage of language extension modules and alike is not acceptable.
2407
2408       Tests should be lax
2409           We don't want false negatives when testing. In case of doubt tests
2410           should succeed.
2411
2412           Also, in case of tests invoking some external program, it should be
2413           checked that the external program is available and that it works as
2414           expected or otherwise skip those tests.
2415
2416       Backward compatibility
2417           Nowadays Net::OpenSSH is quite stable and there are lots of scripts
2418           out there using it that we don't want to break, so, keeping the API
2419           backward compatible is a top priority.
2420
2421           Probably only security issues could now justify a backward
2422           incompatible change.
2423
2424       Follow my coding style
2425           Look at the rest of the code.
2426
2427           I let Emacs do the formatting for me using cperl-mode PerlStyle.
2428
2429       Talk to me
2430           Before making a large change or implementing a new feature get in
2431           touch with me.
2432
2433           I may have my own ideas about how things should be done. It is
2434           better if you know them before hand, otherwise, you risk getting
2435           your patch rejected.
2436
2437       Well, actually you should know that I am quite good at rejecting
2438       patches but it is not my fault!
2439
2440       Most of the patches I get are broken in some way: they don't follow the
2441       main module principles, sometimes the author didn't get the full
2442       picture and solved the issue in a short-sighted way, etc.
2443
2444       In any case, you should not be discouraged to contribute. Even if your
2445       patch is not applied directly, seeing how it solves your requirements
2446       or, in the case of bugs, the underlying problem analysis may be very
2447       useful and help me to do it... my way.
2448
2449       I always welcome documentation corrections and improvements.
2450
2452       Copyright (C) 2008-2022 by Salvador FandiƱo (sfandino@yahoo.com)
2453
2454       This library is free software; you can redistribute it and/or modify it
2455       under the same terms as Perl itself, either Perl version 5.10.0 or, at
2456       your option, any later version of Perl 5 you may have available.
2457
2458
2459
2460perl v5.36.0                      2022-07-22                   Net::OpenSSH(3)
Impressum