perl实例之简单的FTP客户端

发布时间:2019-10-19编辑:脚本学堂
本文分享一个perl实例代码,实现一个简单的ftp客户端,学习下POSIX与Sys::Hostname模块的用法。有需要的朋友参考下。

perl实现一个简单的Ftp客户端。
代码:
 

复制代码 代码示例:

#!/usr/bin/perl -w
#
use warnings;
use strict;
use POSIX qw(O_RDWR O_CREAT O_EXCL tmpnam);
use Sys::hostname; # for 'hostname'

die "Simple anonymous FTP command line clientn Usage: $0 <server> <command>n" unless scalar(@ARGV)>=2;

my ($ftp_server,@ftp_command)=@ARGV;

my $ftp_resultfile;
do {
    $ftp_resultfile = tmpnam();
    sysopen FTP_RESULT, $ftp_resultfile, O_RDWR|O_CREAT|O_EXCL;
} until (defined fileno(FTP_RESULT));

if (open (FTP, "|ftp -n > $ftp_resultfile 2>&1")) {
    print "Client running, sending commandn";

    print FTP "open $ftp_servern";
    my $email=getlogin.'@'.hostname;
    print FTP "user anonymous $emailn";
    print FTP "@ftp_commandn";
    close FTP;
} else {
    die "Failed to run client: $!n";
}

print "waiting for responsen";
my @ftp_results = <FTP_RESULT>;
check_result(@ftp_results);
close FTP_RESULT;
unlink $ftp_resultfile;
print "Donen";

sub check_result {
     return unless @_;
     print "Response:n";
     print "t$_" foreach @_;
}