在发布网站的时候,由于要更新的文件比较多,有时候漏传,或者传错了文件,这样后果是很严重的,直接引起网站的异常,所以写了一个自动同步测试服务器的程序,以批量完成文件的更新。
环境,一台测试服务器,一台网站服务器
需求,将测试服务器更新的文件拉取到网站服务器上,网站对应的目录结构都相同。
思路,用perl实现ftp的下载机制,自动将更新文件村放到相应目录,将更新的旧文件按照当前日志进行备份,同时显示更新文件的进度(百分比)。
执行结果如下:
[root@drbd-2 crontab]# ./test.pl
60% [========================================== ]
3 files is download ok!
2 files is lost...........
this files have losted :
/var/ftp/pub/aa
/var/ftp/pub/bb
代码如下:
#!/usr/bin/perl -w
use strict;
use Net::FTP;
use File::Copy;
use Date::Manip;
use File::Basename;
use Term::ProgressBar;
my $server = '192.168.1.100';
my $port = '21';
my $user = 'upload';
my $pw = '123456';
my $file = '/usr/local/crontab/upload';
my $backup_path = '/var/ftp/backup';
open FILE, "< $file"
or die "can't open $file..... ($!)";
my @failed_files = ();
sub ftp() {
my $ftp =
Net::FTP->new( $server, Port => $port, Debug => 0, Timeout => 600 )
or die "Cannot connect.\n";
$ftp->login( $user, $pw )
or die "Could not login.\n";
my $get = 0;
open F2, "< $file" or die $!;
my $number = grep { !/^\s*$/ } ;
close F2;
my $progress = Term::ProgressBar->new( { count => $number } );
$ftp->binary;
foreach () {
$_ =~ tr/\t //d;
if ( $_ =~ /^\s*$/ ) {
next;
}
chomp;
my $server_path = dirname($_);
my $server_file = basename($_);
my $temp_path = substr( $server_path, index( $server_path, "pub" ) );
my $local_path = $server_path;
if ( -e $local_path ) {
}
else {
$ENV{"umask"} = "022";
system("mkdir -p $server_path");
}
my $local_file = $server_path . "/$server_file";
if ( -e $local_file ) {
my $now_time = localtime();
my $today_dir = UnixDate( "$now_time", "%Y-%m-%d_%H:%M" );
system("mkdir -p $backup_path/$today_dir/$temp_path");
move( "$local_file", $backup_path . "/$today_dir/$temp_path" )
or die "mv file failed: $!";
}
$ftp->cwd($server_path)
or die "Cannot change working directory. $ftp->message\n";
if ( $ftp->get( $server_file, $local_file ) ) {
$progress->update( ++$get );
}
else {
push( @failed_files, $local_file );
}
}
print "$get files is download ok!" . "\n";
my $lost = $number - $get;
print "$lost files is lost..........." . "\n";
}
&ftp();
for (@failed_files) {
print;
print "\n";
}
阅读(1141) | 评论(0) | 转发(1) |