Here's some code snippits from a program I am working on right now. Note that there may be a bug in the line (23) with the $sftp->ls (i.e. the program may inifintely loop here). Disclaimer: code has not been comletely tested nor is it the best written in the world.
use Net::SFTP;
use Net::SFTP::Util;
use Net::SFTP::Attributes;
use Net::SFTP::Constants qw( :flags );
# ...
#///////////////////////////////////////////////////////////////
sub sftp_connect {
my( $hostname ) = @_;
my $sftp = Net::SFTP->new(
$hostname,
user => $cfg{sftp_username},
password => $cfg{sftp_password},
) || die "Could not login to the remote server";
return $sftp;
}
#///////////////////////////////////////////////////////////////
sub sftp_ls_match {
my( $sftp, $path, $filename_to_match ) = @_;
my $file_ref;
my @files = @{ $sftp->ls( $path ) || die "Could not sftp->ls($pat
+h)" } ;
FIND_FILE:
foreach my $ref ( @files ) {
next FIND_FILE unless $ref->{filename} eq $filename_to_match;
$file_ref = $ref;
last FIND_FILE;
}
return $file_ref;
}
#///////////////////////////////////////////////////////////////
sub sftp_data_file_new {
my( $hostname, $data ) = @_;
my( $attr_ref, $flags, $offset );
my $sftp = sftp_connect( $hostname ) || die "Could not sftp
+_connect($hostname)";
my $file_ref = sftp_ls_match( $sftp, $cfg{sftp_path}, $cfg{data_
+file_new} );
# CASE: File exists
if( defined $file_ref ) {
# NOTE: $sftp->ls does not follow symbolic links. Thus the mti
+me from
# $file_ref->{a} could be for a symbolic link (where mtime wil
+l rarely
# change). Thus we use the output from do_stat which does foll
+ow sym links
$attr_ref = $sftp->do_stat( "$cfg{sftp_path}/$cfg{data_file_
+new}" );
$offset = $attr_ref->{size};
$flags = SSH2_FXF_WRITE | SSH2_FXF_APPEND;
}
# CASE: File does *NOT* exist
else {
$attr_ref = new Net::SFTP::Attributes;
$offset = 0;
$flags = SSH2_FXF_WRITE | SSH2_FXF_CREAT;
}
my $handle = $sftp->do_open( "$cfg{sftp_path}/$cfg{data_file_new}"
+, $flags, $attr_ref);
$sftp->do_write( $handle, $offset, $data );
$sftp->do_close( $handle );
# To get the new mtime we need to stat the file.
$attr_ref = $sftp->do_stat( "$cfg{sftp_path}/$cfg{data_file_new}"
+);
# ...
return;
}
|