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



为什么我的程序不工作?它拒绝连接到主机,我尝试了两个不同的服务器并验证了使用的是哪个端口。请注意,我对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] filen";
    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;

现在你已经有了答案<> -> <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;

如果你在一个文件中有一些连接凭证(比如名为credit),比如

myname
mypass
然后

$ ftp.pl host 8020 file cred

将打开host:8020为使用凭证的文件。

我不确定你想这样做,这只是<>的工作方式。

相关内容

  • 没有找到相关文章

最新更新