如何使用Perl检查远程服务器上是否存在文件?
我可以在使用Perl模块Net::FTP
吗?
检查文件是否存在
if (-e $file_check) {
print "File Exists!\n";
}
else {
print "File Doesn't Exist!\n";
}
答案 0 :(得分:6)
使用SSH执行此操作可能是最好的选择:
#!/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";
}
答案 1 :(得分:4)
您可以使用如下命令:
use Net::FTP;
$ftp->new(url);
$ftp->login(usr,pass);
$directoryToCheck = "foo";
unless ($ftp->cwd($directoryToCheck))
{
print "Directory doesn't exist
}
答案 2 :(得分:1)
如果文件位于远程服务器上的FTP空间中,则使用Net :: FTP。获取目录的ls
列表,并查看您的文件是否在那里。
但你不能只是去查看服务器上是否有任意文件。想想会出现什么样的安全问题。
答案 3 :(得分:1)
登录FTP服务器,查看您是否可以在您关注的文件上获取FTP SIZE
:
#!/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', 'anon@ftp.invalid') 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";
}
答案 4 :(得分:0)
您可以将expect脚本用于相同的目的(不需要额外的模块)。 expect将在FTP服务器上执行“ls -l”,perl脚本将解析输出并确定文件是否存在。它实现起来非常简单。
这是代码,
PERL脚本:(main.pl)
# ftpLog variable stores output of the expect script which logs in to FTP server and runs "ls -l" command
$fileName = "myFile.txt";
$ftpLog = `/usr/local/bin/expect /path/to/expect_script/ftp_chk.exp $ftpIP $ftpUser $ftpPass $ftpPath`;
# verify that file exists on FTP server by looking for filename in "ls -l" output
if(index($ftpLog,$fileName) > -1)
{
print "File exists!";
}
else
{
print "File does not exist.";
}
EXPECT脚本:(ftp_chk.exp)
#!/usr/bin/expect -f
set force_conservative 0;
set timeout 30
set ftpIP [lindex $argv 0]
set ftpUser [lindex $argv 1]
set ftpPass [lindex $argv 2]
set ftpPath [lindex $argv 3]
spawn ftp $ftpIP
expect "Name ("
send "$ftpUser\r"
sleep 2
expect {
"assword:" {
send "$ftpPass\r"
sleep 2
expect "ftp>"
send "cd $ftpPath\r\n"
sleep 2
expect "ftp>"
send "ls -l\r\n"
sleep 2
exit
}
"yes/no)?" {
send "yes\r"
sleep 2
exp_continue
}
timeout {
puts "\nError: ftp timed out.\n"
exit
}
}
我在我的一个工具中使用了这个设置,我可以保证它完美运行:)