How can I check if a file exists on a remote server using Perl?
Can I do this while using the Perl module Net::FTP?
CHECK TO SEE IF FILE EXISTS
if (-e $file_check) {
print "File Exists!\n";
}
else {
print "File Doesn't Exist!\n";
}
How can I check if a file exists on a remote server using Perl?
Can I do this while using the Perl module Net::FTP?
CHECK TO SEE IF FILE EXISTS
if (-e $file_check) {
print "File Exists!\n";
}
else {
print "File Doesn't Exist!\n";
}
If the file is in the FTP space on the remote server, then use Net::FTP. Get an ls
listing of the directory and see if your file is in there.
But you can't just go and see if any arbitrary file is on the server. Think of what a security problem that would be.
You might be best served by using SSH to do this:
#!/usr/bin/perl
use strict;
use warnings;
my $ssh = "/usr/bin/ssh";
my $host = "localhost";
my $test = "/usr/bin/test";
my $file = shift;
system $ssh, $host, $test, "-e", $file;
my $rc = $? >> 8;
if ($rc) {
print "file $file doesn't exist on $host\n";
} else {
print "file $file exists on $host\n";
}
Log in to the FTP server, and see if you can get an FTP SIZE
on the file you care about:
#!/usr/bin/env perl
use strict;
use warnings;
use Net::FTP;
use URI;
# ftp_file_exists('ftp://host/path')
#
# Return true if FTP URI points to an accessible, plain file.
# (May die on error, return false on inaccessible files, doesn't handle
# directories, and has hardcoded credentials.)
#
sub ftp_file_exists {
my $uri = URI->new(shift); # Parse ftp:// into URI object
my $ftp = Net::FTP->new($uri->host) or die "Connection error($uri): $@";
$ftp->login('anonymous', '[email protected]') or die "Login error", $ftp->message;
my $exists = defined $ftp->size($uri->path);
$ftp->quit;
return $exists;
}
for my $uri (@ARGV) {
print "$uri: ", (ftp_file_exists($uri) ? "yes" : "no"), "\n";
}