2012-12-03 40 views
0

爲了測試目的,我需要編寫一個程序,它使用[Net :: FTP]連接到服務器,然後接收文件某個目錄。一旦收到,就把它放回到同一個地方。在Perl中使用Net :: FTP並嘗試不同的命令

這裏是我的代碼:

#!/usr/bin/perl 

    use Net::FTP; 

    $host = "serverA"; 
    $username = "test"; 
    $password = "ftptest123"; 
    $ftpdir = "/ftptest"; 
    $file = "ftptest.txt"; 

    $ftp = Net::FTP->new($host) or die "Error connecting to $host: $!"; 

    $ftp->login($username,$password) or die "Login failed: $!"; 

    $ftp->cwd($ftpdir) or die "Can't go to $ftpdir: $!"; 

    $ftp->get($file) or die "Can't get $file: $!"; 

    $ftp->put($file) or die "Can't put $file: $!"; 

    $ftp->quit or die "Error closing ftp connection: $!"; 

如何去這個任何想法?它似乎運行正常,但是當它擊中put聲明它拍攝出這樣的我:$ftp->message

[Net::FTP]: https://metacpan.org/module/Net::FTP 
+2

你的錯誤是什麼? – jordanm

+0

你也應該用「嚴格使用;使用警告」來開始你的perl腳本; – hd1

回答

1

檢查錯誤消息,而不是在$!。它可能會告訴你,你沒有寫訪問該目錄,或不允許覆蓋現有文件...

+0

除new()錯誤消息位於'$ @' – runrig

1

首先,你應該始終use strictuse warnings,並聲明所有的變量在第一次使用時使用my。通過這種方式,您將會突出顯示您將會看到的許多微不足道的錯誤。

Net::FTP的文檔不完整,因爲它沒有提供有關message方法的任何信息。然而,從簡介中可以清楚地看到,有關任何錯誤的信息都可以使用$ftp->message訪問。

當然這不適用於構造函數,就好像那個失敗沒有對象提供message方法,所以在這種情況下信息出現在內置變量[email protected]中。

在您的程序上嘗試此變體。它可能會立即告訴你爲什麼它失敗。

#!/usr/bin/perl 

use strict; 
use warnings; 

use Net::FTP; 

my $host = 'serverA'; 
my $username = 'test'; 
my $password = 'ftptest123'; 
my $ftpdir = '/ftptest'; 
my $file = 'ftptest.txt'; 

my $ftp = Net::FTP->new($host) or die "Error connecting to $host: [email protected]"; 

$ftp->login($username,$password) or die "Login failed: ", $ftp->message; 

$ftp->cwd($ftpdir) or die "Can't go to $ftpdir: ", $ftp->message; 

$ftp->get($file) or die "Can't get $file: ", $ftp->message; 

$ftp->put($file) or die "Can't put $file: ", $ftp->message; 

$ftp->quit or die "Error closing ftp connection: ", $ftp->message; 
+0

+1(嚴格使用)之外,請使用警告以及完整錯誤檢查的示例 –

相關問題