PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Net-SSH-0.09/SSH.pm

#
Perl | 343 lines | 270 code | 73 blank | 0 comment | 10 complexity | 66eb36edbe4a562db4c80b068a52c17e MD5 | raw file
  1. package Net::SSH;
  2. use strict;
  3. use vars qw($VERSION @ISA @EXPORT_OK $ssh $equalspace $DEBUG @ssh_options);
  4. use Exporter;
  5. use POSIX ":sys_wait_h";
  6. use IO::File;
  7. use IO::Select;
  8. use IPC::Open2;
  9. use IPC::Open3;
  10. @ISA = qw(Exporter);
  11. @EXPORT_OK = qw( ssh issh ssh_cmd sshopen2 sshopen3 );
  12. $VERSION = '0.09';
  13. $DEBUG = 0;
  14. $ssh = "ssh";
  15. =head1 NAME
  16. Net::SSH - Perl extension for secure shell
  17. =head1 SYNOPSIS
  18. use Net::SSH qw(ssh issh sshopen2 sshopen3);
  19. ssh('user@hostname', $command);
  20. issh('user@hostname', $command);
  21. ssh_cmd('user@hostname', $command);
  22. ssh_cmd( {
  23. user => 'user',
  24. host => 'host.name',
  25. command => 'command',
  26. args => [ '-arg1', '-arg2' ],
  27. stdin_string => "string\n",
  28. } );
  29. sshopen2('user@hostname', $reader, $writer, $command);
  30. sshopen3('user@hostname', $writer, $reader, $error, $command);
  31. =head1 DESCRIPTION
  32. Simple wrappers around ssh commands.
  33. For an all-perl implementation that does not require the system B<ssh> command,
  34. see L<Net::SSH::Perl> instead.
  35. =head1 SUBROUTINES
  36. =over 4
  37. =item ssh [USER@]HOST, COMMAND [, ARGS ... ]
  38. Calls ssh in batch mode.
  39. =cut
  40. sub ssh {
  41. my($host, @command) = @_;
  42. @ssh_options = &_ssh_options unless @ssh_options;
  43. my @cmd = ($ssh, @ssh_options, $host, @command);
  44. warn "[Net::SSH::ssh] executing ". join(' ', @cmd). "\n"
  45. if $DEBUG;
  46. system(@cmd);
  47. }
  48. =item issh [USER@]HOST, COMMAND [, ARGS ... ]
  49. Prints the ssh command to be executed, waits for the user to confirm, and
  50. (optionally) executes the command.
  51. =cut
  52. sub issh {
  53. my($host, @command) = @_;
  54. my @cmd = ($ssh, $host, @command);
  55. print join(' ', @cmd), "\n";
  56. if ( &_yesno ) {
  57. system(@cmd);
  58. }
  59. }
  60. =item ssh_cmd [USER@]HOST, COMMAND [, ARGS ... ]
  61. =item ssh_cmd OPTIONS_HASHREF
  62. Calls ssh in batch mode. Throws a fatal error if data occurs on the command's
  63. STDERR. Returns any data from the command's STDOUT.
  64. If using the hashref-style of passing arguments, possible keys are:
  65. user (optional)
  66. host (requried)
  67. command (required)
  68. args (optional, arrayref)
  69. stdin_string (optional) - written to the command's STDIN
  70. =cut
  71. sub ssh_cmd {
  72. my($host, $stdin_string, @command);
  73. if ( ref($_[0]) ) {
  74. my $opt = shift;
  75. $host = $opt->{host};
  76. $host = $opt->{user}. '@'. $host if exists $opt->{user};
  77. @command = ( $opt->{command} );
  78. push @command, @{ $opt->{args} } if exists $opt->{args};
  79. $stdin_string = $opt->{stdin_string};
  80. } else {
  81. ($host, @command) = @_;
  82. undef $stdin_string;
  83. }
  84. my $reader = IO::File->new();
  85. my $writer = IO::File->new();
  86. my $error = IO::File->new();
  87. my $pid = sshopen3( $host, $writer, $reader, $error, @command ) or die $!;
  88. print $writer $stdin_string if defined $stdin_string;
  89. close $writer;
  90. my $select = new IO::Select;
  91. foreach ( $reader, $error ) { $select->add($_); }
  92. my($output_stream, $error_stream) = ('', '');
  93. while ( $select->count ) {
  94. my @handles = $select->can_read;
  95. foreach my $handle ( @handles ) {
  96. my $buffer = '';
  97. my $bytes = sysread($handle, $buffer, 4096);
  98. if ( !defined($bytes) ) {
  99. waitpid($pid, WNOHANG);
  100. die "[Net::SSH::ssh_cmd] $!"
  101. };
  102. $select->remove($handle) if !$bytes;
  103. if ( $handle eq $reader ) {
  104. $output_stream .= $buffer;
  105. } elsif ( $handle eq $error ) {
  106. $error_stream .= $buffer;
  107. }
  108. }
  109. }
  110. waitpid($pid, WNOHANG);
  111. die "$error_stream" if length($error_stream);
  112. return $output_stream;
  113. }
  114. =item sshopen2 [USER@]HOST, READER, WRITER, COMMAND [, ARGS ... ]
  115. Connects the supplied filehandles to the ssh process (in batch mode).
  116. =cut
  117. sub sshopen2 {
  118. my($host, $reader, $writer, @command) = @_;
  119. @ssh_options = &_ssh_options unless @ssh_options;
  120. open2($reader, $writer, $ssh, @ssh_options, $host, @command);
  121. }
  122. =item sshopen3 HOST, WRITER, READER, ERROR, COMMAND [, ARGS ... ]
  123. Connects the supplied filehandles to the ssh process (in batch mode).
  124. =cut
  125. sub sshopen3 {
  126. my($host, $writer, $reader, $error, @command) = @_;
  127. @ssh_options = &_ssh_options unless @ssh_options;
  128. open3($writer, $reader, $error, $ssh, @ssh_options, $host, @command);
  129. }
  130. sub _yesno {
  131. print "Proceed [y/N]:";
  132. my $x = scalar(<STDIN>);
  133. $x =~ /^y/i;
  134. }
  135. sub _ssh_options {
  136. my $reader = IO::File->new();
  137. my $writer = IO::File->new();
  138. my $error = IO::File->new();
  139. open3($writer, $reader, $error, $ssh, '-V');
  140. my $ssh_version = <$error>;
  141. chomp($ssh_version);
  142. if ( $ssh_version =~ /.*OpenSSH[-|_](\w+)\./ && $1 == 1 ) {
  143. $equalspace = " ";
  144. } else {
  145. $equalspace = "=";
  146. }
  147. my @options = ( '-o', 'BatchMode'.$equalspace.'yes' );
  148. if ( $ssh_version =~ /.*OpenSSH[-|_](\w+)\./ && $1 > 1 ) {
  149. unshift @options, '-T';
  150. }
  151. @options;
  152. }
  153. =back
  154. =head1 EXAMPLE
  155. use Net::SSH qw(sshopen2);
  156. use strict;
  157. my $user = "username";
  158. my $host = "hostname";
  159. my $cmd = "command";
  160. sshopen2("$user\@$host", *READER, *WRITER, "$cmd") || die "ssh: $!";
  161. while (<READER>) {
  162. chomp();
  163. print "$_\n";
  164. }
  165. close(READER);
  166. close(WRITER);
  167. =head1 FREQUENTLY ASKED QUESTIONS
  168. Q: How do you supply a password to connect with ssh within a perl script
  169. using the Net::SSH module?
  170. A: You don't (at least not with this module). Use RSA or DSA keys. See the
  171. quick help in the next section and the ssh-keygen(1) manpage.
  172. A #2: See L<Net::SSH::Expect> instead.
  173. Q: My script is "leaking" ssh processes.
  174. A: See L<perlfaq8/"How do I avoid zombies on a Unix system">, L<IPC::Open2>,
  175. L<IPC::Open3> and L<perlfunc/waitpid>.
  176. =head1 GENERATING AND USING SSH KEYS
  177. =over 4
  178. =item 1 Generate keys
  179. Type:
  180. ssh-keygen -t rsa
  181. And do not enter a passphrase unless you wanted to be prompted for
  182. one during file copying.
  183. Here is what you will see:
  184. $ ssh-keygen -t rsa
  185. Generating public/private rsa key pair.
  186. Enter file in which to save the key (/home/User/.ssh/id_rsa):
  187. Enter passphrase (empty for no passphrase):
  188. Enter same passphrase again:
  189. Your identification has been saved in /home/User/.ssh/id_rsa.
  190. Your public key has been saved in /home/User/.ssh/id_rsa.pub.
  191. The key fingerprint is:
  192. 5a:cd:2b:0a:cd:d9:15:85:26:79:40:0c:55:2a:f4:23 User@JEFF-CPU
  193. =item 2 Copy public to machines you want to upload to
  194. C<id_rsa.pub> is your public key. Copy it to C<~/.ssh> on target machine.
  195. Put a copy of the public key file on each machine you want to log into.
  196. Name the copy C<authorized_keys> (some implementations name this file
  197. C<authorized_keys2>)
  198. Then type:
  199. chmod 600 authorized_keys
  200. Then make sure your home dir on the remote machine is not group or
  201. world writeable.
  202. =back
  203. =head1 AUTHORS
  204. Ivan Kohler <ivan-netssh_pod@420.am>
  205. Assistance wanted - this module could really use a maintainer with enough time
  206. to at least review and apply more patches. Or the module should just be
  207. deprecated in favor of Net::SSH::Expect or made into an ::Any style
  208. compatibility wrapper that uses whatver implementation is avaialble
  209. (Net::SSH2, Net::SSH::Perl or shelling out like the module does now). Please
  210. email Ivan if you are interested in helping.
  211. John Harrison <japh@in-ta.net> contributed an example for the documentation.
  212. Martin Langhoff <martin@cwa.co.nz> contributed the ssh_cmd command, and
  213. Jeff Finucane <jeff@cmh.net> updated it and took care of the 0.04 release.
  214. Anthony Awtrey <tony@awtrey.com> contributed a fix for those still using
  215. OpenSSH v1.
  216. Thanks to terrence brannon <tbone@directsynergy.com> for the documentation in
  217. the GENERATING AND USING SSH KEYS section.
  218. =head1 COPYRIGHT
  219. Copyright (c) 2004 Ivan Kohler.
  220. Copyright (c) 2007-2008 Freeside Internet Services, Inc.
  221. All rights reserved.
  222. This program is free software; you can redistribute it and/or modify it under
  223. the same terms as Perl itself.
  224. =head1 BUGS
  225. Not OO.
  226. Look at IPC::Session (also fsh, well now the native SSH "master mode" stuff)
  227. =head1 SEE ALSO
  228. For a perl implementation that does not require the system B<ssh> command, see
  229. L<Net::SSH::Perl> instead.
  230. For a wrapper version that allows you to use passwords, see L<Net::SSH::Expect>
  231. instead.
  232. For another non-forking version that uses the libssh2 library, see
  233. L<Net::SSH2>.
  234. For a way to execute remote Perl code over an ssh connection see
  235. L<IPC::PerlSSH>.
  236. ssh-keygen(1), ssh(1), L<IO::File>, L<IPC::Open2>, L<IPC::Open3>
  237. =cut
  238. 1;