Perl的ftp----put文件

本文介绍了一个使用Perl编写的自动化FTP工具,该工具可通过配置文件指定主机、用户名、密码及要传输的文件等信息,实现文件的批量上传和下载,提高了工作效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值