2011-10-16 37 views
1

爲什麼我的程序不工作?它拒絕連接到主機,我試過兩個不同的服務器,並驗證使用哪個端口。 請注意,就Perl而言,我並不是很有經驗。使用Perl編寫的FTP應用程序無法連接

use strict; 
use Net::FTP; 
use warnings; 

my $num_args = $#ARGV+1; 
my $filename; 
my $port; 
my $host; 
my $ftp; 



if($num_args < 2) 
{ 
    print "Usage: ftp.pl host [port] file\n"; 
    exit(); 
} 
elsif($num_args == 3) 
{ 
    $port = $ARGV[1]; 
    $host = $ARGV[0]; 
    $filename = $ARGV[2]; 
    print "Connecting to $host on port $port.\n"; 
    $ftp = Net::FTP->new($host, Port => $port, Timeout => 30, Debug => 1) 
     or die "Can't open $host on port $port.\n"; 
} 
else 
{ 
    $host = $ARGV[0]; 
    $filename = $ARGV[1]; 
    print "Connecting to $host with the default port.\n"; 
    $ftp = Net::FTP->new($host, Timeout => 30, Debug => 1) 
     or die "Can't open $host on port $port.\n"; 
} 

print "Usename: "; 
my $username = <>; 
print "\nPassword: "; 
my $password = <>; 

$ftp->login($username, $password); 
$ftp->put($filename) or die "Can't upload $filename.\n"; 

print "Done!\n"; 

$ftp->quit; 

在此先感謝。

+1

也許你應該詳細說明「不工作」部分。錯誤消息等。你怎麼知道它沒有連接? – TLP

+0

沒有錯誤消息。闡述不應該是必要的,它不會連接。也就是說,Net :: FTP-> new()失敗。而已。 感謝您的回答。 – Griffin

+0

Net :: FTP不能失敗,否則腳本會死掉。你到達用戶/密碼提示?你是否記得'chomp'用戶名和密碼? – TLP

回答

2

現在你已經有了你的答案<> - ><STDIN>,我想我看到了問題。當@ARGV包含任何內容時,<>是'魔術開放'。 Perl將@ARGV中的下一項解釋爲文件名,將其打開並逐行讀取。因此,我想你也許可以這樣做:

use strict; 
use Net::FTP; 
use warnings; 

use Scalar::Util 'looks_like_number'; 

if(@ARGV < 2) 
{ 
    print "Usage: ftp.pl host [port] file [credentials file]\n"; 
    exit(); 
} 

my $host = shift; # or equiv shift @ARGV; 
my $port = (looks_like_number $ARGV[0]) ? shift : 0; 
my $filename = shift; 

my @ftp_args = (
    $host, 
    Timeout => 30, 
    Debug => 1 
); 

if ($port) 
} 
    print "Connecting to $host on port $port.\n"; 
    push @ftp_args, (Port => $port); 
} 
else 
{ 
    print "Connecting to $host with the default port.\n"; 
} 
my $ftp = Net::FTP->new(@ftp_args) 
    or die "Can't open $host on port $port.\n"; 

#now if @ARGV is empty reads STDIN, if not opens file named in current $ARGV[0] 

print "Usename: "; 
chomp(my $username = <>); #reads line 1 of file 
print "\nPassword: "; 
chomp(my $password = <>); #reads line 2 of file 

$ftp->login($username, $password); 
$ftp->put($filename) or die "Can't upload $filename.\n"; 

print "Done!\n"; 

$ftp->quit; 

然後,如果你有一個文件(比如說名爲CRED)一些連接creditials像

myname 
mypass 

然後

$ ftp.pl host 8020 file cred 

會打開主機:8020用於在cred中使用憑證的文件。

我不確定你想這樣做,它只是如何<>工作。

相關問題