1Net::OpenSSH(3) User Contributed Perl Documentation Net::OpenSSH(3)
2
3
4
6 Net::OpenSSH - Perl SSH client package implemented on top of OpenSSH
7
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
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
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 Enables forwarding of the authentication agent.
309
310 This option can not be used when passing a passphrase (via
311 "passphrase") to unlock the login private key.
312
313 Note that Net::OpenSSH will not run "ssh-agent" for you. This
314 has to be done ahead of time and the environment variable
315 "SSH_AUTH_SOCK" set pointing to the proper place.
316
317 forward_X11 => 1
318 Enables forwarding of the X11 protocol
319
320 default_stdin_fh => $fh
321 default_stdout_fh => $fh
322 default_stderr_fh => $fh
323 Default I/O streams for "open_ex" and derived methods
324 (currently, that means any method but "pipe_in" and "pipe_out"
325 and I plan to remove those exceptions soon!).
326
327 For instance:
328
329 open my $stderr_fh, '>>', '/tmp/$host.err' or die ...;
330 open my $stdout_fh, '>>', '/tmp/$host.log' or die ...;
331
332 my $ssh = Net::OpenSSH->new($host, default_stderr_fh => $stderr_fh,
333 default_stdout_fh => $stdout_fh);
334 $ssh->error and die "SSH connection failed: " . $ssh->error;
335
336 $ssh->scp_put("/foo/bar*", "/tmp")
337 or die "scp failed: " . $ssh->error;
338
339 default_stdin_file = $fn
340 default_stdout_file = $fn
341 default_stderr_file = $fn
342 Opens the given file names and use them as the defaults.
343
344 master_stdout_fh => $fh
345 master_stderr_fh => $fh
346 Redirect corresponding stdio streams of the master SSH process
347 to given filehandles.
348
349 master_stdout_discard => $bool
350 master_stderr_discard => $bool
351 Discard corresponding stdio streams.
352
353 expand_vars => $bool
354 Activates variable expansion inside command arguments and file
355 paths.
356
357 See "Variable expansion" below.
358
359 vars => \%vars
360 Initial set of variables.
361
362 external_master => 1
363 Instead of launching a new OpenSSH client in master mode, the
364 module tries to reuse an already existent one. "ctl_path" must
365 also be passed when this option is set. See also
366 "get_ctl_path".
367
368 Example:
369
370 $ssh = Net::OpenSSH->new('foo', external_master => 1, ctl_path = $path);
371
372 When "external_master" is set, the hostname argument becomes
373 optional (0.0.0.0 is passed to OpenSSH which does not use it at
374 all).
375
376 default_encoding => $encoding
377 default_stream_encoding => $encoding
378 default_argument_encoding => $encoding
379 Set default encodings. See "Data encoding".
380
381 password_prompt => $string
382 password_prompt => $re
383 By default, when using password authentication, the module
384 expects the remote side to send a password prompt matching
385 "/[?:]/".
386
387 This option can be used to override that default for the rare
388 cases when a different prompt is used.
389
390 Examples:
391
392 password_prompt => ']'; # no need to escape ']'
393 password_prompt => qr/[:?>]/;
394
395 login_handler => \&custom_login_handler
396 Some remote SSH server may require a custom
397 login/authentication interaction not natively supported by
398 Net::OpenSSH. In that cases, you can use this option to replace
399 the default login logic.
400
401 The callback will be invoked repeatedly as
402 "custom_login_handler($ssh, $pty, $data)" where $ssh is the
403 current Net::OpenSSH object, "pty" a IO::Pty object attached to
404 the slave "ssh" process tty and $data a reference to an scalar
405 you can use at will.
406
407 The login handler must return 1 after the login process has
408 completed successfully or 0 in case it still needs to do
409 something else. If some error happens, it must die.
410
411 Note, that blocking operations should not be performed inside
412 the login handler (at least if you want the "async" and
413 "timeout" features to work).
414
415 See also the sample script "login_handler.pl" in the "examples"
416 directory.
417
418 Usage of this option is incompatible with the "password" and
419 "passphrase" options, you will have to handle password or
420 passphrases from the custom handler yourself.
421
422 master_setpgrp => 1
423 When this option is set, the master process is run as a
424 different process group. As a consequence it will not die when
425 the user presses Ctrl-C at the terminal.
426
427 In order to allow the master SSH process to request any
428 information from the user, the module may set it as the
429 terminal controlling process while the connection is
430 established (using "tcsetpgrp" in POSIX). Afterwards, the
431 terminal controlling process is reset.
432
433 This feature is highly experimental. Report any problems you
434 may find, please.
435
436 master_pty_force => 1
437 By default, Net::OpenSSH attaches the master SSH process to a
438 pty only when some kind of interactive authentication is
439 requested. If this flag is set a pty will be attached always.
440
441 That allows to get better diagnostics for some kind of errors
442 (as for instance, bad host keys) and also allows to retrieve
443 the pty log using get_master_pty_log.
444
445 $ssh->error
446 Returns the error condition for the last performed operation.
447
448 The returned value is a dualvar as $! (see "$!" in perlvar) that
449 renders an informative message when used in string context or an
450 error number in numeric context (error codes appear in
451 Net::OpenSSH::Constants).
452
453 $ssh->get_master_pty_log
454 In order to handle password authentication or entering the
455 passphrase for a private key, Net::OpenSSH may run the master SSH
456 process attached to a pty.
457
458 In that case and after a constructor call returns a connection
459 failure error, this method can be called to retrieve the output
460 captured at the pty (the log is discarded when the connection is
461 established successfully).
462
463 Any data consumed from the pty by custom login handlers will be
464 missing from the the returned log.
465
466 $ssh->get_user
467 $ssh->get_host
468 $ssh->get_port
469 Return the corresponding SSH login parameters.
470
471 $ssh->get_ctl_path
472 Returns the path to the socket where the OpenSSH master process
473 listens for new multiplexed connections.
474
475 ($in, $out, $err, $pid) = $ssh->open_ex(\%opts, @cmd)
476 Note: this is a low level method which, probably, you do not need
477 to use!
478
479 That method starts the command @cmd on the remote machine creating
480 new pipes for the IO channels as specified on the %opts hash.
481
482 If @cmd is omitted, the remote user shell is run.
483
484 Returns four values, the first three ($in, $out and $err)
485 correspond to the local side of the pipes created (they can be
486 undef) and the fourth ($pid) to the PID of the new SSH slave
487 process. An empty list is returned on failure.
488
489 Note that "waitpid" has to be used afterwards to reap the slave SSH
490 process.
491
492 Accepted options:
493
494 stdin_pipe => 1
495 Creates a new pipe and connects the reading side to the stdin
496 stream of the remote process. The writing side is returned as
497 the first value ($in).
498
499 stdin_pty => 1
500 Similar to "stdin_pipe", but instead of a regular pipe it uses
501 a pseudo-tty (pty).
502
503 Note that on some operating systems (e.g. HP-UX, AIX), ttys are
504 not reliable. They can overflow when large chunks are written
505 or when data is written faster than it is read.
506
507 stdin_fh => $fh
508 Duplicates $fh and uses it as the stdin stream of the remote
509 process.
510
511 stdin_file => $filename
512 stdin_file => \@open_args
513 Opens the file of the given name for reading and uses it as the
514 remote process stdin stream.
515
516 If an array reference is passed its contents are used as the
517 arguments for the underlying open call. For instance:
518
519 $ssh->system({stdin_file => ['-|', 'gzip -c -d file.gz']}, $rcmd);
520
521 stdin_discard => 1
522 Uses /dev/null as the remote process stdin stream.
523
524 stdout_pipe => 1
525 Creates a new pipe and connects the writing side to the stdout
526 stream of the remote process. The reading side is returned as
527 the second value ($out).
528
529 stdout_pty => 1
530 Connects the stdout stream of the remote process to the pseudo-
531 pty. This option requires "stdin_pty" to be also set.
532
533 stdout_fh => $fh
534 Duplicates $fh and uses it as the stdout stream of the remote
535 process.
536
537 stdout_file => $filename
538 stdout_file => \@open_args
539 Opens the file of the given filename and redirect stdout there.
540
541 stdout_discard => 1
542 Uses /dev/null as the remote process stdout stream.
543
544 stdinout_socket => 1
545 Creates a new socketpair, attaches the stdin an stdout streams
546 of the slave SSH process to one end and returns the other as
547 the first value ($in) and undef for the second ($out).
548
549 Example:
550
551 my ($socket, undef, undef, $pid) = $ssh->open_ex({stdinout_socket => 1},
552 '/bin/netcat $dest');
553
554 See also "open2socket".
555
556 stdinout_dpipe => $cmd
557 stdinout_dpipe => \@cmd
558 Runs the given command locally attaching its stdio streams to
559 those of the remote SSH command. Conceptually it is equivalent
560 to the dpipe(1) shell command.
561
562 stderr_pipe => 1
563 Creates a new pipe and connects the writing side to the stderr
564 stream of the remote process. The reading side is returned as
565 the third value ($err).
566
567 Example:
568
569 my $pid = $ssh->open_ex({stdinout_dpipe => 'vncviewer -stdio'},
570 x11vnc => '-inetd');
571
572 stderr_fh => $fh
573 Duplicates $fh and uses it as the stderr stream of the remote
574 process.
575
576 stderr_file => $filename
577 Opens the file of the given name and redirects stderr there.
578
579 stderr_to_stdout => 1
580 Makes stderr point to stdout.
581
582 tty => $bool
583 Tells "ssh" to allocate a pseudo-tty for the remote process. By
584 default, a tty is allocated if remote command stdin stream is
585 attached to a tty.
586
587 When this flag is set and stdin is not attached to a tty, the
588 ssh master and slave processes may generate spurious warnings
589 about failed tty operations. This is caused by a bug present in
590 older versions of OpenSSH.
591
592 close_slave_pty => 0
593 When a pseudo pty is used for the stdin stream, the slave side
594 is automatically closed on the parent process after forking the
595 ssh command.
596
597 This option disables that feature, so that the slave pty can be
598 accessed on the parent process as "$pty->slave". It will have
599 to be explicitly closed (see IO::Pty)
600
601 quote_args => $bool
602 See "Shell quoting" below.
603
604 remote_shell => $shell
605 Sets the remote shell. Allows one to change the argument
606 quoting mechanism in a per-command fashion.
607
608 This may be useful when interacting with a Windows machine
609 where argument parsing may be done at the command level in
610 custom ways.
611
612 Example:
613
614 $ssh->system({remote_shell => 'MSWin'}, echo => $line);
615 $ssh->system({remote_shell => 'MSCmd,MSWin'}, type => $file);
616
617 forward_agent => $bool
618 Enables/disables forwarding of the authentication agent.
619
620 This option can only be used when agent forwarding has been
621 previously requested on the constructor.
622
623 forward_X11 => $bool
624 Enables/disables forwarding of the X11 protocol.
625
626 This option can only be used when X11 forwarding has been
627 previously requested on the constructor.
628
629 ssh_opts => \@opts
630 List of extra options for the "ssh" command.
631
632 This feature should be used with care, as the given options are
633 not checked in any way by the module, and they could interfere
634 with it.
635
636 tunnel => $bool
637 Instead of executing a command in the remote host, this option
638 instruct Net::OpenSSH to create a TCP tunnel. The arguments
639 become the target IP and port or the remote path for an Unix
640 socket.
641
642 Example:
643
644 my ($in, $out, undef, $pid) = $ssh->open_ex({tunnel => 1}, $IP, $port);
645 my ($in, $out, undef, $pid) = $ssh->open_ex({tunnel => 1}, $socket_path);
646
647 See also "Tunnels".
648
649 subsystem => $bool
650 Request a connection to a SSH subsystem. The name of the
651 subsystem must be passed as an argument, as in the following
652 example:
653
654 my $s = $ssh->open2socket({subsystem => 1}, 'netconf');
655
656 encoding => $encoding
657 argument_encoding => $encoding
658 Set encodings. See "Data encoding".
659
660 Usage example:
661
662 # similar to IPC::Open2 open2 function:
663 my ($in_pipe, $out_pipe, undef, $pid) =
664 $ssh->open_ex( { stdin_pipe => 1,
665 stdout_pipe => 1 },
666 @cmd )
667 or die "open_ex failed: " . $ssh->error;
668 # do some IO through $in/$out
669 # ...
670 waitpid($pid);
671
672 setpgrp => 1
673 Calls "setpgrp" after forking the child process. As a result it
674 will not die when the user presses Ctrl+C at the console. See also
675 "setpgrp" in perlfunc.
676
677 Using this option without also setting "master_setpgrp" on the
678 constructor call is mostly useless as the signal will be delivered
679 to the master process and all the remote commands aborted.
680
681 This feature is experimental.
682
683 $ssh->system(\%opts, @cmd)
684 Runs the command @cmd on the remote machine.
685
686 Returns true on success, undef otherwise.
687
688 The error status is set to "OSSH_SLAVE_CMD_FAILED" when the remote
689 command exits with a non zero code (the code is available from $?,
690 see "$?" in perlvar).
691
692 Example:
693
694 $ssh->system('ls -R /')
695 or die "ls failed: " . $ssh->error";
696
697 As for "system" builtin, "SIGINT" and "SIGQUIT" signals are
698 blocked. (see "system" in perlfunc). Also, setting $SIG{CHLD} to
699 "IGNORE" or to a custom signal handler will interfere with this
700 method.
701
702 Accepted options:
703
704 stdin_data => $input
705 stdin_data => \@input
706 Sends the given data through the stdin stream to the remote
707 process.
708
709 For example, the following code creates a file on the remote
710 side:
711
712 $ssh->system({stdin_data => \@data}, "cat >/tmp/foo")
713 or die "unable to write file: " . $ssh->error;
714
715 timeout => $timeout
716 The operation is aborted after $timeout seconds elapsed without
717 network activity.
718
719 See also "Timeouts".
720
721 async => 1
722 Does not wait for the child process to exit. The PID of the new
723 process is returned.
724
725 Note that when this option is combined with "stdin_data", the
726 given data will be transferred to the remote side before
727 returning control to the caller.
728
729 See also the "spawn" method documentation below.
730
731 stdin_fh => $fh
732 stdin_discard => $bool
733 stdout_fh => $fh
734 stdout_discard => $bool
735 stderr_fh => $fh
736 stderr_discard => $bool
737 stderr_to_stdout => $bool
738 stdinout_dpipe => $cmd
739 tty => $bool
740 See the "open_ex" method documentation for an explanation of
741 these options.
742
743 stdin_keep_open => $bool
744 When "stdin_data" is given, the module closes the stdin stream
745 once all the data has been sent. Unfortunately, some SSH buggy
746 servers fail to handle this event correctly and close the
747 channel prematurely.
748
749 As a workaround, when this flag is set the stdin is left open
750 until the remote process terminates.
751
752 $ok = $ssh->test(\%opts, @cmd);
753 Runs the given command and returns its success/failure exit status
754 as 1 or 0 respectively. Returns undef when something goes wrong in
755 the SSH layer.
756
757 Error status is not set to OSSH_SLAVE_CMD_FAILED when the remote
758 command exits with a non-zero code.
759
760 By default this method discards the remote command "stdout" and
761 "sterr" streams.
762
763 Usage example:
764
765 if ($ssh->test(ps => -C => $executable)) {
766 say "$executable is running on remote machine"
767 }
768 else {
769 die "something got wrong: ". $ssh->error if $ssh->error;
770
771 say "$executable is not running on remote machine"
772 }
773
774 This method support the same set of options as "system", except
775 "async" and "tunnel".
776
777 $output = $ssh->capture(\%opts, @cmd);
778 @output = $ssh->capture(\%opts, @cmd);
779 This method is conceptually equivalent to the perl backquote
780 operator (e.g. "`ls`"): it runs the command on the remote machine
781 and captures its output.
782
783 In scalar context returns the output as a scalar. In list context
784 returns the output broken into lines (it honors $/, see "$/" in
785 perlvar).
786
787 The exit status of the remote command is returned in $?.
788
789 When an error happens while capturing (for instance, the operation
790 times out), the partial captured output will be returned. Error
791 conditions have to be explicitly checked using the "error" method.
792 For instance:
793
794 my $output = $ssh->capture({ timeout => 10 },
795 "echo hello; sleep 20; echo bye");
796 $ssh->error and
797 warn "operation didn't complete successfully: ". $ssh->error;
798 print $output;
799
800 Setting $SIG{CHLD} to a custom signal handler or to "IGNORE" will
801 interfere with this method.
802
803 Accepted options:
804
805 stdin_data => $input
806 stdin_data => \@input
807 stdin_keep_open => $bool
808 See the "system" method documentation for an explanation of
809 these options.
810
811 timeout => $timeout
812 See "Timeouts".
813
814 stdin_fh => $fh
815 stdin_discard => $bool
816 stderr_fh => $fh
817 stderr_discard => $bool
818 stderr_to_stdout => $bool
819 tty => $bool
820 See the "open_ex" method documentation for an explanation of
821 these options.
822
823 ($output, $errput) = $ssh->capture2(\%opts, @cmd)
824 captures the output sent to both stdout and stderr by @cmd on the
825 remote machine.
826
827 Setting $SIG{CHLD} to a custom signal handler or to "IGNORE" will
828 also interfere with this method.
829
830 The accepted options are:
831
832 stdin_data => $input
833 stdin_data => \@input
834 stdin_keep_open => $bool
835 See the "system" method documentation for an explanation of
836 these options.
837
838 timeout => $timeout
839 See "Timeouts".
840
841 stdin_fh => $fh
842 stdin_discard => $bool
843 tty => $bool
844 See the "open_ex" method documentation for an explanation of
845 these options.
846
847 ($in, $pid) = $ssh->pipe_in(\%opts, @cmd)
848 This method is similar to the following Perl "open" call
849
850 $pid = open $in, '|-', @cmd
851
852 but running @cmd on the remote machine (see "open" in perlfunc).
853
854 No options are currently accepted.
855
856 There is no need to perform a waitpid on the returned PID as it
857 will be done automatically by perl when $in is closed.
858
859 Example:
860
861 my ($in, $pid) = $ssh->pipe_in('cat >/tmp/fpp')
862 or die "pipe_in failed: " . $ssh->error;
863 print $in $_ for @data;
864 close $in or die "close failed";
865
866 ($out, $pid) = $ssh->pipe_out(\%opts, @cmd)
867 Reciprocal to previous method, it is equivalent to
868
869 $pid = open $out, '-|', @cmd
870
871 running @cmd on the remote machine.
872
873 No options are currently accepted.
874
875 ($in, $out, $pid) = $ssh->open2(\%opts, @cmd)
876 ($pty, $pid) = $ssh->open2pty(\%opts, @cmd)
877 ($socket, $pid) = $ssh->open2socket(\%opts, @cmd)
878 ($in, $out, $err, $pid) = $ssh->open3(\%opts, @cmd)
879 ($pty, $err, $pid) = $ssh->open3pty(\%opts, @cmd)
880 Shortcuts around "open_ex" method.
881
882 $pid = $ssh->spawn(\%opts, @_)
883 Another "open_ex" shortcut, it launches a new remote process in the
884 background and returns the PID of the local slave SSH process.
885
886 At some later point in your script, "waitpid" should be called on
887 the returned PID in order to reap the slave SSH process.
888
889 For instance, you can run some command on several hosts in parallel
890 with the following code:
891
892 my %conn = map { $_ => Net::OpenSSH->new($_, async => 1) } @hosts;
893 my @pid;
894 for my $host (@hosts) {
895 open my($fh), '>', "/tmp/out-$host.txt"
896 or die "unable to create file: $!";
897 push @pid, $conn{$host}->spawn({stdout_fh => $fh}, $cmd);
898 }
899
900 waitpid($_, 0) for @pid;
901
902 Note that "spawn" should not be used to start detached remote
903 processes that may survive the local program (see also the "FAQ"
904 about running remote processes detached).
905
906 ($socket, $pid) = $ssh->open_tunnel(\%opts, $dest_host, $port)
907 ($socket, $pid) = $ssh->open_tunnel(\%opts, $socket_path)
908 Similar to "open2socket", but instead of running a command, it
909 opens a TCP tunnel to the given address. See also "Tunnels".
910
911 $out = $ssh->capture_tunnel(\%opts, $dest_host, $port)
912 @out = $ssh->capture_tunnel(\%opts, $dest_host, $port)
913 Similar to "capture", but instead of running a command, it opens a
914 TCP tunnel.
915
916 Example:
917
918 $out = $ssh->capture_tunnel({stdin_data => join("\r\n",
919 "GET / HTTP/1.0",
920 "Host: www.perl.org",
921 "", "") },
922 'www.perl.org', 80)
923
924 See also "Tunnels".
925
926 $ssh->scp_get(\%opts, $remote1, $remote2,..., $local_dir_or_file)
927 $ssh->scp_put(\%opts, $local, $local2,..., $remote_dir_or_file)
928 These two methods are wrappers around the "scp" command that allow
929 transfers of files to/from the remote host using the existing SSH
930 master connection.
931
932 When transferring several files, the target argument must point to
933 an existing directory. If only one file is to be transferred, the
934 target argument can be a directory or a file name or can be
935 omitted. For instance:
936
937 $ssh->scp_get({glob => 1}, '/var/tmp/foo*', '/var/tmp/bar*', '/tmp');
938 $ssh->scp_put('/etc/passwd');
939
940 Both "scp_get" and "scp_put" methods return a true value when all
941 the files are transferred correctly, otherwise they return undef.
942
943 Accepted options:
944
945 quiet => 0
946 By default, "scp" is called with the quiet flag "-q" enabled in
947 order to suppress progress information. This option allows one
948 to re-enable the progress indication bar.
949
950 verbose => 1
951 Calls "scp" with the "-v" flag.
952
953 recursive => 1
954 Copies files and directories recursively.
955
956 glob => 1
957 Enables expansion of shell metacharacters in the sources list
958 so that wildcards can be used to select files.
959
960 glob_flags => $flags
961 Second argument passed to File::Glob::bsd_glob function. Only
962 available for "scp_put" method.
963
964 copy_attrs => 1
965 Copies modification and access times and modes from the
966 original files.
967
968 bwlimit => $Kbits
969 Limits the used bandwidth, specified in Kbit/s.
970
971 timeout => $secs
972 The transfer is aborted if the connection does not finish
973 before the given timeout elapses. See also "Timeouts".
974
975 async => 1
976 Does not wait for the "scp" command to finish. When this option
977 is used, the method returns the PID of the child "scp" process.
978
979 For instance, it is possible to transfer files to several hosts
980 in parallel as follows:
981
982 use Errno;
983 my (%pid, %ssh);
984 for my $host (@hosts) {
985 $ssh{$host} = Net::OpenSSH->new($host, async => 1);
986 }
987 for my $host (@hosts) {
988 $pid{$host} = $ssh{$host}->scp_put({async => 1}, $local_fn, $remote_fn)
989 or warn "scp_put to $host failed: " . $ssh{$host}->error . "\n";
990 }
991 for my $host (@hosts) {
992 if (my $pid = $pid{$host}) {
993 if (waitpid($pid, 0) > 0) {
994 my $exit = ($? >> 8);
995 $exit and warn "transfer of file to $host failed ($exit)\n";
996 }
997 else {
998 redo if ($! == EINTR);
999 warn "waitpid($pid) failed: $!\n";
1000 }
1001 }
1002 }
1003
1004 stdout_fh => $fh
1005 stderr_fh => $fh
1006 stderr_to_stdout => 1
1007 These options are passed unchanged to method "open_ex",
1008 allowing capture of the output of the "scp" program.
1009
1010 Note that "scp" will not generate progress reports unless its
1011 stdout stream is attached to a tty.
1012
1013 ssh_opts => \@opts
1014 List of extra options for the "ssh" command.
1015
1016 This feature should be used with care, as the given options are
1017 not checked in any way by the module, and they could interfere
1018 with it.
1019
1020 $ssh->rsync_get(\%opts, $remote1, $remote2,..., $local_dir_or_file)
1021 $ssh->rsync_put(\%opts, $local1, $local2,..., $remote_dir_or_file)
1022 These methods use "rsync" over SSH to transfer files from/to the
1023 remote machine.
1024
1025 They accept the same set of options as the "scp" ones.
1026
1027 Any unrecognized option will be passed as an argument to the
1028 "rsync" command (see rsync(1)). Underscores can be used instead of
1029 dashes in "rsync" option names.
1030
1031 For instance:
1032
1033 $ssh->rsync_get({exclude => '*~',
1034 verbose => 1,
1035 safe_links => 1},
1036 '/remote/dir', '/local/dir');
1037
1038 $sftp = $ssh->sftp(%sftp_opts)
1039 Creates a new Net::SFTP::Foreign object for SFTP interaction that
1040 runs through the ssh master connection.
1041
1042 @call = $ssh->make_remote_command(\%opts, @cmd)
1043 $call = $ssh->make_remote_command(\%opts, @cmd)
1044 This method returns the arguments required to execute a command on
1045 the remote machine via SSH. For instance:
1046
1047 my @call = $ssh->make_remote_command(ls => "/var/log");
1048 system @call;
1049
1050 In scalar context, returns the arguments quoted and joined into one
1051 string:
1052
1053 my $remote = $ssh->make_remote_comand("cd /tmp/ && tar xf -");
1054 system "tar cf - . | $remote";
1055
1056 The options accepted are as follows:
1057
1058 tty => $bool
1059 Enables/disables allocation of a tty on the remote side.
1060
1061 forward_agent => $bool
1062 Enables/disables forwarding of authentication agent.
1063
1064 This option can only be used when agent forwarding has been
1065 previously requested on the constructor.
1066
1067 tunnel => 1
1068 Return a command to create a connection to some TCP server
1069 reachable from the remote host. In that case the arguments are
1070 the destination address and port. For instance:
1071
1072 $cmd = $ssh->make_remote_command({tunnel => 1}, $host, $port);
1073
1074 subsystem => 1
1075 Return a command for invoking a SSH subsystem (i.e. SFTP or
1076 netconf). In that case the only argument is the subsystem name.
1077
1078 $ssh->wait_for_master($async)
1079 When the connection has been established by calling the constructor
1080 with the "async" option, this call allows one to advance the
1081 process.
1082
1083 If $async is true, it will perform any work that can be done
1084 immediately without waiting (for instance, entering the password or
1085 checking for the existence of the multiplexing socket) and then
1086 return. If a false value is given, it will finalize the connection
1087 process and wait until the multiplexing socket is available.
1088
1089 It returns a true value after the connection has been successfully
1090 established. False is returned if the connection process fails or
1091 if it has not yet completed (then, the "error" method can be used
1092 to distinguish between both cases).
1093
1094 From version 0.64 upwards, undef is returned when the master is
1095 still in an unstable state (login, killing, etc.) and 0 when it is
1096 in a stable state (running, stopped or gone).
1097
1098 $ssh->check_master
1099 This method runs several checks to ensure that the master
1100 connection is still alive.
1101
1102 $ssh->shell_quote(@args)
1103 Returns the list of arguments quoted so that they will be restored
1104 to their original form when parsed by the remote shell.
1105
1106 In scalar context returns the list of arguments quoted and joined.
1107
1108 Usually this task is done automatically by the module. See "Shell
1109 quoting" below.
1110
1111 This method can also be used as a class method.
1112
1113 Example:
1114
1115 my $quoted_args = Net::OpenSSH->shell_quote(@args);
1116 system('ssh', '--', $host, $quoted_args);
1117
1118 $ssh->shell_quote_glob(@args)
1119 This method is like the previous "shell_quote" but leaves wildcard
1120 characters unquoted.
1121
1122 It can be used as a class method also.
1123
1124 $ssh->set_expand_vars($bool)
1125 Enables/disables variable expansion feature (see "Variable
1126 expansion").
1127
1128 $ssh->get_expand_vars
1129 Returns current state of variable expansion feature.
1130
1131 $ssh->set_var($name, $value)
1132 $ssh->get_var($name, $value)
1133 These methods allow one to change and to retrieve the value of the
1134 given name.
1135
1136 $ssh->get_master_pid
1137 Returns the PID of the master SSH process
1138
1139 $ssh->master_exited
1140 This methods allows one to tell the module that the master process
1141 has exited when we get its PID from some external wait or waitpid
1142 call. For instance:
1143
1144 my $ssh = Net::OpenSSH->new('foo', async => 1);
1145
1146 # create new processes
1147 # ...
1148
1149 # rip them...
1150 my $master_pid = $ssh->master_pid;
1151 while ((my $pid = wait) > 0) {
1152 if ($pid == $master_pid) {
1153 $ssh->master_exited;
1154 }
1155 }
1156
1157 If your program rips the master process and this method is not
1158 called, the OS could reassign the PID to a new unrelated process
1159 and the module would try to kill it at object destruction time.
1160
1161 $ssh->disconnect($async)
1162 Shuts down the SSH connection.
1163
1164 Usually, you don't need to call this method explicitly, but just
1165 let the Net::OpenSSH object go out of scope.
1166
1167 If "async" is true, it doesn't wait for the SSH connection to
1168 terminate. In that case, "wait_for_master" must be called
1169 repeatedly until the shutdown sequence terminates (See the
1170 "AnyEvent" integration section below).
1171
1172 $pid = $ssh->sshfs_import(\%opts, $remote_fs, $local_mnt_point)
1173 $pid = $ssh->sshfs_export(\%opts, $local_fs, $remote_mnt_point)
1174 These methods use sshfs(1) to import or export a file system
1175 through the SSH connection.
1176
1177 They return the $pid of the "sshfs" process or of the slave "ssh"
1178 process used to proxy it. Killing that process unmounts the file
1179 system, though, it may be probably better to use fusermount(1).
1180
1181 The options accepted are as follows:
1182
1183 ssh_opts => \@ssh_opts
1184 Options passed to the slave "ssh" process.
1185
1186 sshfs_opts => \@sshfs_opts
1187 Options passed to the "sshfs" command. For instance, to mount
1188 the file system in read-only mode:
1189
1190 my $pid = $ssh->sshfs_export({sshfs_opts => [-o => 'ro']},
1191 "/", "/mnt/foo");
1192
1193 Note that this command requires a recent version of "sshfs" to work
1194 (at the time of writing, it requires the yet unreleased version
1195 available from the FUSE git repository!).
1196
1197 See also the sshfs(1) man page and the "sshfs" and FUSE web sites
1198 at <https://github.com/libfuse/sshfs> and
1199 <https://github.com/libfuse/libfuse> respectively.
1200
1201 $or = $ssh->object_remote(@args)
1202 Returns an Object::Remote::Connection instance running on top of
1203 the Net::OpenSSH connection.
1204
1205 Example:
1206
1207 my $or = $ssh->object_remote;
1208 my $hostname = Sys::Hostname->can::on($or, 'hostname');
1209 say $hostname->();
1210
1211 See also Object::Remote.
1212
1213 $any = $ssh->any(%opts)
1214 Wraps the current object inside a Net::SSH::Any one.
1215
1216 Example:
1217
1218 my $any = $ssh->any;
1219 my $content = $any->scp_get_content("my-file.txt");
1220
1221 $pid = $ssh->disown_master
1222 Under normal operation Net::OpenSSH controls the life-time of the
1223 master "ssh" process and when the object is destroyed the master
1224 process and any connection running over it are terminated.
1225
1226 In some (rare) cases, it is desirable to let the master process and
1227 all the running connections survive. Calling this method does just
1228 that, it tells Net::OpenSSH object that the master process is not
1229 its own anymore.
1230
1231 The return value is the PID of the master process.
1232
1233 Note also that disowning the master process does not affect the
1234 operation of the module in any other regard.
1235
1236 For instance:
1237
1238 # See examples/sshfs_mount.pl for a working program
1239 my $ssh = Net::OpenSSH->new($host);
1240 my $sshfs_pid = $ssh->sshfs_import("/home/foo", "my-remote-home");
1241 $ssh->disown_master;
1242 $ssh->stop; # tells the master to stop accepting requests
1243 exit(0);
1244
1245 Shell quoting
1246 By default, when invoking remote commands, this module tries to mimic
1247 perl "system" builtin in regard to argument processing. Quoting
1248 "system" in perlfunc:
1249
1250 Argument processing varies depending on the number of arguments. If
1251 there is more than one argument in LIST, or if LIST is an array with
1252 more than one value, starts the program given by the first element
1253 of the list with arguments given by the rest of the list. If there
1254 is only one scalar argument, the argument is checked for shell
1255 metacharacters, and if there are any, the entire argument is passed
1256 to the system's command shell for parsing (this is "/bin/sh -c" on
1257 Unix platforms, but varies on other platforms).
1258
1259 Take for example Net::OpenSSH "system" method:
1260
1261 $ssh->system("ls -l *");
1262 $ssh->system('ls', '-l', '/');
1263
1264 The first call passes the argument unchanged to ssh and it is executed
1265 in the remote side through the shell which interprets metacharacters.
1266
1267 The second call escapes any shell metacharacters so that, effectively,
1268 it is equivalent to calling the command directly and not through the
1269 shell.
1270
1271 Under the hood, as the Secure Shell protocol does not provide for this
1272 mode of operation and always spawns a new shell where it runs the given
1273 command, Net::OpenSSH quotes any shell metacharacters in the command
1274 list.
1275
1276 All the methods that invoke a remote command (system, open_ex, etc.)
1277 accept the option "quote_args" that allows one to force/disable shell
1278 quoting.
1279
1280 For instance:
1281
1282 $ssh->system({quote_args => 1}, "/path with spaces/bin/foo");
1283
1284 will correctly handle the spaces in the program path.
1285
1286 The shell quoting mechanism implements some extensions (for instance,
1287 performing redirections to /dev/null on the remote side) that can be
1288 disabled with the option "quote_args_extended":
1289
1290 $ssh->system({ stderr_discard => 1,
1291 quote_args => 1, quote_args_extended => 0 },
1292 @cmd);
1293
1294 The option "quote_args" can also be used to disable quoting when more
1295 than one argument is passed. For instance, to get some pattern expanded
1296 by the remote shell:
1297
1298 $ssh->system({quote_args => 0}, 'ls', '-l', "/tmp/files_*.dat");
1299
1300 The method "shell_quote" can be used to selectively quote some
1301 arguments and leave others untouched:
1302
1303 $ssh->system({quote_args => 0},
1304 $ssh->shell_quote('ls', '-l'),
1305 "/tmp/files_*.dat");
1306
1307 When the glob option is set in "scp" and "rsync" file transfer methods,
1308 an alternative quoting method which knows about file wildcards and
1309 passes them unquoted is used. The set of wildcards recognized currently
1310 is the one supported by bash(1).
1311
1312 Another way to selectively use quote globing or fully disable quoting
1313 for some specific arguments is to pass them as scalar references or
1314 double scalar references respectively. In practice, that means
1315 prepending them with one or two backslashes. For instance:
1316
1317 # quote the last argument for globing:
1318 $ssh->system('ls', '-l', \'/tmp/my files/filed_*dat');
1319
1320 # append a redirection to the remote command
1321 $ssh->system('ls', '-lR', \\'>/tmp/ls-lR.txt');
1322
1323 # expand remote shell variables and glob in the same command:
1324 $ssh->system('tar', 'czf', \\'$HOME/out.tgz', \'/var/log/server.*.log');
1325
1326 As shell quoting is a tricky matter, I expect bugs to appear in this
1327 area. You can see how "ssh" is called, and the quoting used setting the
1328 following debug flag:
1329
1330 $Net::OpenSSH::debug |= 16;
1331
1332 By default, the module assumes the remote shell is some variant of a
1333 POSIX or Bourne shell ("bash", "dash", "ksh", etc.). If this is not the
1334 case, the construction option "remote_shell" can be used to select an
1335 alternative quoting mechanism.
1336
1337 For instance:
1338
1339 $ssh = Net::OpenSSH->new($host, remote_shell => 'csh');
1340 $ssh->system(echo => "hard\n to\n quote\n argument!");
1341
1342 Currently there are quoters available for POSIX (Bourne) compatible
1343 shells, "csh" and the two Windows variants "MSWin" (for servers using
1344 Win32::CreateProcess, see Net::OpenSSH::ShellQuoter::MSWin) and "MSCmd"
1345 (for servers using "cmd.exe", see Net::OpenSSH::ShellQuoter::MSCmd).
1346
1347 In any case, you can always do the quoting yourself and pass the quoted
1348 remote command as a single string:
1349
1350 # for VMS
1351 $ssh->system('DIR/SIZE NFOO::USERS:[JSMITH.DOCS]*.TXT;0');
1352
1353 Note that the current quoting mechanism does not handle possible
1354 aliases defined by the remote shell. In that case, to force execution
1355 of the command instead of the alias, the full path to the command must
1356 be used.
1357
1358 Timeouts
1359 In order to stop remote processes when they timeout, the ideal approach
1360 would be to send them signals through the SSH connection as specified
1361 by the protocol standard.
1362
1363 Unfortunately OpenSSH does not implement that feature so Net::OpenSSH
1364 has to use other imperfect approaches:
1365
1366 Ā· close slave I/O streams
1367
1368 Closing the STDIN and STDOUT streams of the unresponsive remote
1369 process will effectively deliver a SIGPIPE when it tries to access
1370 any of them.
1371
1372 Remote processes may not access STDIN or STDOUT and even then,
1373 Net::OpenSSH can only close these channels when it is capturing
1374 them, so this approach does not always work.
1375
1376 Ā· killing the local SSH slave process
1377
1378 This action may leave the remote process running, creating a remote
1379 orphan so Net::OpenSSH does not use it unless the construction
1380 option "kill_ssh_on_timeout" is set.
1381
1382 Luckily, future versions of OpenSSH will support signaling remote
1383 processes via the mux channel.
1384
1385 Variable expansion
1386 The variable expansion feature allows one to define variables that are
1387 expanded automatically inside command arguments and file paths.
1388
1389 This feature is disabled by default. It is intended to be used with
1390 Net::OpenSSH::Parallel and other similar modules.
1391
1392 Variables are delimited by a pair of percent signs ("%"), for instance
1393 "%HOST%". Also, two consecutive percent signs are replaced by a single
1394 one.
1395
1396 The special variables "HOST", "USER" and "PORT" are maintained
1397 internally by the module and take the obvious values.
1398
1399 Variable expansion is performed before shell quoting (see "Shell
1400 quoting").
1401
1402 Some usage example:
1403
1404 my $ssh = Net::OpenSSH->new('server.foo.com', expand_vars => 1);
1405 $ssh->set_var(ID => 42);
1406 $ssh->system("ls >/tmp/ls.out-%HOST%-%ID%");
1407
1408 will redirect the output of the "ls" command to
1409 "/tmp/ls.out-server.foo.com-42" on the remote host.
1410
1411 Tunnels
1412 Besides running commands on the remote host, Net::OpenSSH also allows
1413 one to tunnel TCP connections to remote machines reachable from the SSH
1414 server.
1415
1416 That feature is made available through the "tunnel" option of the
1417 "open_ex" method, and also through wrapper methods "open_tunnel" and
1418 "capture_tunnel" and most others where it makes sense.
1419
1420 Example:
1421
1422 $ssh->system({tunnel => 1,
1423 stdin_data => "GET / HTTP/1.0\r\n\r\n",
1424 stdout_file => "/tmp/$server.res"},
1425 $server, 80)
1426 or die "unable to retrieve page: " . $ssh->error;
1427
1428 or capturing the output of several requests in parallel:
1429
1430 my @pids;
1431 for (@servers) {
1432 my $pid = $ssh->spawn({tunnel => 1,
1433 stdin_file => "/tmp/request.req",
1434 stdout_file => "/tmp/$_.res"},
1435 $_, 80);
1436 if ($pid) {
1437 push @pids, $pid;
1438 }
1439 else {
1440 warn "unable to spawn tunnel process to $_: " . $ssh->error;
1441 }
1442 }
1443 waitpid ($_, 0) for (@pids);
1444
1445 Under the hood, in order to create a tunnel, a new "ssh" process is
1446 spawned with the option "-W${address}:${port}" (available from OpenSSH
1447 5.4 and upwards) making it redirect its stdio streams to the remote
1448 given address. Unlike when "ssh" "-L" options is used to create
1449 tunnels, no TCP port is opened on the local machine at any time so this
1450 is a perfectly secure operation.
1451
1452 The PID of the new process is returned by the named methods. It must be
1453 reaped once the pipe or socket handlers for the local side of the
1454 tunnel have been closed.
1455
1456 OpenSSH 5.4 or later is required for the tunnels functionality to work.
1457 Also, note that tunnel forwarding may be administratively forbidden at
1458 the server side (see sshd(8) and sshd_config(5) or the documentation
1459 provided by your SSH server vendor).
1460
1461 Tunnels targeting UNIX sockets
1462
1463 When connecting to hosts running a recent version of OpenSSH sshd, it
1464 is also possible to open connections targeting Unix sockets.
1465
1466 For instance:
1467
1468 my $response = $ssh->capture({tunnel => 1, stdin_data => $request },
1469 "/tmp/socket-foo");
1470
1471 Currently, this feature requires a patched OpenSSH ssh client. The
1472 patch is available as
1473 "patches/openssh-fwd-stdio-to-streamlocal-1.patch".
1474
1475 Port forwarding
1476
1477 Net::OpenSSH does not offer direct support for handling port
1478 forwardings between server and client. But that can be done easily
1479 anyway passing custom SSH options to its methods.
1480
1481 For instance, tunnel creation options can be passed to the constructor:
1482
1483 my $ssh = Net::OpenSSH->new(...
1484 master_opts => -Llocalhost:1234:localhost:3306');
1485
1486 The port forwardings can also be changed for a running SSH connection
1487 using a Control command:
1488
1489 # setting up a tunnel:
1490 $ssh->system({ssh_opts => ['-O','forward',
1491 '-L127.0.0.1:12345:127.0.0.1:3306']});
1492
1493 # canceling it:
1494 $ssh->system({ssh_opts => ['-O', 'cancel',
1495 '-L127.0.0.1:12345:127.0.0.1:3306']});
1496
1497 Data encoding
1498 Net::OpenSSH has some support for transparently converting the data
1499 send or received from the remote server to Perl internal unicode
1500 representation.
1501
1502 The methods supporting that feature are those that move data from/to
1503 Perl data structures (e.g. "capture", "capture2", "capture_tunnel" and
1504 methods supporting the "stdin_data" option). Data accessed through
1505 pipes, sockets or redirections is not affected by the encoding options.
1506
1507 It is also possible to set the encoding of the command and arguments
1508 passed to the remote server on the command line.
1509
1510 By default, if no encoding option is given on the constructor or on the
1511 method calls, Net::OpenSSH will not perform any encoding
1512 transformation, effectively processing the data as "latin1".
1513
1514 When data can not be converted between the Perl internal representation
1515 and the selected encoding inside some Net::OpenSSH method, it will fail
1516 with an "OSSH_ENCODING_ERROR" error.
1517
1518 The supported encoding options are as follows:
1519
1520 stream_encoding => $encoding
1521 sets the encoding of the data send and received on capture methods.
1522
1523 argument_encoding => $encoding
1524 sets the encoding of the command line arguments
1525
1526 encoding => $encoding
1527 sets both "argument_encoding" and "stream_encoding".
1528
1529 The constructor also accepts "default_encoding",
1530 "default_stream_encoding" and "default_argument_encoding" that set the
1531 defaults.
1532
1533 Diverting "new"
1534 When a code ref is installed at $Net::OpenSSH::FACTORY, calls to new
1535 will be diverted through it.
1536
1537 That feature can be used to transparently implement connection caching,
1538 for instance:
1539
1540 my $old_factory = $Net::OpenSSH::FACTORY;
1541 my %cache;
1542
1543 sub factory {
1544 my ($class, %opts) = @_;
1545 my $signature = join("\0", $class, map { $_ => $opts{$_} }, sort keys %opts);
1546 my $old = $cache{signature};
1547 return $old if ($old and $old->error != OSSH_MASTER_FAILED);
1548 local $Net::OpenSSH::FACTORY = $old_factory;
1549 $cache{$signature} = $class->new(%opts);
1550 }
1551
1552 $Net::OpenSSH::FACTORY = \&factory;
1553
1554 ... and I am sure it can be abused in several other ways!
1555
1557 Expect
1558 Sometimes you would like to use Expect to control some program running
1559 in the remote host. You can do it as follows:
1560
1561 my ($pty, $pid) = $ssh->open2pty(@cmd)
1562 or die "unable to run remote command @cmd";
1563 my $expect = Expect->init($pty);
1564
1565 Then, you will be able to use the new Expect object in $expect as
1566 usual.
1567
1568 Net::Telnet
1569 This example is adapted from Net::Telnet documentation:
1570
1571 my ($pty, $pid) = $ssh->open2pty({stderr_to_stdout => 1})
1572 or die "unable to start remote shell: " . $ssh->error;
1573 my $telnet = Net::Telnet->new(-fhopen => $pty,
1574 -prompt => '/.*\$ $/',
1575 -telnetmode => 0,
1576 -cmd_remove_mode => 1,
1577 -output_record_separator => "\r");
1578
1579 $telnet->waitfor(-match => $telnet->prompt,
1580 -errmode => "return")
1581 or die "login failed: " . $telnet->lastline;
1582
1583 my @lines = $telnet->cmd("who");
1584
1585 ...
1586
1587 $telnet->close;
1588 waitpid($pid, 0);
1589
1590 mod_perl and mod_perl2
1591 mod_perl and mod_perl2 tie STDIN and STDOUT to objects that are not
1592 backed up by real file descriptors at the operating system level.
1593 Net::OpenSSH will fail if any of these handles is used explicitly or
1594 implicitly when calling some remote command.
1595
1596 The work-around is to redirect them to "/dev/null" or to some file:
1597
1598 open my $def_in, '<', '/dev/null' or die "unable to open /dev/null";
1599 my $ssh = Net::OpenSSH->new($host,
1600 default_stdin_fh => $def_in);
1601
1602 my $out = $ssh->capture($cmd1);
1603 $ssh->system({stdout_discard => 1}, $cmd2);
1604 $ssh->system({stdout_to_file => '/tmp/output'}, $cmd3);
1605
1606 Also, note that from a security stand point, running "ssh" from inside
1607 the web server process is not a great idea. An attacker exploiting some
1608 Apache bug would be able to access the SSH keys and passwords and gain
1609 unlimited access to the remote systems.
1610
1611 If you can, use a queue (as TheSchwartz) or any other mechanism to
1612 execute the ssh commands from another process running under a different
1613 user account.
1614
1615 At a minimum, ensure that "~www-data/.ssh" (or similar) is not
1616 accessible through the web server!
1617
1618 Net::SFTP::Foreign
1619 See method "sftp".
1620
1621 Net::SSH::Any
1622 See method "any".
1623
1624 Object::Remote
1625 See method "object_remote".
1626
1627 AnyEvent (and similar frameworks)
1628 Net::OpenSSH provides all the functionality required to be integrated
1629 inside event oriented programming framework such as AnyEvent or
1630 IO::Async in the following way:
1631
1632 1. Create a disconnected Net::OpenSSH object:
1633 my $ssh = Net::OpenSSH->new($host, async => 1, ...);
1634
1635 2. Let the object connect to the remote host:
1636 Use a timer to call the "wait_for_master" method in async mode
1637 repeatedly until it returns a true value indicating success.
1638
1639 Also, the object error state needs to be checked after every call
1640 in order to detect failed connections. For instance:
1641
1642 my $ssh = Net::OpenSSH->new(..., async => 1);
1643 my $w;
1644 $w = AE::timer 0.1, 0.1, sub {
1645 if ($ssh->wait_for_master(1)) {
1646 # the connection has been established!
1647 # remote commands can be run now
1648 undef $w;
1649 on_ssh_success(...);
1650 }
1651 elsif ($ssh->error) {
1652 # connection can not be established
1653 undef $w;
1654 on_ssh_failure(...);
1655 }
1656 }
1657
1658 3. Use the event framework to launch the remote processes:
1659 Call Net::OpenSSH "make_remote_command" to construct commands which
1660 can be run using the framework regular facilities for launching
1661 external commands.
1662
1663 Error checking should also be performed at this point because the
1664 SSH connection could be broken.
1665
1666 For instance:
1667
1668 if (defined(my $cmd = $ssh->make_remote_command(echo => 'hello!')) {
1669 AnyEvent::Util::run_cmd($cmd, %run_cmd_opts);
1670 }
1671 else {
1672 # something went wrong!
1673 }
1674
1675 Alternatively, any of the "open*" methods provided by Net::OpenSSH
1676 could also be used to launch remote commands.
1677
1678 4. When finished, disconnect asynchronously
1679 After initiating an asynchronous disconnect with disconnect(1),
1680 repeatedly call "wait_for_master" until you get a defined but false
1681 value:
1682
1683 $ssh->disconnect(1);
1684
1685 my $w; $w = AE::timer 0.1, 0.1, sub {
1686 my $res = $ssh->wait_for_master(1);
1687
1688 if (defined $res && !$res) {
1689 undef $w;
1690 undef $ssh;
1691 }
1692 };
1693
1694 Be careful not to let the $ssh object go out of scope until the
1695 disconnection has finished, otherwise its destructor will wait and
1696 block your program until the disconnection has completed.
1697
1698 Other modules
1699 CPAN contains several modules that rely on SSH to perform their duties
1700 as for example IPC::PerlSSH or GRID::Machine.
1701
1702 Often, it is possible to instruct them to go through a Net::OpenSSH
1703 multiplexed connection employing some available constructor option. For
1704 instance:
1705
1706 use Net::OpenSSH;
1707 use IPC::PerlIPC;
1708 my $ssh = Net::OpenSSH->new(...);
1709 $ssh->error and die "unable to connect to remote host: " . $ssh->error;
1710 my @cmd = $ssh->make_remote_command('/usr/bin/perl');
1711 my $ipc = IPC::PerlSSH->new(Command => \@cmd);
1712 my @r = $ipc->eval('...');
1713
1714 or...
1715
1716 use GRID::Machine;
1717 ...
1718 my @cmd = $ssh->make_remote_command('/usr/bin/perl');
1719 my $grid = GRID::Machine->new(command => \@cmd);
1720 my $r = $grid->eval('print "hello world!\n"');
1721
1722 In other cases, some kind of plugin mechanism is provided by the 3rd
1723 party modules to allow for different transports. The method "open2" may
1724 be used to create a pair of pipes for transport in these cases.
1725
1727 Usually, Net::OpenSSH works out of the box, but when it fails, some
1728 users have a hard time finding the cause of the problem. This mini
1729 troubleshooting guide should help you to find and solve it.
1730
1731 1 - check the error message
1732 Add in your script, after the Net::OpenSSH constructor call, an
1733 error check:
1734
1735 $ssh = Net::OpenSSH->new(...);
1736 $ssh->error and die "SSH connection failed: " . $ssh->error;
1737
1738 The error message will tell what has gone wrong.
1739
1740 2 - Check the connection parameters
1741 Believe it or not, passing bad parameters to Net::OpenSSH turns to
1742 be one of the top causes of failures so check that you are using
1743 the right parameters.
1744
1745 Specifically, if you are obtaining them from the outside, ensure
1746 that they don't have extra spaces or new lines attached (do you
1747 need to "chomp"?).
1748
1749 Passwords and URIs may contain "$" or "@" characters. If you have
1750 then hardcoded in your script, check that those are quoted properly
1751 (and BTW, use "strict").
1752
1753 3 - OpenSSH version
1754 Ensure that you have a version of "ssh" recent enough:
1755
1756 $ ssh -V
1757 OpenSSH_5.1p1 Debian-5, OpenSSL 0.9.8g 19 Oct 2007
1758
1759 OpenSSH version 4.1 was the first to support the multiplexing
1760 feature and is the minimal required by the module to work. I advise
1761 you to use the latest OpenSSH (currently 7.5).
1762
1763 The "ssh_cmd" constructor option lets you select the "ssh" binary
1764 to use. For instance:
1765
1766 $ssh = Net::OpenSSH->new($host,
1767 ssh_cmd => "/opt/OpenSSH/5.8/bin/ssh")
1768
1769 Some hardware vendors (e.g. Sun, err... Oracle) include custom
1770 versions of OpenSSH bundled with the operating system. In
1771 principle, Net::OpenSSH should work with these SSH clients as long
1772 as they are derived from some version of OpenSSH recent enough.
1773 Anyway, my advise is to use the real OpenSSH software if you can!
1774
1775 4 - run ssh from the command line
1776 Check you can connect to the remote host using the same parameters
1777 you are passing to Net::OpenSSH. In particular, ensure that you are
1778 running "ssh" as the same local user.
1779
1780 If you are running your script from a web server, the user would
1781 probably be "www", "apache" or something alike.
1782
1783 Common problems are:
1784
1785 Ā· Remote host public key not present in known_hosts file.
1786
1787 The SSH protocol uses public keys to identify the remote hosts
1788 so that they can not be supplanted by some malicious third
1789 parties.
1790
1791 For OpenSSH, usually the server public key is stored in
1792 "/etc/ssh/ssh_host_dsa_key.pub" or in
1793 "/etc/ssh/ssh_host_rsa_key.pub" and that key should be copied
1794 into the "~/.ssh/known_hosts" file in the local machine (other
1795 SSH implementations may use other file locations).
1796
1797 Maintaining the server keys when several hosts and clients are
1798 involved may be somewhat inconvenient, so most SSH clients, by
1799 default, when a new connection is established to a host whose
1800 key is not in the "known_hosts" file, show the key and ask the
1801 user if he wants the key copied there.
1802
1803 Ā· Wrong remote host public key in known_hosts file.
1804
1805 This is another common problem that happens when some server is
1806 replaced or reinstalled from scratch and its public key changes
1807 becoming different to that installed on the "known_hosts" file.
1808
1809 The easiest way to solve that problem is to remove the old key
1810 from the "known_hosts" file by hand using any editor and then
1811 to connect to the server replying "yes" when asked to save the
1812 new key.
1813
1814 Ā· Wrong permissions for the "~/.ssh" directory or its contents.
1815
1816 OpenSSH client performs several checks on the access
1817 permissions of the "~/.ssh" directory and its contents and
1818 refuses to use them when misconfigured. See the FILES section
1819 from the ssh(1) man page.
1820
1821 Ā· Incorrect settings for password or public key authentication.
1822
1823 Check that you are using the right password or that the user
1824 public key is correctly installed on the server.
1825
1826 5 - security checks on the multiplexing socket
1827 Net::OpenSSH performs some security checks on the directory where
1828 the multiplexing socket is going to be placed to ensure that it can
1829 not be accessed by other users.
1830
1831 The default location for the multiplexing socket is under
1832 "~/.libnet-openssh-perl". It can be changed using the "ctl_dir" and
1833 "ctl_path" constructor arguments.
1834
1835 The requirements for that directory and all its parents are:
1836
1837 Ā· They have to be owned by the user executing the script or by
1838 root
1839
1840 Ā· Their permission masks must be 0755 or more restrictive, so
1841 nobody else has permissions to perform write operations on
1842 them.
1843
1844 The constructor option "strict_mode" disables these security
1845 checks, but you should not use it unless you understand its
1846 implications.
1847
1848 6 - file system must support sockets
1849 Some file systems (as for instance FAT or AFS) do not support
1850 placing sockets inside them.
1851
1852 Ensure that the "ctl_dir" path does not lay into one of those file
1853 systems.
1854
1856 Debugging of Net::OpenSSH internals is controlled through the variable
1857 $Net::OpenSSH::debug. Every bit of this variable activates debugging of
1858 some subsystem as follows:
1859
1860 bit 1 - errors
1861 Dumps changes on the internal object attribute where errors are
1862 stored.
1863
1864 bit 2 - ctl_path
1865 Dumps information about ctl_path calculation and the tests
1866 performed on that directory in order to decide if it is secure to
1867 place the multiplexing socket inside.
1868
1869 bit 4 - connecting
1870 Dumps information about the establishment of new master
1871 connections.
1872
1873 bit 8 - commands and arguments
1874 Dumps the command and arguments for every system/exec call.
1875
1876 bit 16 - command execution
1877 Dumps information about the progress of command execution.
1878
1879 bit 32 - destruction
1880 Dumps information about the destruction of Net::OpenSSH objects and
1881 the termination of the SSH master processes.
1882
1883 bit 64 - IO loop
1884 Dumps information about the progress of the IO loop on capture
1885 operations.
1886
1887 bit 128 - IO hexdumps
1888 Generates hexdumps of the information that travels through the SSH
1889 streams inside capture operations.
1890
1891 bit 512 - OS tracing of the master process
1892 Use the module Net::OpenSSH::OSTracer to trace the SSH master
1893 process at the OS level.
1894
1895 For instance, in order to activate all the debugging flags, you can
1896 use:
1897
1898 $Net::OpenSSH::debug = ~0;
1899
1900 Note that the meaning of the flags and the information generated is
1901 only intended for debugging of the module and may change without notice
1902 between releases.
1903
1904 If you are using password authentication, enabling debugging for
1905 IO::Tty may also show interesting information:
1906
1907 IO::Tty::DEBUG = 1;
1908
1909 Finally, by default debugging output is sent to "STDERR". You can
1910 override it pointing $Net::OpenSSH::debug_fh to a different file
1911 handle. For instance:
1912
1913 BEGIN {
1914 open my $out, '>', '/tmp/debug.txt' or warn $!;
1915 $Net::OpenSSH::debug_fh = $out;
1916 $Net::OpenSSH::debug = -1;
1917 }
1918
1920 Q: Is this module secure?
1921
1922 A: Well, it tries to be!
1923
1924 From a security standpoint the aim of this module is to be as secure as
1925 OpenSSH, your operating system, your shell and in general your
1926 environment allow it to be.
1927
1928 It does not take any shortcut just to make your life easier if that
1929 means lowering the security level (for instance, disabling
1930 "StrictHostKeyChecking" by default).
1931
1932 In code supporting features that are not just proxied to OpenSSH, the
1933 module tries to keep the same standards of security as OpenSSH (for
1934 instance, checking directory and file permissions when placing the
1935 multiplexing socket).
1936
1937 On the other hand, and keeping with OpenSSH philosophy, the module lets
1938 you disable most (all?) of those security measures. But just because it
1939 lets you do it it doesn't mean it is a good idea to do so!!!
1940
1941 If you are a novice programmer or SSH user, and googling you have just
1942 found some flag that you don't understand but that seems to magically
1943 solve your connection problems... well, believe me, it is probably a
1944 bad idea to use it. Ask somebody how really knows first!
1945
1946 Just to make thinks clear, if your code contains any of the keywords
1947 from the (non-exclusive) list below and you don't know why, you are
1948 probably wrecking the security of the SSH protocol:
1949
1950 strict_mode
1951 StrictHostKeyChecking
1952 UserKnownHostsFile
1953
1954 Other considerations related to security you may like to know are as
1955 follows:
1956
1957 Taint mode
1958 The module supports working in taint mode.
1959
1960 If you are in an exposed environment, you should probably enable it
1961 for your script in order to catch any unchecked command for being
1962 executed in the remote side.
1963
1964 Web environments
1965 It is a bad idea to establish SSH connections from your webserver
1966 because if it becomes compromised in any way, the attacker would be
1967 able to use the credentials from your script to connect to the
1968 remote host and do anything he wishes there.
1969
1970 Command quoting
1971 The module can quote commands and arguments for you in a flexible
1972 and powerful way.
1973
1974 This is a feature you should use as it reduces the possibility of
1975 some attacker being able to inject and run arbitrary commands on
1976 the remote machine (and even for scripts that are not exposed it is
1977 always advisable to enable argument quoting).
1978
1979 Having said that, take into consideration that argument-quoting is
1980 just a hack to emulate the invoke-without-a-shell feature of Perl
1981 builtins such as "system" and alike. There may be bugs(*) on the
1982 quoting code, your particular shell may have different quoting
1983 rules with unhandled corner cases or whatever. If your script is
1984 exposed to the outside, you should check your inputs and restrict
1985 what you accept as valid.
1986
1987 [* even if this is one of the parts of the module more intensively
1988 tested!]
1989
1990 Shellshock
1991 (see Shellshock
1992 <http://en.wikipedia.org/wiki/Shellshock_%28software_bug%29>)
1993
1994 When executing local commands, the module always avoids calling the
1995 shell so in this way it is not affected by Shellshock.
1996
1997 Unfortunately, some commands ("scp", "rsync" and "ssh" when the
1998 "ProxyCommand" option is used) invoke other commands under the hood
1999 using the user shell. That opens the door to local Shellshock
2000 exploitation.
2001
2002 On the remote side invocation of the shell is unavoidable due to
2003 the protocol design.
2004
2005 By default, SSH does not forward environment variables but some
2006 Linux distributions explicitly change the default OpenSSH
2007 configuration to enable forwarding and acceptance of some specific
2008 ones (for instance "LANG" and "LC_*" on Debian and derivatives,
2009 Fedora does alike) and this also opens the door to Shellshock
2010 exploitation.
2011
2012 Note that the shell used to invoke commands is not "/bin/sh" but
2013 the user shell as configured in "/etc/passwd", PAM or whatever
2014 authentication subsystem is used by the local or remote operating
2015 system. Debian users, don't think you are not affected because your
2016 "/bin/sh" points to "dash"!
2017
2019 Frequent questions about the module:
2020
2021 Connecting to switches, routers, etc.
2022 Q: I can not get the method "system", "capture", etc., to work when
2023 connecting to some router, switch, etc. What I am doing wrong?
2024
2025 A: Roughly, the SSH protocol allows for two modes of operation:
2026 command mode and interactive mode.
2027
2028 Command mode is designed to run single commands on the remote host.
2029 It opens a SSH channel between both hosts, asks the remote computer
2030 to run some given command and when it finishes, the channel is
2031 closed. It is what you get, for instance, when you run something
2032 as...
2033
2034 $ ssh my.unix.box cat foo.txt
2035
2036 ... and it is also the way Net::OpenSSH runs commands on the remote
2037 host.
2038
2039 Interactive mode launches a shell on the remote hosts with its
2040 stdio streams redirected to the local ones so that the user can
2041 transparently interact with it.
2042
2043 Some devices (as probably the one you are using) do not run an
2044 standard, general purpose shell (e.g. "bash", "csh" or "ksh") but
2045 some custom program specially targeted and limited to the task of
2046 configuring the device.
2047
2048 Usually, the SSH server running on these devices does not support
2049 command mode. It unconditionally attaches the restricted shell to
2050 any incoming SSH connection and waits for the user to enter
2051 commands through the redirected stdin stream.
2052
2053 The only way to work-around this limitation is to make your script
2054 talk to the restricted shell (1-open a new SSH session, 2-wait for
2055 the shell prompt, 3-send a command, 4-read the output until you get
2056 to the shell prompt again, repeat from 3). The best tool for this
2057 task is probably Expect, used alone or combined with Net::OpenSSH
2058 (see "Expect").
2059
2060 There are some devices that support command mode but that only
2061 accept one command per connection. In that cases, using Expect is
2062 also probably the best option.
2063
2064 Nowadays, there is a new player, Net::CLI::Interact that may be
2065 more suitable than Expect, and Net::Appliance::Session for working
2066 specifically with network devices.
2067
2068 Connection fails
2069 Q: I am unable to make the module connect to the remote host...
2070
2071 A: Have you read the troubleshooting section? (see
2072 "TROUBLESHOOTING").
2073
2074 Disable StrictHostKeyChecking
2075 Q: Why is "ssh" not run with "StrictHostKeyChecking=no"?
2076
2077 A: Using "StrictHostKeyChecking=no" relaxes the default security
2078 level of SSH and it will be relatively easy to end with a
2079 misconfigured SSH (for instance, when "known_hosts" is unwritable)
2080 that could be forged to connect to a bad host in order to perform
2081 man-in-the-middle attacks, etc.
2082
2083 I advice you to do not use that option unless you fully understand
2084 its implications from a security point of view.
2085
2086 If you want to use it anyway, past it to the constructor:
2087
2088 $ssh = Net::OpenSSH->new($host,
2089 master_opts => [-o => "StrictHostKeyChecking=no"],
2090 ...);
2091
2092 child process STDIN/STDOUT/STDERR is not a real system file handle
2093 Q: Calls to "system", "capture", etc. fail with the previous error,
2094 what's happening?
2095
2096 A: The reported stdio stream is closed or is not attached to a real
2097 file handle (e.g. it is a tied handle). Redirect it to "/dev/null"
2098 or to a real file:
2099
2100 my $out = $ssh->capture({stdin_discard => 1, stderr_to_stdout => 1},
2101 $cmd);
2102
2103 See also the mod_perl entry above.
2104
2105 Solaris (and AIX and probably others)
2106 Q: I was trying Net::OpenSSH on Solaris and seem to be running into
2107 an issue...
2108
2109 A: The SSH client bundled with Solaris is an early fork of OpenSSH
2110 that does not provide the multiplexing functionality required by
2111 Net::OpenSSH. You will have to install the OpenSSH client.
2112
2113 Precompiled packages are available from Sun Freeware
2114 (<http://www.sunfreeware.com>). There, select your OS version an
2115 CPU architecture, download the OpenSSH package and its dependencies
2116 and install them. Note that you do not need to configure Solaris to
2117 use the OpenSSH server "sshd".
2118
2119 Ensure that OpenSSH client is in your path before the system "ssh"
2120 or alternatively, you can hardcode the full path into your scripts
2121 as follows:
2122
2123 $ssh = Net::OpenSSH->new($host,
2124 ssh_cmd => '/usr/local/bin/ssh');
2125
2126 AIX and probably some other unixen, also bundle SSH clients lacking
2127 the multiplexing functionality and require installation of the real
2128 OpenSSH.
2129
2130 Can not change working directory
2131 Q: I want to run some command inside a given remote directory but I
2132 am unable to change the working directory. For instance:
2133
2134 $ssh->system('cd /home/foo/bin');
2135 $ssh->systen('ls');
2136
2137 does not list the contents of "/home/foo/bin".
2138
2139 What am I doing wrong?
2140
2141 A: Net::OpenSSH (and, for that matter, all the SSH modules
2142 available from CPAN but Net::SSH::Expect) run every command in a
2143 new session so most shell builtins that are run for its side
2144 effects become useless (e.g. "cd", "export", "ulimit", "umask",
2145 etc., usually, you can list them running "help" from the shell).
2146
2147 A work around is to combine several commands in one, for instance:
2148
2149 $ssh->system('cd /home/foo/bin && ls');
2150
2151 Note the use of the shell "&&" operator instead of ";" in order to
2152 abort the command as soon as any of the subcommands fail.
2153
2154 Also, several commands can be combined into one while still using
2155 the multi-argument quoting feature as follows:
2156
2157 $ssh->system(@cmd1, \\'&&', @cmd2, \\'&&', @cmd3, ...);
2158
2159 Running detached remote processes
2160 Q: I need to be able to ssh into several machines from my script,
2161 launch a process to run in the background there, and then return
2162 immediately while the remote programs keep running...
2163
2164 A: If the remote systems run some Unix/Linux variant, the right
2165 approach is to use nohup(1) that will disconnect the remote process
2166 from the stdio streams and to ask the shell to run the command on
2167 the background. For instance:
2168
2169 $ssh->system("nohup $long_running_command &");
2170
2171 Also, it may be possible to demonize the remote program. If it is
2172 written in Perl you can use App::Daemon for that (actually, there
2173 are several CPAN modules that provided that kind of functionality).
2174
2175 In any case, note that you should not use "spawn" for that.
2176
2177 MaxSessions server limit reached
2178 Q: I created an $ssh object and then fork a lot children processes
2179 which use this object. When the children number is bigger than
2180 "MaxSessions" as defined in sshd configuration (defaults to 10),
2181 trying to fork new remote commands will prompt the user for the
2182 password.
2183
2184 A: When the slave SSH client gets a response from the remote
2185 servers saying that the maximum number of sessions for the current
2186 connection has been reached, it fall backs to open a new direct
2187 connection without going through the multiplexing socket.
2188
2189 To stop that for happening, the following hack can be used:
2190
2191 $ssh = Net::OpenSSH->new(host,
2192 default_ssh_opts => ['-oConnectionAttempts=0'],
2193 ...);
2194
2195 Running remote commands with sudo
2196 Q: How can I run remote commands using "sudo" to become root first?
2197
2198 A: The simplest way is to tell "sudo" to read the password from
2199 stdin with the "-S" flag and to do not use cached credentials with
2200 the "-k" flag. You may also like to use the "-p" flag to tell
2201 "sudo" to print an empty prompt. For instance:
2202
2203 my @out = $ssh->capture({ stdin_data => "$sudo_passwd\n" },
2204 'sudo', '-Sk',
2205 '-p', '',
2206 '--',
2207 @cmd);
2208
2209 If the version of sudo installed on the remote host does not
2210 support the "-S" flag (it tells sudo to read the password from its
2211 STDIN stream), you can do it as follows:
2212
2213 my @out = $ssh->capture({ tty => 1,
2214 stdin_data => "$sudo_passwd\n" },
2215 'sudo', '-k',
2216 '-p', '',
2217 '--',
2218 @cmd);
2219
2220 This may generate an spurious and harmless warning from the SSH
2221 master connection (because we are requesting allocation of a tty on
2222 the remote side and locally we are attaching it to a regular pair
2223 of pipes).
2224
2225 If for whatever reason the methods described above fail, you can
2226 always revert to using Expect to talk to the remote "sudo". See the
2227 "examples/expect.pl" script from this module distribution.
2228
2230 OpenSSH client documentation ssh(1), ssh_config(5), the project web
2231 <http://www.openssh.org> and its FAQ
2232 <http://www.openbsd.org/openssh/faq.html>. scp(1) and rsync(1). The
2233 OpenSSH Wikibook <http://en.wikibooks.org/wiki/OpenSSH>.
2234
2235 Net::OpenSSH::Gateway for detailed instruction about how to get this
2236 module to connect to hosts through proxies and other SSH gateway
2237 servers.
2238
2239 Core perl documentation perlipc, "open" in perlfunc, "waitpid" in
2240 perlfunc.
2241
2242 IO::Pty to known how to use the pseudo tty objects returned by several
2243 methods on this package.
2244
2245 Net::SFTP::Foreign provides a compatible SFTP implementation.
2246
2247 Expect can be used to interact with commands run through this module on
2248 the remote machine (see also the "expect.pl" and <autosudo.pl> scripts
2249 in the examples directory).
2250
2251 SSH::OpenSSH::Parallel is an advanced scheduler that allows one to run
2252 commands in remote hosts in parallel. It is obviously based on
2253 Net::OpenSSH.
2254
2255 SSH::Batch allows one to run remote commands in parallel in a cluster.
2256 It is build on top on "Net::OpenSSH" also.
2257
2258 Other Perl SSH clients: Net::SSH::Perl, Net::SSH2, Net::SSH,
2259 Net::SSH::Expect, Net::SCP, Net::SSH::Mechanize.
2260
2261 Net::OpenSSH::Compat is a package offering a set of compatibility
2262 layers for other SSH modules on top of Net::OpenSSH.
2263
2264 IPC::PerlSSH, GRID::Machine allow execution of Perl code in remote
2265 machines through SSH.
2266
2267 SSH::RPC implements an RPC mechanism on top of SSH using Net::OpenSSH
2268 to handle the connections.
2269
2270 Net::CLI::Interact allows one to interact with remote shells and other
2271 services. It is specially suited for interaction with network
2272 equipment. The phrasebook approach it uses is very clever. You may also
2273 like to check the other modules <https://metacpan.org/author/OLIVER>
2274 from its author, Oliver Gorwits.
2275
2277 Experimental features
2278 Object::Remote integration is highly experimental.
2279
2280 Support for tunnels targeting Unix sockets is highly experimental.
2281
2282 Support for the setpgrp feature is highly experimental.
2283
2284 Support for the gateway feature is highly experimental and mostly
2285 stalled.
2286
2287 Support for taint mode is experimental.
2288
2289 Known issues
2290 Net::OpenSSH does not work on Windows. OpenSSH multiplexing feature
2291 requires passing file handles through sockets, something that is not
2292 supported by any version of Windows.
2293
2294 It does not work on VMS either... well, probably, it does not work on
2295 anything not resembling a modern Linux/Unix OS.
2296
2297 Old versions of OpenSSH "ssh" may leave stdio streams in non-blocking
2298 mode. That can result on failures when writing to "STDOUT" or "STDERR"
2299 after using the module. In order to work-around this issue, Perl
2300 "fcntl" in perlfunc can be used to unset the non-blocking flag:
2301
2302 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
2303 my $flags = fcntl(STDOUT, F_GETFL, 0);
2304 fcntl(STDOUT, F_SETFL, $flags & ~O_NONBLOCK);
2305
2306 Reporting bugs and asking for help
2307 To report bugs send an email to the address that appear below or use
2308 the CPAN bug tracking system at <http://rt.cpan.org>.
2309
2310 Post questions related to how to use the module in PerlMonks
2311 <http://perlmonks.org/>, you will probably get faster responses than if
2312 you address me directly and I visit PerlMonks quite often, so I will
2313 see your question anyway.
2314
2315 Commercial support
2316 Commercial support, professional services and custom software
2317 development around this module are available through my current
2318 company. Drop me an email with a rough description of your requirements
2319 and we will get back to you ASAP.
2320
2321 My wishlist
2322 If you like this module and you are feeling generous, take a look at my
2323 Amazon Wish List: <http://amzn.com/w/1WU1P6IR5QZ42>.
2324
2325 Also consider contributing to the OpenSSH project this module builds
2326 upon: <http://www.openssh.org/donations.html>.
2327
2329 - Tests for "scp_*", "rsync_*" and "sftp" methods
2330
2331 - Make "pipe_in" and "pipe_out" methods "open_ex" based
2332
2333 - "auto_discard_streams" feature for mod_perl2 and similar environments
2334
2335 - Refactor open_ex support for multiple commands, maybe just keeping
2336 tunnel, ssh and raw
2337
2338 Send your feature requests, ideas or any feedback, please!
2339
2341 The source code of this module is hosted at GitHub:
2342 <http://github.com/salva/p5-Net-OpenSSH>.
2343
2344 Code contributions to the module are welcome but you should obey the
2345 following rules:
2346
2347 Only Perl 5.8.4 required
2348 Yes, that's pretty old, but Net::OpenSSH is intended to be also
2349 used by system administrators that sometimes have to struggle with
2350 old systems. The reason to pick 5.8.4 is that it has been the
2351 default perl on Solaris for a long time.
2352
2353 Avoid the "All the world's a Linux PC" syndrome
2354 The module should work on any (barely) sane Unix or Linux operating
2355 system. Specially, it should not be assumed that the over-featured
2356 GNU utilities and toolchain are available.
2357
2358 Dependencies are optional
2359 In order to make the module very easy to install, no mandatory
2360 dependencies on other CPAN modules are allowed.
2361
2362 Optional modules, that are loaded only on demand, are acceptable
2363 when they are used for adding new functionality (as it is done, for
2364 instance, with IO::Pty).
2365
2366 Glue code for integration with 3rd party modules is also allowed
2367 (as it is done with Expect).
2368
2369 Usage of language extension modules and alike is not acceptable.
2370
2371 Tests should be lax
2372 We don't want false negatives when testing. In case of doubt tests
2373 should succeed.
2374
2375 Also, in case of tests invoking some external program, it should be
2376 checked that the external program is available and that it works as
2377 expected or otherwise skip those tests.
2378
2379 Backward compatibility
2380 Nowadays Net::OpenSSH is quite stable and there are lots of scripts
2381 out there using it that we don't want to break, so, keeping the API
2382 backward compatible is a top priority.
2383
2384 Probably only security issues could now justify a backward
2385 incompatible change.
2386
2387 Follow my coding style
2388 Look at the rest of the code.
2389
2390 I let Emacs do the formatting for me using cperl-mode PerlStyle.
2391
2392 Talk to me
2393 Before making a large change or implementing a new feature get in
2394 touch with me.
2395
2396 I may have my own ideas about how things should be done. It is
2397 better if you know them before hand, otherwise, you risk getting
2398 your patch rejected.
2399
2400 Well, actually you should know that I am quite good at rejecting
2401 patches but it is not my fault!
2402
2403 Most of the patches I get are broken in some way: they don't follow the
2404 main module principles, sometimes the author didn't get the full
2405 picture and solved the issue in a short-sighted way, etc.
2406
2407 In any case, you should not be discouraged to contribute. Even if your
2408 patch is not applied directly, seeing how it solves your requirements
2409 or, in the case of bugs, the underlying problem analysis may be very
2410 useful and help me to do it... my way.
2411
2412 I always welcome documentation corrections and improvements.
2413
2415 Copyright (C) 2008-2018 by Salvador FandiƱo (sfandino@yahoo.com)
2416
2417 This library is free software; you can redistribute it and/or modify it
2418 under the same terms as Perl itself, either Perl version 5.10.0 or, at
2419 your option, any later version of Perl 5 you may have available.
2420
2421
2422
2423perl v5.28.0 2018-05-05 Net::OpenSSH(3)