工作需要,经常要更新一些运行包,但是每次手工去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=本地路径;文件列表;远程主机路径
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。