Perl的ftp----put文件

前端之家收集整理的这篇文章主要介绍了Perl的ftp----put文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

工作需要,经常要更新一些运行包,但是每次手工去ftp,既麻烦,还浪费时间.于是就用Perl写了一个通过配置文件自动ftp的小工具.采用perl主要是考虑它的跨平台性,当然了用python等也可以.
配置文件里边可以指定主机,用户名,密码,要传输的文件等等.


代码如下:
#!/usr/bin/perl
use Net::FTP;
use Class::Struct;

struct FtpInfo => {
host => '$',
user => '$',
password => '$',
tasks => '@',#FtpTask list
};

struct FtpTask => {
dir => '$',
files => '@',
remoteDir => '$',
};

Main:
@ftps = &InitTasks;

open(LOG,">>log.txt") or die(" Open log.txt error");
print LOG "/n/n#######Start:".localtime()."/n";

foreach(@ftps) {
&PutFiles($_,LOG);
}
print LOG "#######End:".localtime();
close(LOG);
sub InitTasks {
my @ftps = ();
local $ftpCount = 0;

open(CONF,"idnms.conf") or die("cant open file:idnms.conf");

while ($line = ) {
next if $line =~ /^#/;# the '#' is comment.
next if $line =~ /^/s*$/;# ignore empty line
$line =~ s/(^/s+)|(/s*$)//;#trim

if ($line =~ /^/[/d*/w*$/]/ ) {#prcess []
$ftpCount++;
$ftpInfo = new FtpInfo;
$ftps[$ftpCount-1] = $ftpInfo;

$tasksCount = 0;
next;
}
@attr = split(/=/,$line);
$ftpInfo->host($attr[1]),next if $attr[0] eq "host";
$ftpInfo->user($attr[1]),next if $attr[0] eq "user";
$ftpInfo->password($attr[1]),next if $attr[0] eq "password";

if ( $attr[0] =~ /^task:/ ) {
($dir,$fs,$remote) = split(/;/,$attr[1]);
@files = split(/,/,$fs);
$task = new FtpTask(dir=>$dir,
files=>[@files],
remoteDir=>$remote);
$ftpInfo->tasks($tasksCount++,$task);
}
}
close(CONF);
return @ftps;
}

sub PutFiles {
my $ftpInfo = shift;
my $LOG = shift;

my $ftp = Net::FTP->new($ftpInfo->host)
or die("Cant connect to " . $ftpInfo->host);
$msg = "/nconnect to host:".$ftpInfo->host."/n";
print LOG $msg;
print $msg;
$ftp->login($ftpInfo->user,$ftpInfo->password)
or die("Cant login in:",$ftp->message);

$ftp->binary();
foreach $task (@{$ftpInfo->tasks}) {
$ftp->cwd($task->remoteDir)
or die("Cant go to the remote dir:",$ftp->message);

foreach $file (@{$task->files}) {
$ftp->put($task->dir."/".$file,$file)
or die(" Cant put file:".$file,$ftp->message);
$msg = "Put file:".$file." over,on ".localtime()."/n";
print LOG $msg;
print $msg;
}
}

$ftp->quit();
}

配置文件格式如下:
[说明]host=xxx.xxx.xxx.xxxuser=user1password=user1task:xx1=本地路径;文件列表;远程主机路径task:xx2=本地路径;文件列表;远程主机路径

猜你在找的Perl相关文章