2010-06-28 139 views

回答

1

如果该文件是在远程服务器上的FTP空间,然后使用Net :: FTP。获取该目录的ls列表,看看您的文件是否在那里。

但是你不能只是去看看服务器上是否有任意文件。想想会是什么安全问题。

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"; 
} 
+0

但如何处理,如果它的密码保护的远程服务器? – Jithin 2012-10-09 04:48:05

+0

@Jithin这是ssh密钥的用途。 – 2012-10-10 13:24:06

+0

是的,我明白了。但是,如果远程服务器受密码保护,脚本中是否有任何解决方法? – Jithin 2012-10-11 04:18:40

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): [email protected]"; 
    $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"; 
} 
+0

这将工作在零大小的文件? – Schwern 2010-06-28 17:18:10

+0

@Schwern,谢谢,“不”,但修改后的代码会。 – pilcrow 2010-06-28 18:40:16

4

你可以使用一个命令如:

use Net::FTP; 
$ftp->new(url); 
$ftp->login(usr,pass); 

$directoryToCheck = "foo"; 

unless ($ftp->cwd($directoryToCheck)) 
{ 
    print "Directory doesn't exist 
} 
0

你可以使用一个expect脚本为同一目的(不需要额外的模块)。期望将在FTP服务器上执行“ls -l”,并且perl脚本将解析输出并确定文件是否存在。它的实现非常简单。

下面的代码,

PERL脚本:

#!/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 
    } 
} 

我已经在一个使用此设置(ftp_chk.exp):(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脚本我的工具,我可以保证它的作品完美:)

相关问题