加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl的ftp----put文件

发布时间:2020-12-15 20:57:43 所属栏目:大数据 来源:网络整理
导读:工作需要,经常要更新一些运行包,但是每次手工去ftp,既麻烦,还浪费时间.于是就用Perl写了一个通过配置文件来自动ftp的小工具.采用perl主要是考虑它的跨平台性,当然了用python等也可以. 在配置文件里边可以指定主机,用户名,密码,要传输的文件等等. 代码如下: #

工作需要,经常要更新一些运行包,但是每次手工去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=本地路径;文件列表;远程主机路径

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读