Get file from Remote server and append data in local server file

Viewed 71

I have a script which gets file from remote machine to local machine and appends data to the existing file if the file is already present in the local machine.

Code below: This uses Net::SFTP::Foreign Perl module.

.
.
my $remote_dir = "/REMOTE/MACHINE/PATH";
my $file        = "Report9_202007.txt";

my $local_dir   = "/LOCAL/MACHINE/PATH";

my $sftp = Net::SFTP::Foreign->new(host=>$host , user=>$user , password=>$pass);
$sftp->die_on_error("Unable to establish SFTP connection");

$sftp->put("$remote_dir/$file","$local_dir/$file", append=>1, overwrite=>0) or die "put failed:".$sftp->error;
$sftp->disconnect;
.
.

Above script works perfectly fine. As you can see I am appending data of the report to the existing file and not overwriting into it in local machine in condition ..append=>1, overwrite=>0)

Similarly, I have some dependency on Perl module on one of the VM so I thought of doing same operation using Net::OpenSSH perl module.

Script below:

.
.
my $ssh = Net::OpenSSH->new($host,
                            user => $user,
                            password => $passwd
);
$ssh->error and die "Couldn't establish SSH connection: ". $ssh->error;
.
.
$ssh->scp_put({glob => 1}, "$remote_dir/$file", "$local_dir/$file")
        or die "scp failed: " . $ssh->error;
.

But here its overwriting the existing file when it puts the file from remote server to local server. How can I modify the script which should do a same operation like Net::SFTP::Foreign does while putting the file by setting overwrite value as 0 and append as 1 in scp_put?

1 Answers

This should do the trick as long as the remote system runs some kind of UNIX:

open my $fh, '>>', $local_file or die $!
$ssh->system({stdout_fh => $fh}, cat => $remote_file) or die $ssh->error
Related