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