0

I want my code to do the following: if a certain file can be found on a server, I want to get it and save it to a text file. If it can't be found, I want to save to another text file.

How can I do this?

This is my code:

#!/usr/bin/perl
use Net::TFTP;

my $server = "192.168.1.1";
my $file = "image.bin";

my $tftp = Net::TFTP->new("$server");
$tftp->octet;
$tftp->get("$file","$server-$file");
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • 1
    You should [edit] your question to explain what the result of using your code is, and how it differs from what you want to achieve. – Benjamin W. Mar 14 '18 at 14:02

1 Answers1

0

Your question or desired output is not clear to me. From what I understand for your description you need to search a foreign host for some files and if they exist get them, if not add them in a file. One possible approach to your problem could be with Net::SFTP::Foreign. On my sample of code bellow I just search for the files in the dir and if I found the files that I want I add them in an array for further processing. In your case you can use get or something else, read the documentation of the module which is very very reach.

Sample of code:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use Net::SFTP::Foreign;

my %args = ( host     => "127.0.0.1",
             user     => "user",
             port     => "22", # default 22
             # psw    => "psw", # uncomment if you are using passwords
             key_path => "/home/user/.ssh/id_rsa" ); # comment if you are using passwords

my $sftp = Net::SFTP::Foreign->new(%args);
$sftp->die_on_error("Unable to establish SFTP connection");

my $ls = $sftp->ls('/home/user/myTestDir/TestDir')
    or die "unable to retrieve directory: ".$sftp->error;

my @rest;
my @wanted;
for (@$ls) {
    next if (substr($_->{filename},0,1) eq "."); # skip ('.' and '..')
    if ($_->{filename} eq 'foo.txt'){
    push @wanted, $_->{filename};
    } else {
    push @rest, $_->{filename};
    }
}
print Dumper \@wanted, \@rest;

# do your stuff with the files

__END__

$ perl test.pl
$VAR1 = [
          'foo.txt'
        ];
$VAR2 = [
          'bar.txt'
        ];
Thanos
  • 1,618
  • 4
  • 28
  • 49