用Perl编写的FTP应用程序无法连接

时间:2011-10-16 20:35:36

标签: perl ftp timeout

为什么我的程序不起作用?它拒绝连接到主机,我尝试了两个不同的服务器并验证了使用了哪个端口。 请注意,在Perl方面我并不是很有经验。

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 个答案:

答案 0 :(得分:2)

现在您已经有了答案<> - &gt; <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)中有一些连接信用,如

myname
mypass

然后

$ ftp.pl host 8020 file cred

将使用cred中的凭据打开主机:8020 for file。

我不确定你是否愿意这样做,只是<>的工作原理。