Thread

Posted on Tue Jul 31 17:26:17 2007 by dantcutler
Donwload files using SFTP

Hello

I'm trying to write some simple code to automate donwloading from an SFTP site.

Does someone have a simple example of an open and read that outputs (effectiviely downloads) a file on my end?

I thought it should be something like open, read to buf, write buf to file -??

Thanks!!!
#!/usr/bin/perl -w use strict; use warnings; use Net::SSH2; use Net::SSH2::SFTP; use Net::SSH2::File; use IO::File; use Data::Dumper; my $host = 'sftp.somesite.com'; my $source_path = "mydir"; my $user = "user"; my $password = "passwd"; my $ssh = Net::SSH2->new(); my %hash; #$ssh->debug(%hash,1); die "Can't Connect to $host" unless $ssh->connect($host); if ($ssh->auth_password($user, $password)) { my $sftp = $ssh->sftp(); my $fh = $sftp->opendir($source_path) or die; while (my $ref = $fh->read()) { print "uid: $ref->{uid}\n"; print "mode: $ref->{mode}\n"; print "mtime: $ref->{mtime}\n"; print "name: $ref->{name}\n"; print "atime: $ref->{atime}\n"; print "size: $ref->{size}\n"; print "gid: $ref->{gid}\n"; if (($ref->{mode} & 0170000) >> 15) # Is this a file? { print "Type: File\n"; #EVERYTHING works until I try to open a file for reading... #What's wrong with this?? my $ff = $fh->open($ref->{name}, O_RDONLY); open(xout,">/tmp/$ref->{name}") || die; # Open a local file of same na me my $buffer; my $ret_size = $ff->read($buffer,$ref->{size}); print xout "$buffer"; close xout; } } } else { print "Auth Failed\t $ssh->error \n"; }
Direct Responses: 6435 | Write a response
Posted on Sun Nov 11 11:13:48 2007 by dbrobins in response to 5846
Re: Donwload files using SFTP
I believe the problem is caused by a bug fixed in Net::SSH2 0.18, which I just released (the version is now synced to libssh2, hence the jump); it's on CPAN but not yet indexed. The bug is that if the value of a POSIX flag (O_RDONLY) is 0, then it doesn't get correctly converted to an SFTP flag, so we'll try to open the file with no flags, which is invalid. Please try 0.18 and let me know if that fixes the problem.
Write a response