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 $ssh->restart($async)
1173 Restarts the SSH session closing any open connection and creating a
1174 new one. Any open channel would also be killed.
1175
1176 Note that calling this method may request again the password or
1177 passphrase from the user.
1178
1179 In asynchronous mode, this method requires the connection to be
1180 terminated before it gets called. Afterwards, "wait_for_master"
1181 should be called repeaptly until the new connection is stablished.
1182
1183 my $async = 1;
1184 $ssh->disconnect($async);
1185 while (1) {
1186 defined $ssh->wait_for_master($async) # returns 0 when the
1187 # disconnect process
1188 # finishes
1189 and last;
1190 do_something_else();
1191 }
1192 $ssh->restart($async);
1193 while (1) {
1194 defined $ssh->wait_for_master($async)
1195 and last;
1196 do_somethin_else();
1197 }
1198
1199 $pid = $ssh->sshfs_import(\%opts, $remote_fs, $local_mnt_point)
1200 $pid = $ssh->sshfs_export(\%opts, $local_fs, $remote_mnt_point)
1201 These methods use sshfs(1) to import or export a file system
1202 through the SSH connection.
1203
1204 They return the $pid of the "sshfs" process or of the slave "ssh"
1205 process used to proxy it. Killing that process unmounts the file
1206 system, though, it may be probably better to use fusermount(1).
1207
1208 The options accepted are as follows:
1209
1210 ssh_opts => \@ssh_opts
1211 Options passed to the slave "ssh" process.
1212
1213 sshfs_opts => \@sshfs_opts
1214 Options passed to the "sshfs" command. For instance, to mount
1215 the file system in read-only mode:
1216
1217 my $pid = $ssh->sshfs_export({sshfs_opts => [-o => 'ro']},
1218 "/", "/mnt/foo");
1219
1220 Note that this command requires a recent version of "sshfs" to work
1221 (at the time of writing, it requires the yet unreleased version
1222 available from the FUSE git repository!).
1223
1224 See also the sshfs(1) man page and the "sshfs" and FUSE web sites
1225 at <https://github.com/libfuse/sshfs> and
1226 <https://github.com/libfuse/libfuse> respectively.
1227
1228 $or = $ssh->object_remote(@args)
1229 Returns an Object::Remote::Connection instance running on top of
1230 the Net::OpenSSH connection.
1231
1232 Example:
1233
1234 my $or = $ssh->object_remote;
1235 my $hostname = Sys::Hostname->can::on($or, 'hostname');
1236 say $hostname->();
1237
1238 See also Object::Remote.
1239
1240 $any = $ssh->any(%opts)
1241 Wraps the current object inside a Net::SSH::Any one.
1242
1243 Example:
1244
1245 my $any = $ssh->any;
1246 my $content = $any->scp_get_content("my-file.txt");
1247
1248 $pid = $ssh->disown_master
1249 Under normal operation Net::OpenSSH controls the life-time of the
1250 master "ssh" process and when the object is destroyed the master
1251 process and any connection running over it are terminated.
1252
1253 In some (rare) cases, it is desirable to let the master process and
1254 all the running connections survive. Calling this method does just
1255 that, it tells Net::OpenSSH object that the master process is not
1256 its own anymore.
1257
1258 The return value is the PID of the master process.
1259
1260 Note also that disowning the master process does not affect the
1261 operation of the module in any other regard.
1262
1263 For instance:
1264
1265 # See examples/sshfs_mount.pl for a working program
1266 my $ssh = Net::OpenSSH->new($host);
1267 my $sshfs_pid = $ssh->sshfs_import("/home/foo", "my-remote-home");
1268 $ssh->disown_master;
1269 $ssh->stop; # tells the master to stop accepting requests
1270 exit(0);
1271
1272 Shell quoting
1273 By default, when invoking remote commands, this module tries to mimic
1274 perl "system" builtin in regard to argument processing. Quoting
1275 "system" in perlfunc:
1276
1277 Argument processing varies depending on the number of arguments. If
1278 there is more than one argument in LIST, or if LIST is an array with
1279 more than one value, starts the program given by the first element
1280 of the list with arguments given by the rest of the list. If there
1281 is only one scalar argument, the argument is checked for shell
1282 metacharacters, and if there are any, the entire argument is passed
1283 to the system's command shell for parsing (this is "/bin/sh -c" on
1284 Unix platforms, but varies on other platforms).
1285
1286 Take for example Net::OpenSSH "system" method:
1287
1288 $ssh->system("ls -l *");
1289 $ssh->system('ls', '-l', '/');
1290
1291 The first call passes the argument unchanged to ssh and it is executed
1292 in the remote side through the shell which interprets metacharacters.
1293
1294 The second call escapes any shell metacharacters so that, effectively,
1295 it is equivalent to calling the command directly and not through the
1296 shell.
1297
1298 Under the hood, as the Secure Shell protocol does not provide for this
1299 mode of operation and always spawns a new shell where it runs the given
1300 command, Net::OpenSSH quotes any shell metacharacters in the command
1301 list.
1302
1303 All the methods that invoke a remote command (system, open_ex, etc.)
1304 accept the option "quote_args" that allows one to force/disable shell
1305 quoting.
1306
1307 For instance:
1308
1309 $ssh->system({quote_args => 1}, "/path with spaces/bin/foo");
1310
1311 will correctly handle the spaces in the program path.
1312
1313 The shell quoting mechanism implements some extensions (for instance,
1314 performing redirections to /dev/null on the remote side) that can be
1315 disabled with the option "quote_args_extended":
1316
1317 $ssh->system({ stderr_discard => 1,
1318 quote_args => 1, quote_args_extended => 0 },
1319 @cmd);
1320
1321 The option "quote_args" can also be used to disable quoting when more
1322 than one argument is passed. For instance, to get some pattern expanded
1323 by the remote shell:
1324
1325 $ssh->system({quote_args => 0}, 'ls', '-l', "/tmp/files_*.dat");
1326
1327 The method "shell_quote" can be used to selectively quote some
1328 arguments and leave others untouched:
1329
1330 $ssh->system({quote_args => 0},
1331 $ssh->shell_quote('ls', '-l'),
1332 "/tmp/files_*.dat");
1333
1334 When the glob option is set in "scp" and "rsync" file transfer methods,
1335 an alternative quoting method which knows about file wildcards and
1336 passes them unquoted is used. The set of wildcards recognized currently
1337 is the one supported by bash(1).
1338
1339 Another way to selectively use quote globing or fully disable quoting
1340 for some specific arguments is to pass them as scalar references or
1341 double scalar references respectively. In practice, that means
1342 prepending them with one or two backslashes. For instance:
1343
1344 # quote the last argument for globing:
1345 $ssh->system('ls', '-l', \'/tmp/my files/filed_*dat');
1346
1347 # append a redirection to the remote command
1348 $ssh->system('ls', '-lR', \\'>/tmp/ls-lR.txt');
1349
1350 # expand remote shell variables and glob in the same command:
1351 $ssh->system('tar', 'czf', \\'$HOME/out.tgz', \'/var/log/server.*.log');
1352
1353 As shell quoting is a tricky matter, I expect bugs to appear in this
1354 area. You can see how "ssh" is called, and the quoting used setting the
1355 following debug flag:
1356
1357 $Net::OpenSSH::debug |= 16;
1358
1359 By default, the module assumes the remote shell is some variant of a
1360 POSIX or Bourne shell ("bash", "dash", "ksh", etc.). If this is not the
1361 case, the construction option "remote_shell" can be used to select an
1362 alternative quoting mechanism.
1363
1364 For instance:
1365
1366 $ssh = Net::OpenSSH->new($host, remote_shell => 'csh');
1367 $ssh->system(echo => "hard\n to\n quote\n argument!");
1368
1369 Currently there are quoters available for POSIX (Bourne) compatible
1370 shells, "csh" and the two Windows variants "MSWin" (for servers using
1371 Win32::CreateProcess, see Net::OpenSSH::ShellQuoter::MSWin) and "MSCmd"
1372 (for servers using "cmd.exe", see Net::OpenSSH::ShellQuoter::MSCmd).
1373
1374 In any case, you can always do the quoting yourself and pass the quoted
1375 remote command as a single string:
1376
1377 # for VMS
1378 $ssh->system('DIR/SIZE NFOO::USERS:[JSMITH.DOCS]*.TXT;0');
1379
1380 Note that the current quoting mechanism does not handle possible
1381 aliases defined by the remote shell. In that case, to force execution
1382 of the command instead of the alias, the full path to the command must
1383 be used.
1384
1385 Timeouts
1386 In order to stop remote processes when they timeout, the ideal approach
1387 would be to send them signals through the SSH connection as specified
1388 by the protocol standard.
1389
1390 Unfortunately OpenSSH does not implement that feature so Net::OpenSSH
1391 has to use other imperfect approaches:
1392
1393 ā¢ close slave I/O streams
1394
1395 Closing the STDIN and STDOUT streams of the unresponsive remote
1396 process will effectively deliver a SIGPIPE when it tries to access
1397 any of them.
1398
1399 Remote processes may not access STDIN or STDOUT and even then,
1400 Net::OpenSSH can only close these channels when it is capturing
1401 them, so this approach does not always work.
1402
1403 ā¢ killing the local SSH slave process
1404
1405 This action may leave the remote process running, creating a remote
1406 orphan so Net::OpenSSH does not use it unless the construction
1407 option "kill_ssh_on_timeout" is set.
1408
1409 Luckily, future versions of OpenSSH will support signaling remote
1410 processes via the mux channel.
1411
1412 Variable expansion
1413 The variable expansion feature allows one to define variables that are
1414 expanded automatically inside command arguments and file paths.
1415
1416 This feature is disabled by default. It is intended to be used with
1417 Net::OpenSSH::Parallel and other similar modules.
1418
1419 Variables are delimited by a pair of percent signs ("%"), for instance
1420 "%HOST%". Also, two consecutive percent signs are replaced by a single
1421 one.
1422
1423 The special variables "HOST", "USER" and "PORT" are maintained
1424 internally by the module and take the obvious values.
1425
1426 Variable expansion is performed before shell quoting (see "Shell
1427 quoting").
1428
1429 Some usage example:
1430
1431 my $ssh = Net::OpenSSH->new('server.foo.com', expand_vars => 1);
1432 $ssh->set_var(ID => 42);
1433 $ssh->system("ls >/tmp/ls.out-%HOST%-%ID%");
1434
1435 will redirect the output of the "ls" command to
1436 "/tmp/ls.out-server.foo.com-42" on the remote host.
1437
1438 Tunnels
1439 Besides running commands on the remote host, Net::OpenSSH also allows
1440 one to tunnel TCP connections to remote machines reachable from the SSH
1441 server.
1442
1443 That feature is made available through the "tunnel" option of the
1444 "open_ex" method, and also through wrapper methods "open_tunnel" and
1445 "capture_tunnel" and most others where it makes sense.
1446
1447 Example:
1448
1449 $ssh->system({tunnel => 1,
1450 stdin_data => "GET / HTTP/1.0\r\n\r\n",
1451 stdout_file => "/tmp/$server.res"},
1452 $server, 80)
1453 or die "unable to retrieve page: " . $ssh->error;
1454
1455 or capturing the output of several requests in parallel:
1456
1457 my @pids;
1458 for (@servers) {
1459 my $pid = $ssh->spawn({tunnel => 1,
1460 stdin_file => "/tmp/request.req",
1461 stdout_file => "/tmp/$_.res"},
1462 $_, 80);
1463 if ($pid) {
1464 push @pids, $pid;
1465 }
1466 else {
1467 warn "unable to spawn tunnel process to $_: " . $ssh->error;
1468 }
1469 }
1470 waitpid ($_, 0) for (@pids);
1471
1472 Under the hood, in order to create a tunnel, a new "ssh" process is
1473 spawned with the option "-W${address}:${port}" (available from OpenSSH
1474 5.4 and upwards) making it redirect its stdio streams to the remote
1475 given address. Unlike when "ssh" "-L" options is used to create
1476 tunnels, no TCP port is opened on the local machine at any time so this
1477 is a perfectly secure operation.
1478
1479 The PID of the new process is returned by the named methods. It must be
1480 reaped once the pipe or socket handlers for the local side of the
1481 tunnel have been closed.
1482
1483 OpenSSH 5.4 or later is required for the tunnels functionality to work.
1484 Also, note that tunnel forwarding may be administratively forbidden at
1485 the server side (see sshd(8) and sshd_config(5) or the documentation
1486 provided by your SSH server vendor).
1487
1488 Tunnels targeting UNIX sockets
1489
1490 When connecting to hosts running a recent version of OpenSSH sshd, it
1491 is also possible to open connections targeting Unix sockets.
1492
1493 For instance:
1494
1495 my $response = $ssh->capture({tunnel => 1, stdin_data => $request },
1496 "/tmp/socket-foo");
1497
1498 Currently, this feature requires a patched OpenSSH ssh client. The
1499 patch is available as
1500 "patches/openssh-fwd-stdio-to-streamlocal-1.patch".
1501
1502 Port forwarding
1503
1504 Net::OpenSSH does not offer direct support for handling port
1505 forwardings between server and client. But that can be done easily
1506 anyway passing custom SSH options to its methods.
1507
1508 For instance, tunnel creation options can be passed to the constructor:
1509
1510 my $ssh = Net::OpenSSH->new(...
1511 master_opts => -Llocalhost:1234:localhost:3306');
1512
1513 The port forwardings can also be changed for a running SSH connection
1514 using a Control command:
1515
1516 # setting up a tunnel:
1517 $ssh->system({ssh_opts => ['-O','forward',
1518 '-L127.0.0.1:12345:127.0.0.1:3306']});
1519
1520 # canceling it:
1521 $ssh->system({ssh_opts => ['-O', 'cancel',
1522 '-L127.0.0.1:12345:127.0.0.1:3306']});
1523
1524 Data encoding
1525 Net::OpenSSH has some support for transparently converting the data
1526 send or received from the remote server to Perl internal unicode
1527 representation.
1528
1529 The methods supporting that feature are those that move data from/to
1530 Perl data structures (e.g. "capture", "capture2", "capture_tunnel" and
1531 methods supporting the "stdin_data" option). Data accessed through
1532 pipes, sockets or redirections is not affected by the encoding options.
1533
1534 It is also possible to set the encoding of the command and arguments
1535 passed to the remote server on the command line.
1536
1537 By default, if no encoding option is given on the constructor or on the
1538 method calls, Net::OpenSSH will not perform any encoding
1539 transformation, effectively processing the data as "latin1".
1540
1541 When data can not be converted between the Perl internal representation
1542 and the selected encoding inside some Net::OpenSSH method, it will fail
1543 with an "OSSH_ENCODING_ERROR" error.
1544
1545 The supported encoding options are as follows:
1546
1547 stream_encoding => $encoding
1548 sets the encoding of the data send and received on capture methods.
1549
1550 argument_encoding => $encoding
1551 sets the encoding of the command line arguments
1552
1553 encoding => $encoding
1554 sets both "argument_encoding" and "stream_encoding".
1555
1556 The constructor also accepts "default_encoding",
1557 "default_stream_encoding" and "default_argument_encoding" that set the
1558 defaults.
1559
1560 Diverting "new"
1561 When a code ref is installed at $Net::OpenSSH::FACTORY, calls to new
1562 will be diverted through it.
1563
1564 That feature can be used to transparently implement connection caching,
1565 for instance:
1566
1567 my $old_factory = $Net::OpenSSH::FACTORY;
1568 my %cache;
1569
1570 sub factory {
1571 my ($class, %opts) = @_;
1572 my $signature = join("\0", $class, map { $_ => $opts{$_} }, sort keys %opts);
1573 my $old = $cache{signature};
1574 return $old if ($old and $old->error != OSSH_MASTER_FAILED);
1575 local $Net::OpenSSH::FACTORY = $old_factory;
1576 $cache{$signature} = $class->new(%opts);
1577 }
1578
1579 $Net::OpenSSH::FACTORY = \&factory;
1580
1581 ... and I am sure it can be abused in several other ways!
1582
1584 Expect
1585 Sometimes you would like to use Expect to control some program running
1586 in the remote host. You can do it as follows:
1587
1588 my ($pty, $pid) = $ssh->open2pty(@cmd)
1589 or die "unable to run remote command @cmd";
1590 my $expect = Expect->init($pty);
1591
1592 Then, you will be able to use the new Expect object in $expect as
1593 usual.
1594
1595 Net::Telnet
1596 This example is adapted from Net::Telnet documentation:
1597
1598 my ($pty, $pid) = $ssh->open2pty({stderr_to_stdout => 1})
1599 or die "unable to start remote shell: " . $ssh->error;
1600 my $telnet = Net::Telnet->new(-fhopen => $pty,
1601 -prompt => '/.*\$ $/',
1602 -telnetmode => 0,
1603 -cmd_remove_mode => 1,
1604 -output_record_separator => "\r");
1605
1606 $telnet->waitfor(-match => $telnet->prompt,
1607 -errmode => "return")
1608 or die "login failed: " . $telnet->lastline;
1609
1610 my @lines = $telnet->cmd("who");
1611
1612 ...
1613
1614 $telnet->close;
1615 waitpid($pid, 0);
1616
1617 mod_perl and mod_perl2
1618 mod_perl and mod_perl2 tie STDIN and STDOUT to objects that are not
1619 backed up by real file descriptors at the operating system level.
1620 Net::OpenSSH will fail if any of these handles is used explicitly or
1621 implicitly when calling some remote command.
1622
1623 The work-around is to redirect them to "/dev/null" or to some file:
1624
1625 open my $def_in, '<', '/dev/null' or die "unable to open /dev/null";
1626 my $ssh = Net::OpenSSH->new($host,
1627 default_stdin_fh => $def_in);
1628
1629 my $out = $ssh->capture($cmd1);
1630 $ssh->system({stdout_discard => 1}, $cmd2);
1631 $ssh->system({stdout_to_file => '/tmp/output'}, $cmd3);
1632
1633 Also, note that from a security stand point, running "ssh" from inside
1634 the web server process is not a great idea. An attacker exploiting some
1635 Apache bug would be able to access the SSH keys and passwords and gain
1636 unlimited access to the remote systems.
1637
1638 If you can, use a queue (as TheSchwartz) or any other mechanism to
1639 execute the ssh commands from another process running under a different
1640 user account.
1641
1642 At a minimum, ensure that "~www-data/.ssh" (or similar) is not
1643 accessible through the web server!
1644
1645 Net::SFTP::Foreign
1646 See method "sftp".
1647
1648 Net::SSH::Any
1649 See method "any".
1650
1651 Object::Remote
1652 See method "object_remote".
1653
1654 AnyEvent (and similar frameworks)
1655 Net::OpenSSH provides all the functionality required to be integrated
1656 inside event oriented programming framework such as AnyEvent or
1657 IO::Async in the following way:
1658
1659 1. Create a disconnected Net::OpenSSH object:
1660 my $ssh = Net::OpenSSH->new($host, async => 1, ...);
1661
1662 2. Let the object connect to the remote host:
1663 Use a timer to call the "wait_for_master" method in async mode
1664 repeatedly until it returns a true value indicating success.
1665
1666 Also, the object error state needs to be checked after every call
1667 in order to detect failed connections. For instance:
1668
1669 my $ssh = Net::OpenSSH->new(..., async => 1);
1670 my $w;
1671 $w = AE::timer 0.1, 0.1, sub {
1672 if ($ssh->wait_for_master(1)) {
1673 # the connection has been established!
1674 # remote commands can be run now
1675 undef $w;
1676 on_ssh_success(...);
1677 }
1678 elsif ($ssh->error) {
1679 # connection can not be established
1680 undef $w;
1681 on_ssh_failure(...);
1682 }
1683 }
1684
1685 3. Use the event framework to launch the remote processes:
1686 Call Net::OpenSSH "make_remote_command" to construct commands which
1687 can be run using the framework regular facilities for launching
1688 external commands.
1689
1690 Error checking should also be performed at this point because the
1691 SSH connection could be broken.
1692
1693 For instance:
1694
1695 if (defined(my $cmd = $ssh->make_remote_command(echo => 'hello!')) {
1696 AnyEvent::Util::run_cmd($cmd, %run_cmd_opts);
1697 }
1698 else {
1699 # something went wrong!
1700 }
1701
1702 Alternatively, any of the "open*" methods provided by Net::OpenSSH
1703 could also be used to launch remote commands.
1704
1705 4. When finished, disconnect asynchronously
1706 After initiating an asynchronous disconnect with disconnect(1),
1707 repeatedly call "wait_for_master" until you get a defined but false
1708 value:
1709
1710 $ssh->disconnect(1);
1711
1712 my $w; $w = AE::timer 0.1, 0.1, sub {
1713 my $res = $ssh->wait_for_master(1);
1714
1715 if (defined $res && !$res) {
1716 undef $w;
1717 undef $ssh;
1718 }
1719 };
1720
1721 Be careful not to let the $ssh object go out of scope until the
1722 disconnection has finished, otherwise its destructor will wait and
1723 block your program until the disconnection has completed.
1724
1725 Other modules
1726 CPAN contains several modules that rely on SSH to perform their duties
1727 as for example IPC::PerlSSH or GRID::Machine.
1728
1729 Often, it is possible to instruct them to go through a Net::OpenSSH
1730 multiplexed connection employing some available constructor option. For
1731 instance:
1732
1733 use Net::OpenSSH;
1734 use IPC::PerlIPC;
1735 my $ssh = Net::OpenSSH->new(...);
1736 $ssh->error and die "unable to connect to remote host: " . $ssh->error;
1737 my @cmd = $ssh->make_remote_command('/usr/bin/perl');
1738 my $ipc = IPC::PerlSSH->new(Command => \@cmd);
1739 my @r = $ipc->eval('...');
1740
1741 or...
1742
1743 use GRID::Machine;
1744 ...
1745 my @cmd = $ssh->make_remote_command('/usr/bin/perl');
1746 my $grid = GRID::Machine->new(command => \@cmd);
1747 my $r = $grid->eval('print "hello world!\n"');
1748
1749 In other cases, some kind of plugin mechanism is provided by the 3rd
1750 party modules to allow for different transports. The method "open2" may
1751 be used to create a pair of pipes for transport in these cases.
1752
1754 Usually, Net::OpenSSH works out of the box, but when it fails, some
1755 users have a hard time finding the cause of the problem. This mini
1756 troubleshooting guide should help you to find and solve it.
1757
1758 1 - check the error message
1759 Add in your script, after the Net::OpenSSH constructor call, an
1760 error check:
1761
1762 $ssh = Net::OpenSSH->new(...);
1763 $ssh->error and die "SSH connection failed: " . $ssh->error;
1764
1765 The error message will tell what has gone wrong.
1766
1767 2 - Check the connection parameters
1768 Believe it or not, passing bad parameters to Net::OpenSSH turns to
1769 be one of the top causes of failures so check that you are using
1770 the right parameters.
1771
1772 Specifically, if you are obtaining them from the outside, ensure
1773 that they don't have extra spaces or new lines attached (do you
1774 need to "chomp"?).
1775
1776 Passwords and URIs may contain "$" or "@" characters. If you have
1777 then hardcoded in your script, check that those are quoted properly
1778 (and BTW, use "strict").
1779
1780 3 - OpenSSH version
1781 Ensure that you have a version of "ssh" recent enough:
1782
1783 $ ssh -V
1784 OpenSSH_5.1p1 Debian-5, OpenSSL 0.9.8g 19 Oct 2007
1785
1786 OpenSSH version 4.1 was the first to support the multiplexing
1787 feature and is the minimal required by the module to work. I advise
1788 you to use the latest OpenSSH (currently 7.5).
1789
1790 The "ssh_cmd" constructor option lets you select the "ssh" binary
1791 to use. For instance:
1792
1793 $ssh = Net::OpenSSH->new($host,
1794 ssh_cmd => "/opt/OpenSSH/5.8/bin/ssh")
1795
1796 Some hardware vendors (e.g. Sun, err... Oracle) include custom
1797 versions of OpenSSH bundled with the operating system. In
1798 principle, Net::OpenSSH should work with these SSH clients as long
1799 as they are derived from some version of OpenSSH recent enough.
1800 Anyway, my advise is to use the real OpenSSH software if you can!
1801
1802 4 - run ssh from the command line
1803 Check you can connect to the remote host using the same parameters
1804 you are passing to Net::OpenSSH. In particular, ensure that you are
1805 running "ssh" as the same local user.
1806
1807 If you are running your script from a web server, the user would
1808 probably be "www", "apache" or something alike.
1809
1810 Common problems are:
1811
1812 ā¢ Remote host public key not present in known_hosts file.
1813
1814 The SSH protocol uses public keys to identify the remote hosts
1815 so that they can not be supplanted by some malicious third
1816 parties.
1817
1818 For OpenSSH, usually the server public key is stored in
1819 "/etc/ssh/ssh_host_dsa_key.pub" or in
1820 "/etc/ssh/ssh_host_rsa_key.pub" and that key should be copied
1821 into the "~/.ssh/known_hosts" file in the local machine (other
1822 SSH implementations may use other file locations).
1823
1824 Maintaining the server keys when several hosts and clients are
1825 involved may be somewhat inconvenient, so most SSH clients, by
1826 default, when a new connection is established to a host whose
1827 key is not in the "known_hosts" file, show the key and ask the
1828 user if he wants the key copied there.
1829
1830 ā¢ Wrong remote host public key in known_hosts file.
1831
1832 This is another common problem that happens when some server is
1833 replaced or reinstalled from scratch and its public key changes
1834 becoming different to that installed on the "known_hosts" file.
1835
1836 The easiest way to solve that problem is to remove the old key
1837 from the "known_hosts" file by hand using any editor and then
1838 to connect to the server replying "yes" when asked to save the
1839 new key.
1840
1841 ā¢ Wrong permissions for the "~/.ssh" directory or its contents.
1842
1843 OpenSSH client performs several checks on the access
1844 permissions of the "~/.ssh" directory and its contents and
1845 refuses to use them when misconfigured. See the FILES section
1846 from the ssh(1) man page.
1847
1848 ā¢ Incorrect settings for password or public key authentication.
1849
1850 Check that you are using the right password or that the user
1851 public key is correctly installed on the server.
1852
1853 5 - security checks on the multiplexing socket
1854 Net::OpenSSH performs some security checks on the directory where
1855 the multiplexing socket is going to be placed to ensure that it can
1856 not be accessed by other users.
1857
1858 The default location for the multiplexing socket is under
1859 "~/.libnet-openssh-perl". It can be changed using the "ctl_dir" and
1860 "ctl_path" constructor arguments.
1861
1862 The requirements for that directory and all its parents are:
1863
1864 ā¢ They have to be owned by the user executing the script or by
1865 root
1866
1867 ā¢ Their permission masks must be 0755 or more restrictive, so
1868 nobody else has permissions to perform write operations on
1869 them.
1870
1871 The constructor option "strict_mode" disables these security
1872 checks, but you should not use it unless you understand its
1873 implications.
1874
1875 6 - file system must support sockets
1876 Some file systems (as for instance FAT or AFS) do not support
1877 placing sockets inside them.
1878
1879 Ensure that the "ctl_dir" path does not lay into one of those file
1880 systems.
1881
1883 Debugging of Net::OpenSSH internals is controlled through the variable
1884 $Net::OpenSSH::debug. Every bit of this variable activates debugging of
1885 some subsystem as follows:
1886
1887 bit 1 - errors
1888 Dumps changes on the internal object attribute where errors are
1889 stored.
1890
1891 bit 2 - ctl_path
1892 Dumps information about ctl_path calculation and the tests
1893 performed on that directory in order to decide if it is secure to
1894 place the multiplexing socket inside.
1895
1896 bit 4 - connecting
1897 Dumps information about the establishment of new master
1898 connections.
1899
1900 bit 8 - commands and arguments
1901 Dumps the command and arguments for every system/exec call.
1902
1903 bit 16 - command execution
1904 Dumps information about the progress of command execution.
1905
1906 bit 32 - destruction
1907 Dumps information about the destruction of Net::OpenSSH objects and
1908 the termination of the SSH master processes.
1909
1910 bit 64 - IO loop
1911 Dumps information about the progress of the IO loop on capture
1912 operations.
1913
1914 bit 128 - IO hexdumps
1915 Generates hexdumps of the information that travels through the SSH
1916 streams inside capture operations.
1917
1918 bit 512 - OS tracing of the master process
1919 Use the module Net::OpenSSH::OSTracer to trace the SSH master
1920 process at the OS level.
1921
1922 For instance, in order to activate all the debugging flags, you can
1923 use:
1924
1925 $Net::OpenSSH::debug = ~0;
1926
1927 Note that the meaning of the flags and the information generated is
1928 only intended for debugging of the module and may change without notice
1929 between releases.
1930
1931 If you are using password authentication, enabling debugging for
1932 IO::Tty may also show interesting information:
1933
1934 $IO::Tty::DEBUG = 1;
1935
1936 Finally, by default debugging output is sent to "STDERR". You can
1937 override it pointing $Net::OpenSSH::debug_fh to a different file
1938 handle. For instance:
1939
1940 BEGIN {
1941 open my $out, '>', '/tmp/debug.txt' or warn $!;
1942 $Net::OpenSSH::debug_fh = $out;
1943 $Net::OpenSSH::debug = -1;
1944 }
1945
1947 Q: Is this module secure?
1948
1949 A: Well, it tries to be!
1950
1951 From a security standpoint the aim of this module is to be as secure as
1952 OpenSSH, your operating system, your shell and in general your
1953 environment allow it to be.
1954
1955 It does not take any shortcut just to make your life easier if that
1956 means lowering the security level (for instance, disabling
1957 "StrictHostKeyChecking" by default).
1958
1959 In code supporting features that are not just proxied to OpenSSH, the
1960 module tries to keep the same standards of security as OpenSSH (for
1961 instance, checking directory and file permissions when placing the
1962 multiplexing socket).
1963
1964 On the other hand, and keeping with OpenSSH philosophy, the module lets
1965 you disable most (all?) of those security measures. But just because it
1966 lets you do it it doesn't mean it is a good idea to do so!!!
1967
1968 If you are a novice programmer or SSH user, and googling you have just
1969 found some flag that you don't understand but that seems to magically
1970 solve your connection problems... well, believe me, it is probably a
1971 bad idea to use it. Ask somebody how really knows first!
1972
1973 Just to make thinks clear, if your code contains any of the keywords
1974 from the (non-exclusive) list below and you don't know why, you are
1975 probably wrecking the security of the SSH protocol:
1976
1977 strict_mode
1978 StrictHostKeyChecking
1979 UserKnownHostsFile
1980
1981 Other considerations related to security you may like to know are as
1982 follows:
1983
1984 Taint mode
1985 The module supports working in taint mode.
1986
1987 If you are in an exposed environment, you should probably enable it
1988 for your script in order to catch any unchecked command for being
1989 executed in the remote side.
1990
1991 Web environments
1992 It is a bad idea to establish SSH connections from your webserver
1993 because if it becomes compromised in any way, the attacker would be
1994 able to use the credentials from your script to connect to the
1995 remote host and do anything he wishes there.
1996
1997 Command quoting
1998 The module can quote commands and arguments for you in a flexible
1999 and powerful way.
2000
2001 This is a feature you should use as it reduces the possibility of
2002 some attacker being able to inject and run arbitrary commands on
2003 the remote machine (and even for scripts that are not exposed it is
2004 always advisable to enable argument quoting).
2005
2006 Having said that, take into consideration that argument-quoting is
2007 just a hack to emulate the invoke-without-a-shell feature of Perl
2008 builtins such as "system" and alike. There may be bugs(*) on the
2009 quoting code, your particular shell may have different quoting
2010 rules with unhandled corner cases or whatever. If your script is
2011 exposed to the outside, you should check your inputs and restrict
2012 what you accept as valid.
2013
2014 [* even if this is one of the parts of the module more intensively
2015 tested!]
2016
2017 Shellshock
2018 (see Shellshock
2019 <http://en.wikipedia.org/wiki/Shellshock_%28software_bug%29>)
2020
2021 When executing local commands, the module always avoids calling the
2022 shell so in this way it is not affected by Shellshock.
2023
2024 Unfortunately, some commands ("scp", "rsync" and "ssh" when the
2025 "ProxyCommand" option is used) invoke other commands under the hood
2026 using the user shell. That opens the door to local Shellshock
2027 exploitation.
2028
2029 On the remote side invocation of the shell is unavoidable due to
2030 the protocol design.
2031
2032 By default, SSH does not forward environment variables but some
2033 Linux distributions explicitly change the default OpenSSH
2034 configuration to enable forwarding and acceptance of some specific
2035 ones (for instance "LANG" and "LC_*" on Debian and derivatives,
2036 Fedora does alike) and this also opens the door to Shellshock
2037 exploitation.
2038
2039 Note that the shell used to invoke commands is not "/bin/sh" but
2040 the user shell as configured in "/etc/passwd", PAM or whatever
2041 authentication subsystem is used by the local or remote operating
2042 system. Debian users, don't think you are not affected because your
2043 "/bin/sh" points to "dash"!
2044
2046 Frequent questions about the module:
2047
2048 Connecting to switches, routers, etc.
2049 Q: I can not get the method "system", "capture", etc., to work when
2050 connecting to some router, switch, etc. What I am doing wrong?
2051
2052 A: Roughly, the SSH protocol allows for two modes of operation:
2053 command mode and interactive mode.
2054
2055 Command mode is designed to run single commands on the remote host.
2056 It opens a SSH channel between both hosts, asks the remote computer
2057 to run some given command and when it finishes, the channel is
2058 closed. It is what you get, for instance, when you run something
2059 as...
2060
2061 $ ssh my.unix.box cat foo.txt
2062
2063 ... and it is also the way Net::OpenSSH runs commands on the remote
2064 host.
2065
2066 Interactive mode launches a shell on the remote hosts with its
2067 stdio streams redirected to the local ones so that the user can
2068 transparently interact with it.
2069
2070 Some devices (as probably the one you are using) do not run an
2071 standard, general purpose shell (e.g. "bash", "csh" or "ksh") but
2072 some custom program specially targeted and limited to the task of
2073 configuring the device.
2074
2075 Usually, the SSH server running on these devices does not support
2076 command mode. It unconditionally attaches the restricted shell to
2077 any incoming SSH connection and waits for the user to enter
2078 commands through the redirected stdin stream.
2079
2080 The only way to work-around this limitation is to make your script
2081 talk to the restricted shell (1-open a new SSH session, 2-wait for
2082 the shell prompt, 3-send a command, 4-read the output until you get
2083 to the shell prompt again, repeat from 3). The best tool for this
2084 task is probably Expect, used alone or combined with Net::OpenSSH
2085 (see "Expect").
2086
2087 There are some devices that support command mode but that only
2088 accept one command per connection. In that cases, using Expect is
2089 also probably the best option.
2090
2091 Nowadays, there is a new player, Net::CLI::Interact that may be
2092 more suitable than Expect, and Net::Appliance::Session for working
2093 specifically with network devices.
2094
2095 Connection fails
2096 Q: I am unable to make the module connect to the remote host...
2097
2098 A: Have you read the troubleshooting section? (see
2099 "TROUBLESHOOTING").
2100
2101 Disable StrictHostKeyChecking
2102 Q: Why is "ssh" not run with "StrictHostKeyChecking=no"?
2103
2104 A: Using "StrictHostKeyChecking=no" relaxes the default security
2105 level of SSH and it will be relatively easy to end with a
2106 misconfigured SSH (for instance, when "known_hosts" is unwritable)
2107 that could be forged to connect to a bad host in order to perform
2108 man-in-the-middle attacks, etc.
2109
2110 I advice you to do not use that option unless you fully understand
2111 its implications from a security point of view.
2112
2113 If you want to use it anyway, past it to the constructor:
2114
2115 $ssh = Net::OpenSSH->new($host,
2116 master_opts => [-o => "StrictHostKeyChecking=no"],
2117 ...);
2118
2119 child process STDIN/STDOUT/STDERR is not a real system file handle
2120 Q: Calls to "system", "capture", etc. fail with the previous error,
2121 what's happening?
2122
2123 A: The reported stdio stream is closed or is not attached to a real
2124 file handle (e.g. it is a tied handle). Redirect it to "/dev/null"
2125 or to a real file:
2126
2127 my $out = $ssh->capture({stdin_discard => 1, stderr_to_stdout => 1},
2128 $cmd);
2129
2130 See also the mod_perl entry above.
2131
2132 Solaris (and AIX and probably others)
2133 Q: I was trying Net::OpenSSH on Solaris and seem to be running into
2134 an issue...
2135
2136 A: The SSH client bundled with Solaris is an early fork of OpenSSH
2137 that does not provide the multiplexing functionality required by
2138 Net::OpenSSH. You will have to install the OpenSSH client.
2139
2140 Precompiled packages are available from Sun Freeware
2141 (<http://www.sunfreeware.com>). There, select your OS version an
2142 CPU architecture, download the OpenSSH package and its dependencies
2143 and install them. Note that you do not need to configure Solaris to
2144 use the OpenSSH server "sshd".
2145
2146 Ensure that OpenSSH client is in your path before the system "ssh"
2147 or alternatively, you can hardcode the full path into your scripts
2148 as follows:
2149
2150 $ssh = Net::OpenSSH->new($host,
2151 ssh_cmd => '/usr/local/bin/ssh');
2152
2153 AIX and probably some other unixen, also bundle SSH clients lacking
2154 the multiplexing functionality and require installation of the real
2155 OpenSSH.
2156
2157 Can not change working directory
2158 Q: I want to run some command inside a given remote directory but I
2159 am unable to change the working directory. For instance:
2160
2161 $ssh->system('cd /home/foo/bin');
2162 $ssh->systen('ls');
2163
2164 does not list the contents of "/home/foo/bin".
2165
2166 What am I doing wrong?
2167
2168 A: Net::OpenSSH (and, for that matter, all the SSH modules
2169 available from CPAN but Net::SSH::Expect) run every command in a
2170 new session so most shell builtins that are run for its side
2171 effects become useless (e.g. "cd", "export", "ulimit", "umask",
2172 etc., usually, you can list them running "help" from the shell).
2173
2174 A work around is to combine several commands in one, for instance:
2175
2176 $ssh->system('cd /home/foo/bin && ls');
2177
2178 Note the use of the shell "&&" operator instead of ";" in order to
2179 abort the command as soon as any of the subcommands fail.
2180
2181 Also, several commands can be combined into one while still using
2182 the multi-argument quoting feature as follows:
2183
2184 $ssh->system(@cmd1, \\'&&', @cmd2, \\'&&', @cmd3, ...);
2185
2186 Running detached remote processes
2187 Q: I need to be able to ssh into several machines from my script,
2188 launch a process to run in the background there, and then return
2189 immediately while the remote programs keep running...
2190
2191 A: If the remote systems run some Unix/Linux variant, the right
2192 approach is to use nohup(1) that will disconnect the remote process
2193 from the stdio streams and to ask the shell to run the command on
2194 the background. For instance:
2195
2196 $ssh->system("nohup $long_running_command &");
2197
2198 Also, it may be possible to demonize the remote program. If it is
2199 written in Perl you can use App::Daemon for that (actually, there
2200 are several CPAN modules that provided that kind of functionality).
2201
2202 In any case, note that you should not use "spawn" for that.
2203
2204 MaxSessions server limit reached
2205 Q: I created an $ssh object and then fork a lot children processes
2206 which use this object. When the children number is bigger than
2207 "MaxSessions" as defined in sshd configuration (defaults to 10),
2208 trying to fork new remote commands will prompt the user for the
2209 password.
2210
2211 A: When the slave SSH client gets a response from the remote
2212 servers saying that the maximum number of sessions for the current
2213 connection has been reached, it fall backs to open a new direct
2214 connection without going through the multiplexing socket.
2215
2216 To stop that for happening, the following hack can be used:
2217
2218 $ssh = Net::OpenSSH->new(host,
2219 default_ssh_opts => ['-oConnectionAttempts=0'],
2220 ...);
2221
2222 Running remote commands with sudo
2223 Q: How can I run remote commands using "sudo" to become root first?
2224
2225 A: The simplest way is to tell "sudo" to read the password from
2226 stdin with the "-S" flag and to do not use cached credentials with
2227 the "-k" flag. You may also like to use the "-p" flag to tell
2228 "sudo" to print an empty prompt. For instance:
2229
2230 my @out = $ssh->capture({ stdin_data => "$sudo_passwd\n" },
2231 'sudo', '-Sk',
2232 '-p', '',
2233 '--',
2234 @cmd);
2235
2236 If the version of sudo installed on the remote host does not
2237 support the "-S" flag (it tells sudo to read the password from its
2238 STDIN stream), you can do it as follows:
2239
2240 my @out = $ssh->capture({ tty => 1,
2241 stdin_data => "$sudo_passwd\n" },
2242 'sudo', '-k',
2243 '-p', '',
2244 '--',
2245 @cmd);
2246
2247 This may generate an spurious and harmless warning from the SSH
2248 master connection (because we are requesting allocation of a tty on
2249 the remote side and locally we are attaching it to a regular pair
2250 of pipes).
2251
2252 If for whatever reason the methods described above fail, you can
2253 always revert to using Expect to talk to the remote "sudo". See the
2254 "examples/expect.pl" script from this module distribution.
2255
2257 OpenSSH client documentation ssh(1), ssh_config(5), the project web
2258 <http://www.openssh.org> and its FAQ
2259 <http://www.openbsd.org/openssh/faq.html>. scp(1) and rsync(1). The
2260 OpenSSH Wikibook <http://en.wikibooks.org/wiki/OpenSSH>.
2261
2262 Net::OpenSSH::Gateway for detailed instruction about how to get this
2263 module to connect to hosts through proxies and other SSH gateway
2264 servers.
2265
2266 Core perl documentation perlipc, "open" in perlfunc, "waitpid" in
2267 perlfunc.
2268
2269 IO::Pty to known how to use the pseudo tty objects returned by several
2270 methods on this package.
2271
2272 Net::SFTP::Foreign provides a compatible SFTP implementation.
2273
2274 Expect can be used to interact with commands run through this module on
2275 the remote machine (see also the "expect.pl" and <autosudo.pl> scripts
2276 in the examples directory).
2277
2278 SSH::OpenSSH::Parallel is an advanced scheduler that allows one to run
2279 commands in remote hosts in parallel. It is obviously based on
2280 Net::OpenSSH.
2281
2282 SSH::Batch allows one to run remote commands in parallel in a cluster.
2283 It is build on top on "Net::OpenSSH" also.
2284
2285 Other Perl SSH clients: Net::SSH::Perl, Net::SSH2, Net::SSH,
2286 Net::SSH::Expect, Net::SCP, Net::SSH::Mechanize.
2287
2288 Net::OpenSSH::Compat is a package offering a set of compatibility
2289 layers for other SSH modules on top of Net::OpenSSH.
2290
2291 IPC::PerlSSH, GRID::Machine allow execution of Perl code in remote
2292 machines through SSH.
2293
2294 SSH::RPC implements an RPC mechanism on top of SSH using Net::OpenSSH
2295 to handle the connections.
2296
2297 Net::CLI::Interact allows one to interact with remote shells and other
2298 services. It is specially suited for interaction with network
2299 equipment. The phrasebook approach it uses is very clever. You may also
2300 like to check the other modules <https://metacpan.org/author/OLIVER>
2301 from its author, Oliver Gorwits.
2302
2304 Experimental features
2305 Support for the "restart" feature is experimental.
2306
2307 Object::Remote integration is highly experimental.
2308
2309 Support for tunnels targeting Unix sockets is highly experimental.
2310
2311 Support for the "setpgrp" feature is highly experimental.
2312
2313 Support for the gateway feature is highly experimental and mostly
2314 stalled.
2315
2316 Support for taint mode is experimental.
2317
2318 Known issues
2319 Net::OpenSSH does not work on Windows. OpenSSH multiplexing feature
2320 requires passing file handles through sockets, something that is not
2321 supported by any version of Windows.
2322
2323 It does not work on VMS either... well, probably, it does not work on
2324 anything not resembling a modern Linux/Unix OS.
2325
2326 Old versions of OpenSSH "ssh" may leave stdio streams in non-blocking
2327 mode. That can result on failures when writing to "STDOUT" or "STDERR"
2328 after using the module. In order to work-around this issue, Perl
2329 "fcntl" in perlfunc can be used to unset the non-blocking flag:
2330
2331 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
2332 my $flags = fcntl(STDOUT, F_GETFL, 0);
2333 fcntl(STDOUT, F_SETFL, $flags & ~O_NONBLOCK);
2334
2335 Reporting bugs and asking for help
2336 To report bugs send an email to the address that appear below or use
2337 the CPAN bug tracking system at <http://rt.cpan.org>.
2338
2339 Post questions related to how to use the module in PerlMonks
2340 <http://perlmonks.org/>, you will probably get faster responses than if
2341 you address me directly and I visit PerlMonks quite often, so I will
2342 see your question anyway.
2343
2344 Commercial support
2345 Commercial support, professional services and custom software
2346 development around this module are available through my current
2347 company. Drop me an email with a rough description of your requirements
2348 and we will get back to you ASAP.
2349
2350 My wishlist
2351 If you like this module and you are feeling generous, take a look at my
2352 Amazon Wish List: <http://amzn.com/w/1WU1P6IR5QZ42>.
2353
2354 Also consider contributing to the OpenSSH project this module builds
2355 upon: <http://www.openssh.org/donations.html>.
2356
2358 - Tests for "scp_*", "rsync_*" and "sftp" methods
2359
2360 - Make "pipe_in" and "pipe_out" methods "open_ex" based
2361
2362 - "auto_discard_streams" feature for mod_perl2 and similar environments
2363
2364 - Refactor open_ex support for multiple commands, maybe just keeping
2365 tunnel, ssh and raw
2366
2367 Send your feature requests, ideas or any feedback, please!
2368
2370 The source code of this module is hosted at GitHub:
2371 <http://github.com/salva/p5-Net-OpenSSH>.
2372
2373 Code contributions to the module are welcome but you should obey the
2374 following rules:
2375
2376 Only Perl 5.8.4 required
2377 Yes, that's pretty old, but Net::OpenSSH is intended to be also
2378 used by system administrators that sometimes have to struggle with
2379 old systems. The reason to pick 5.8.4 is that it has been the
2380 default perl on Solaris for a long time.
2381
2382 Avoid the "All the world's a Linux PC" syndrome
2383 The module should work on any (barely) sane Unix or Linux operating
2384 system. Specially, it should not be assumed that the over-featured
2385 GNU utilities and toolchain are available.
2386
2387 Dependencies are optional
2388 In order to make the module very easy to install, no mandatory
2389 dependencies on other CPAN modules are allowed.
2390
2391 Optional modules, that are loaded only on demand, are acceptable
2392 when they are used for adding new functionality (as it is done, for
2393 instance, with IO::Pty).
2394
2395 Glue code for integration with 3rd party modules is also allowed
2396 (as it is done with Expect).
2397
2398 Usage of language extension modules and alike is not acceptable.
2399
2400 Tests should be lax
2401 We don't want false negatives when testing. In case of doubt tests
2402 should succeed.
2403
2404 Also, in case of tests invoking some external program, it should be
2405 checked that the external program is available and that it works as
2406 expected or otherwise skip those tests.
2407
2408 Backward compatibility
2409 Nowadays Net::OpenSSH is quite stable and there are lots of scripts
2410 out there using it that we don't want to break, so, keeping the API
2411 backward compatible is a top priority.
2412
2413 Probably only security issues could now justify a backward
2414 incompatible change.
2415
2416 Follow my coding style
2417 Look at the rest of the code.
2418
2419 I let Emacs do the formatting for me using cperl-mode PerlStyle.
2420
2421 Talk to me
2422 Before making a large change or implementing a new feature get in
2423 touch with me.
2424
2425 I may have my own ideas about how things should be done. It is
2426 better if you know them before hand, otherwise, you risk getting
2427 your patch rejected.
2428
2429 Well, actually you should know that I am quite good at rejecting
2430 patches but it is not my fault!
2431
2432 Most of the patches I get are broken in some way: they don't follow the
2433 main module principles, sometimes the author didn't get the full
2434 picture and solved the issue in a short-sighted way, etc.
2435
2436 In any case, you should not be discouraged to contribute. Even if your
2437 patch is not applied directly, seeing how it solves your requirements
2438 or, in the case of bugs, the underlying problem analysis may be very
2439 useful and help me to do it... my way.
2440
2441 I always welcome documentation corrections and improvements.
2442
2444 Copyright (C) 2008-2020 by Salvador FandiƱo (sfandino@yahoo.com)
2445
2446 This library is free software; you can redistribute it and/or modify it
2447 under the same terms as Perl itself, either Perl version 5.10.0 or, at
2448 your option, any later version of Perl 5 you may have available.
2449
2450
2451
2452perl v5.34.0 2021-07-22 Net::OpenSSH(3)