Advertisement
markizano

ssh-test.pl

Oct 23rd, 2012
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.82 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5. use Data::Dumper;
  6. use Net::SSH2;
  7. use Net::SFTP;
  8. use Carp;
  9.  
  10. use Fcntl;
  11. use Fcntl ':DEFAULT';
  12.  
  13. use constant SSH_USER => 'root';
  14. use constant SSH_PASS => 'toor';
  15. use constant SSH_HOST => 'localhost';
  16. use constant SSH_PORT => 21;
  17.  
  18. my ( $conn, $ssh, $sftp, $buf, $buffer, $len );
  19.  
  20. sub ssh_connect {
  21.     my ( $ssh, $user, $host, $pass, $port );
  22.     ( $user, $pass, $host, $port ) = @_;
  23.  
  24.     $host ||= 'localhost';
  25.     $port ||= 22;
  26.  
  27.     $ssh = new Net::SSH2;
  28.     $ssh->debug(1);
  29.     $ssh->blocking(1);
  30.  
  31.     return 0 unless $ssh->connect($host . ':' . $port);
  32.     print "[*] Connect OK!\n";
  33.     return 0 unless $ssh->auth( username => $user, password => $pass);
  34.     print "[*] Auth OK!\n";
  35.  
  36.     return $ssh;
  37. }
  38.  
  39. sub ssh_test_docroot {
  40.     my ( $result, $ssh, $docroot, $sftp, $remote, $hostname );
  41.     ( $ssh, $docroot, $hostname ) = @_;
  42.  
  43.     croak "ssh_test_docroot: Arg 1(\$ssh) must be an instance of Net::SSH2." if ( ref $ssh ne 'Net::SSH2' );
  44.  
  45.     unless ( $sftp = $ssh->sftp() ) {
  46.         # Set some error here.
  47.         warn "[x] Could not extract Net::SSH2::SFTP object.\n";
  48.         $ssh->close();
  49.         return 0;
  50.     }
  51.  
  52.     unless ( $remote = $sftp->open("$docroot/test.txt", O_CREAT, 0666) ) {
  53.         # Set some error code here.
  54.         warn "[x] Could not open remote file `$docroot/test.txt': " . join(":", $sftp->error) . "\n";
  55.         $ssh->close();
  56.         return 0;
  57.     }
  58.  
  59.     unless ( $remote->write("Test Home Page") ) {
  60.         # Set some error code here.
  61.         warn "[x] Could not write contents.\n";
  62.         $ssh->close();
  63.         return 0;
  64.     }
  65.  
  66.     print "[*] Wrote file. Garbage collect.\n";
  67.     $sftp->unlink("$docroot/test.txt");
  68.  
  69.     return 1;
  70. }
  71.  
  72. croak "[x] Unable to connect.\n" unless $ssh = ssh_connect( SSH_USER, SSH_PASS, SSH_HOST, SSH_PORT );
  73. print "[*] Connected!\n";
  74. print Dumper({ docroot => ssh_test_docroot( $ssh, '~/public_html' ) });
  75. $ssh->close();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement