#!/usr/bin/perl use warnings; use strict; use Net::SSH2; use Data::Dumper; # see maillist archives at # http://lists.sourceforge.net/lists/listinfo/ssh-sftp-perl-users my $ssh2 = Net::SSH2->new(); $ssh2->connect('localhost') or die "Unable to connect Host $@ \n"; #this works for passwords #$ssh2->auth_password('z','ztester') or die "Unable to login $@ \n"; #do key authorization like commandline shell # ssh -o PreferredAuthentications=publickey localhost # See: http://cfm.gs.washington.edu/security/ssh/client-pkauth/ # for setting up the keys # this dosn't work #$ssh2->auth(username=>'z', interact => 1); # so get the password for the key use Term::ReadKey; print "And your key password: "; ReadMode('noecho'); chomp(my $pass = ReadLine(0)); ReadMode('restore'); print "\n"; # works when run from z's homedir because you need # permission to read the keys $ssh2->auth_publickey('z', '/home/z/.ssh/id_dsa.pub', '/home/z/.ssh/id_dsa', $pass ); #works my $sftp = $ssh2->sftp(); my $fh = $sftp->open('/etc/passwd') or die; print $_ while <$fh>; #my $chan = $ssh2->channel(); #$chan->blocking(0); #$chan->exec('ls -la'); #while (<$chan>){ print } # to run a remote command in the background # you need to semi-daemonize it by redirecting it's filehandles my $chan3 = $ssh2->channel(); $chan3->blocking(1); $chan3->exec("nohup /home/zentara/perlplay/net/zzsleep > foo.out 2> foo.err < /dev/null &"); $chan3->send_eof; #to run multiple commands use a shell #shell use my $chan = $ssh2->channel(); $chan->blocking(0); $chan->shell(); print $chan "ls -la\n"; print "LINE : $_" while <$chan>; print $chan "who\n"; print "LINE : $_" while <$chan>; print $chan "date\n"; print "LINE : $_" while <$chan>; # file and directory operations #will get dir named 2 #my $chan1 = $ssh2->channel(); #$chan1->exec('ls -la 2'); #while (<$chan1>){ print } # mkdir with sftp #my $sftp = $ssh2->sftp(); my $dir = '/home/z/3'; $sftp->mkdir($dir); my %stat = $sftp->stat($dir); print Dumper([\%stat]), "\n"; #put a file my $remote = "$dir/".time; $ssh2->scp_put($0, $remote); #get a file #use IO::Scalar; #my $check = IO::Scalar->new; #$ssh2->scp_get($remote, $check); #print "$check\n\n"; # get a dirlist my $dir1 = '/home/z'; my $dh = $sftp->opendir($dir1); while(my $item = $dh->read) { print $item->{'name'},"\n"; } #shell use my $chan2 = $ssh2->channel(); $chan2->blocking(0); $chan2->shell(); print $chan2 "uname -a\n"; print "LINE : $_" while <$chan2>; print $chan2 "who\n"; print "LINE : $_" while <$chan2>; $chan2->close; __END__