0.08
[Net-SSH.git] / SSH.pm
1 package Net::SSH;
2
3 use strict;
4 use vars qw($VERSION @ISA @EXPORT_OK $ssh $equalspace $DEBUG @ssh_options);
5 use Exporter;
6 use POSIX ":sys_wait_h";
7 use IO::File;
8 use IO::Select;
9 use IPC::Open2;
10 use IPC::Open3;
11
12 @ISA = qw(Exporter);
13 @EXPORT_OK = qw( ssh issh ssh_cmd sshopen2 sshopen3 );
14 $VERSION = '0.08';
15
16 $DEBUG = 0;
17
18 $ssh = "ssh";
19
20 =head1 NAME
21
22 Net::SSH - Perl extension for secure shell
23
24 =head1 SYNOPSIS
25
26   use Net::SSH qw(ssh issh sshopen2 sshopen3);
27
28   ssh('user@hostname', $command);
29
30   issh('user@hostname', $command);
31
32   ssh_cmd('user@hostname', $command);
33   ssh_cmd( {
34     user => 'user',
35     host => 'host.name',
36     command => 'command',
37     args => [ '-arg1', '-arg2' ],
38     stdin_string => "string\n",
39   } );
40
41   sshopen2('user@hostname', $reader, $writer, $command);
42
43   sshopen3('user@hostname', $writer, $reader, $error, $command);
44
45 =head1 DESCRIPTION
46
47 Simple wrappers around ssh commands.
48
49 For an all-perl implementation that does not require the system B<ssh> command,
50 see L<Net::SSH::Perl> instead.
51
52 =head1 SUBROUTINES
53
54 =over 4
55
56 =item ssh [USER@]HOST, COMMAND [, ARGS ... ]
57
58 Calls ssh in batch mode.
59
60 =cut
61
62 sub ssh {
63   my($host, @command) = @_;
64   @ssh_options = &_ssh_options unless @ssh_options;
65   my @cmd = ($ssh, @ssh_options, $host, @command);
66   warn "[Net::SSH::ssh] executing ". join(' ', @cmd). "\n"
67     if $DEBUG;
68   system(@cmd);
69 }
70
71 =item issh [USER@]HOST, COMMAND [, ARGS ... ]
72
73 Prints the ssh command to be executed, waits for the user to confirm, and
74 (optionally) executes the command.
75
76 =cut
77
78 sub issh {
79   my($host, @command) = @_;
80   my @cmd = ($ssh, $host, @command);
81   print join(' ', @cmd), "\n";
82   if ( &_yesno ) {
83     system(@cmd);
84   }
85 }
86
87 =item ssh_cmd [USER@]HOST, COMMAND [, ARGS ... ]
88
89 =item ssh_cmd OPTIONS_HASHREF
90
91 Calls ssh in batch mode.  Throws a fatal error if data occurs on the command's
92 STDERR.  Returns any data from the command's STDOUT.
93
94 If using the hashref-style of passing arguments, possible keys are:
95
96   user (optional)
97   host (requried)
98   command (required)
99   args (optional, arrayref)
100   stdin_string (optional) - written to the command's STDIN
101
102 =cut
103
104 sub ssh_cmd {
105   my($host, $stdin_string, @command);
106   if ( ref($_[0]) ) {
107     my $opt = shift;
108     $host = $opt->{host};
109     $host = $opt->{user}. '@'. $host if exists $opt->{user};
110     @command = ( $opt->{command} );
111     push @command, @{ $opt->{args} } if exists $opt->{args};
112     $stdin_string = $opt->{stdin_string};
113   } else {
114     ($host, @command) = @_;
115     undef $stdin_string;
116   }
117
118   my $reader = IO::File->new();
119   my $writer = IO::File->new();
120   my $error  = IO::File->new();
121
122   my $pid = sshopen3( $host, $writer, $reader, $error, @command ) or die $!;
123
124   print $writer $stdin_string if defined $stdin_string;
125   close $writer;
126
127   my $select = new IO::Select;
128   foreach ( $reader, $error ) { $select->add($_); }
129
130   my($output_stream, $error_stream) = ('', '');
131   while ( $select->count ) {
132     my @handles = $select->can_read;
133     foreach my $handle ( @handles ) {
134       my $buffer = '';
135       my $bytes = sysread($handle, $buffer, 4096);
136       if ( !defined($bytes) ) {
137         waitpid($pid, WNOHANG);
138         die "[Net::SSH::ssh_cmd] $!"
139       };
140       $select->remove($handle) if !$bytes;
141       if ( $handle eq $reader ) {
142         $output_stream .= $buffer;
143       } elsif ( $handle eq $error ) {
144         $error_stream  .= $buffer;
145       }
146     }
147
148   }
149
150   waitpid($pid, WNOHANG);
151
152   die "$error_stream" if length($error_stream);
153
154   return $output_stream;
155
156 }
157
158 =item sshopen2 [USER@]HOST, READER, WRITER, COMMAND [, ARGS ... ]
159
160 Connects the supplied filehandles to the ssh process (in batch mode).
161
162 =cut
163
164 sub sshopen2 {
165   my($host, $reader, $writer, @command) = @_;
166   @ssh_options = &_ssh_options unless @ssh_options;
167   open2($reader, $writer, $ssh, @ssh_options, $host, @command);
168 }
169
170 =item sshopen3 HOST, WRITER, READER, ERROR, COMMAND [, ARGS ... ]
171
172 Connects the supplied filehandles to the ssh process (in batch mode).
173
174 =cut
175
176 sub sshopen3 {
177   my($host, $writer, $reader, $error, @command) = @_;
178   @ssh_options = &_ssh_options unless @ssh_options;
179   open3($writer, $reader, $error, $ssh, @ssh_options, $host, @command);
180 }
181
182 sub _yesno {
183   print "Proceed [y/N]:";
184   my $x = scalar(<STDIN>);
185   $x =~ /^y/i;
186 }
187
188 sub _ssh_options {
189   my $reader = IO::File->new();
190   my $writer = IO::File->new();
191   my $error  = IO::File->new();
192   open3($writer, $reader, $error, $ssh, '-V');
193   my $ssh_version = <$error>;
194   chomp($ssh_version);
195   if ( $ssh_version =~ /.*OpenSSH[-|_](\w+)\./ && $1 == 1 ) {
196     $equalspace = " ";
197   } else {
198     $equalspace = "=";
199   }
200   my @options = ( '-o', 'BatchMode'.$equalspace.'yes' );
201   if ( $ssh_version =~ /.*OpenSSH[-|_](\w+)\./ && $1 > 1 ) {
202     unshift @options, '-T';
203   }
204   @options;
205 }
206
207 =back
208
209 =head1 EXAMPLE
210
211   use Net::SSH qw(sshopen2);
212   use strict;
213
214   my $user = "username";
215   my $host = "hostname";
216   my $cmd = "command";
217
218   sshopen2("$user\@$host", *READER, *WRITER, "$cmd") || die "ssh: $!";
219
220   while (<READER>) {
221       chomp();
222       print "$_\n";
223   }
224
225   close(READER);
226   close(WRITER);
227
228 =head1 FREQUENTLY ASKED QUESTIONS
229
230 Q: How do you supply a password to connect with ssh within a perl script
231 using the Net::SSH module?
232
233 A: You don't.  Use RSA or DSA keys.  See the ssh-keygen(1) manpage.
234
235 Q: My script is "leaking" ssh processes.
236
237 A: See L<perlfaq8/"How do I avoid zombies on a Unix system">, L<IPC::Open2>,
238 L<IPC::Open3> and L<perlfunc/waitpid>.
239
240 =head1 AUTHORS
241
242 Ivan Kohler <ivan-netssh_pod@420.am>
243
244 John Harrison <japh@in-ta.net> contributed an example for the documentation.
245
246 Martin Langhoff <martin@cwa.co.nz> contributed the ssh_cmd command, and
247 Jeff Finucane <jeff@cmh.net> updated it and took care of the 0.04 release.
248
249 Anthony Awtrey <tony@awtrey.com> contributed a fix for those still using
250 OpenSSH v1.
251
252 =head1 COPYRIGHT
253
254 Copyright (c) 2004 Ivan Kohler.
255 Copyright (c) 2002 Freeside Internet Services, LLC
256 All rights reserved.
257 This program is free software; you can redistribute it and/or modify it under
258 the same terms as Perl itself.
259
260 =head1 BUGS
261
262 Not OO.
263
264 Look at IPC::Session (also fsh)
265
266 =head1 SEE ALSO
267
268 For an all-perl implementation that does not require the system B<ssh> command,
269 see L<Net::SSH::Perl> instead.
270
271 ssh-keygen(1), ssh(1), L<IO::File>, L<IPC::Open2>, L<IPC::Open3>
272
273 =cut
274
275 1;
276