2010-06-28 137 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腳本我的工具,我可以保證它的作品完美:)

相關問題