script de backup recursif sur FTP avec upload uniquement des fichiers nouveaux ou modifiés

Présentation
But: Backup automatique d'un dossier sur un site FTP comme l'hébergement mutualisé OVH.
- Afin de minimiser les uploads, seuls les fichiers modifiers seront uploader.
- Comme via ftp on ne peut pas avoir le mtdm (date de derniere modification) pour un dossier, utilisation d'une base de données simple afin de stocker les fichiers avec leur taille et le mtdm local.
- Comme on ne peut pas accéder la base de donnée directement de l'extérieur par mesure de sécurité, utilisation d'un wrapper HTTP simple utilisant la methode POST.


Base de donnée et les 2 tables:
2 tables:
- backup_folder: pour stocker les chemins globaux des répertoires (et utiliser un id pour la table des fichiers)
- backup_file: stocke le nom du fichier, sa taille, la date de derniere modification, un boolean pour savoir si c'est un dossier
[code]
CREATE TABLE IF NOT EXISTS `backup_folder` (
`id` int(24) NOT NULL AUTO_INCREMENT,
`name` varchar(1024) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `backup_file` (
`id` int(24) NOT NULL AUTO_INCREMENT,
`name` varchar(256) NOT NULL,
`size` int(32) NOT NULL,
`mtime` int(32) NOT NULL,
`path` int(24) NOT NULL,
`isDir` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `c_inode` (`name`,`path`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;;
[/code]



Interface cgi pour la base de donnée:
Simple interface en post. 4 actions:
- ls: to list a directory:
[codeinline]Data: action=ls&folder=D:/Mat/backupTest[/codeinline]

- put: pour ajouter un fichier ou un dossier
[codeinline]Data: action=put&folder=D:/Mat/backupTest&file=2014-7-13.13.45.backupFTP.txt&size=0&mtime=1407912313&isDir=0[/codeinline]

- update: pour actualiser la date de derniere modification et la taille du fichier (et donc uploader la nouvelle version)
[codeinline]Data: action=update&folder=D:/Mat/backupTest&file=2014-7-13.13.44.backupFTP.txt&size=1733&mtime=1407912282&isDir=0[/codeinline]

- del: pour supprimer un fichier ou un dossier (recursivement on supprime tous les sous dossiers/fichiers)
[codeinline]Data: action=del&folder=D:/Mat/backupTest/txt&file=codecs.txt&isDir=0[/codeinline]


Le code (En haut du fichier, juste les parametres de la base de donnée a changer):
[code]
#!/usr/bin/perl
use strict;
use CGI;
use DBI;

use vars qw/
$cgi $action $folder $file $size $mtime $isDir
%DB $dbh $dsn $sql $sth
/;

%DB = (
dbname => 'backup',
host => 'xxxxxxx',
login => 'xxxxxxxx',
pass => 'xxxxxxx''
);


$cgi=new CGI;
print $cgi->header('text/html');

#print "HELLO\n";

$action = $cgi->param('action');
$folder = $cgi->param('folder');
$file = $cgi->param('file');
$size = $cgi->param('size');
$mtime = $cgi->param('mtime');
$isDir = $cgi->param('isDir');

#warn("action: $action, folder: $folder, file: $file, size: $size, mtime: $mtime, isDir: $isDir");

if (!&db_connect()){
&quit("ERROR connecting DB... $DBI::errstr\n");
}

# List folder
if ($action eq 'ls'){
$sql=execute() || &quit("ERROR ls request: $DBI::errstr, sql: $sql\n");

my $nrows = $sth->rows;
if ($nrows == 0){
print "The directory $folder is not on the server\n";
}
for (my $k=0; $k < $nrows; ++$k){
my $res = $sth->fetchrow_hashref();
my $name = $res->{name};
my $size = $res->{size};
my $mtime = $res->{mtime};
my $isDir = $res->{isDir};
my $folder= $res->{folder_id};

print "$isDir $folder $mtime $size $name\n";
}

# add file
} elsif ($action eq 'put'){
# Check folder exists
$sth = $dbh->prepare("select id from backup_folder where name=\"$folder\";");
$sth->execute() || &quit("ERROR getting folder id for '$folder', $DBI::errstr\n");
if ($sth->rows != 1){
print "ERROR, there are no folder: $folder\n";
} else {
my $res = $sth->fetchrow_hashref();
my $folder_id = $res->{id};
$sql=execute() || &quit("ERROR inserting file '$file', $DBI::errstr\n");
print "File inserted";

if ($isDir) {
$sth = $dbh->prepare("insert into backup_folder (name) values (\"$folder/$file\");");
$sth->execute() || &quit("ERROR inserting new folder '$folder/$file', $DBI::errstr\n");

$sth = $dbh->prepare("select id from backup_folder where name=\"$folder/$file\";");
$sth->execute() || &quit("ERROR getting folder id for '$folder/$file', $DBI::errstr\n");
$res = $sth->fetchrow_hashref();
$folder_id = $res->{id};
print ", folder created, folder_id: $folder_id";
}
}



# update file
} elsif ($action eq 'update'){
# Check folder exists
$sth = $dbh->prepare("select id from backup_folder where name=\"$folder\";");
$sth->execute() || &quit("ERROR getting folder id for '$folder', $DBI::errstr\n");
if ($sth->rows != 1){
print "Error, there are no folder: $folder\n";
} else {
my $res = $sth->fetchrow_hashref();
my $folder_id = $res->{id};
$sql=execute() || &quit("ERROR updating file '$file', $DBI::errstr\n");
print "File Updated";
}

# delete file or folder
} elsif ($action eq 'del'){
$sth = $dbh->prepare("delete from backup_file where name=\"$file\";");
$sth->execute() || &quit("ERROR deleting file '$file', $DBI::errstr\n");

if ($isDir){
# delete its files
$sql=execute() || &quit("ERROR deleting files from folder '$file', $DBI::errstr\n");

# delete its folders
$sth = $dbh->prepare("delete from backup_folder where name like \"$folder/$file%\";");
$sth->execute() || &quit("ERROR deleting files from folder '$file', $DBI::errstr\n");
}

print "File deleted";

} else {
print "ERROR Wrong command\n";
}


$sth->finish() if (defined($sth));
&db_disconnect();

exit 0;

sub quit(){
my $msg = shift;
print "$msg";
$sth->finish() if (defined($sth));
&db_disconnect();
exit -1;
}

sub db_connect {
# Connection to the DB
$dsn = "DBI:mysql:database=$DB{dbname};host=$DB{host}";
$dbh = DBI->connect($dsn, $DB{login}, $DB{pass}) or return 0;

return 1;
}

sub db_disconnect {
# Disconnect from the DB
$dbh->disconnect() if (defined($dbh));
}
[/code]




Script d'upload:
Syntax: backupFTP.pl (-h)? (-v)? (-f DEL_FILES)?
-h: help
-v: verbose (or debug) mode
-f: if followed by DEL_FILES, then force deleting files on server that doesn't exist locally anymore

Interception du Ctrl+C et des erreurs FTP ou HTTP afin de fermer proprement le script et d'afficher le résumé de ce qui a pu etre upload.
En cas d'interuption du script avant la fin, il suffit de le relancer et il finira le boulot.
Un fichier log et créer dans le dossier local qui contient la meme chose que le stdout.


Le code (En haut du fichier, juste les parametres du serveur FTP a changer ainsi que l'url de l'interface cgi pour la base de donnée):
[code]
#!/usr/bin/perl
#########################################################
# * Auteur : ramislebobl #
# * Date : 11/08/2014 #
# * Version : Windows (ActivePerl) #
# * Packages : Net::FTP, Try::Tiny #
# * Objectif : Backup files over FTP #
# Use 2 DB tables to track the modification dates. #
# an HTTP wrapper is used to manage the DB #
#########################################################
use strict;
use Net::FTP;
use Try::Tiny;
use LWP::UserAgent;
use Getopt::Std;

use vars qw/
$folderBackup
%FTP $ftp @dir $nbMaxTry $timeBeforeTryAgain
$HTTP $ua $http $resHTTP
@deletedFiles
$debug @error $DEL_FILES
$nbFileUploaded $sizeUploaded
$startTime $endTime $logFile $logFileName
/;

$folderBackup = 'D:\Mat\backupTest';
$HTTP = 'http://URL/dbFtpBackup.cgi';


%FTP = (
host => 'xxxxxxxx',
path => '/Backup',
port => 21,
passive => 1,
login => 'xxxxxxx',
pass => 'xxxxxxxx'
);


$nbMaxTry = 10;
$timeBeforeTryAgain = 1;
$debug = 0;
$DEL_FILES = 0;

$SIG{INT} = \&quit;

&get_options();


$ua = LWP::UserAgent->new;
$ua->agent("FtpBackup/1.0");
$ua->ssl_opts(verify_hostname=>0);


$startTime = time();
$nbFileUploaded = 0;
$sizeUploaded = 0;

# Open log file
my ($sec,$min,$hour,$numday,$month,$year,$weekday,$yearday,$isdst) = localtime($startTime);
$year += 1900;
$logFileName = "$year-$month-$numday.$hour.$min.backupFTP.txt";
open my $logFile, '>>', $logFileName || die "Can't create log file $logFileName\n";


# Connect to the FTP server
my $res = &ftpConnect();
if ( $res =~/^Cannot.*$/){
&quit($res);
}


# Do the job
&backupFolder($folderBackup, $FTP{path}, 0);

&quit("SUCCESS");

exit 0;




sub quit(){
my $msg = shift;

# Sum up the number of files that have been uploaded and the total size
my $endTime = time();
my $duration = $endTime - $startTime;
&log("\n\n==> $msg\n");
&log("SUM UP:\n");
&log("\t- $nbFileUploaded files have been uploaded.\n");
&log("\t- total size: ".&getReadableSize($sizeUploaded)."\n");
&log("\t- duration: ".&getReadableDuration($duration)."\n");

# List files on the server that doesn't exist locally anymore
# (maybe delete them or just list them so possible to do it manually...)
my $nbDeletedFiles = $#deletedFiles + 1;
if ($nbDeletedFiles > 0){
&log("\nThere are $nbDeletedFiles files that were deleted locally but are still on the server:\n");
&log("(We are deleting them now as you choose to. Please wait a moment...)\n") if ($DEL_FILES);
foreach my $deletedFile (@deletedFiles){
&log("\t- $deletedFile->{servDir}/$deletedFile->{name}");
if ($deletedFile->{isDir}){
&log(" (directory)\n");
} else {
&log(" (size: $deletedFile->{size} B)\n");
}

# Force deletion of the files on the server that have been deleted locally
# (option -f DEL_FILES of the script)
if ($DEL_FILES){
my $deletionOK = 1;
try{
$ftp->cwd($deletedFile->{servDir});
if ($deletedFile->{isDir}){
$ftp->rmdir($deletedFile->{name}, 1);
} else {
$ftp->delete($deletedFile->{name});
}
} catch {
$deletionOK = 0;
&log("Issue deleting file on server...\n");
};

# delete from the DB
if ($deletionOK){
&dbDelFile($deletedFile->{name}, $deletedFile->{path}, $deletedFile->{isDir});
}
}
}
}

&log("\nmessage");
my $pwdRemote=$ftp->pwd();
&log("Directory on the server: $pwdRemote\n");

# 3.: Check which files needs to be uploaded
&log("Uploading files:\n");

foreach my $file (@files){
my $needBackup = 1;
my $oldVersionOnServ = 0;
foreach my $servFile (@servFiles){
if ($servFile->{name} eq $file->{name}) {
if ($servFile->{mtime} >= $file->{mtime}){
$needBackup = 0;
} else {
$oldVersionOnServ = 1;
}
last;
}
}

if ($needBackup){
&log("\t- $folderName\\$file->{name}, size: ".$file->{size}.", mtime: ".$file->{mtime}."\n");
my $errorUpload = 0;
try {
$ftp->put("$folderName\\$file->{name}");
} catch {
&log("ERROR during upload...\n");
$errorUpload = 1;
push(@error, { name => $file->{name},
path => $folderName,
size => $file->{size},
isDir => 0

}
);
};

if (!$errorUpload){
++$nbFileUploaded;
$sizeUploaded += $file->{size};
if (! $oldVersionOnServ){
&dbPutFile($file->{name},$file->{size},$file->{mtime},$folderName,0);
} else {
&dbUpdateFile($file->{name},$file->{size},$file->{mtime},$folderName,0);
}
}
}
}
}


# 4.: Check on the server for files that have been deleted locally
foreach my $servFile (@servFiles){
my $fileExistLocally = 0;

# it's a folder
if ($servFile->{isDir}){
foreach my $folder (@folders){
if ($servFile->{name} eq $folder->{name}) {
$fileExistLocally = 1;
last;
}
}
# it's a file
} else {
foreach my $file (@files){
if ($servFile->{name} eq $file->{name}) {
$fileExistLocally = 1;
last;
}
}
}

if (! $fileExistLocally){
push(@deletedFiles, { name => $servFile->{name},
path => $folderName,
servDir => $servDir,
size => $servFile->{size},
isDir => $servFile->{isDir}
}
);
}
}



# 5.: backup folder content recursively
foreach my $folder (@folders){
if ($onlyCheckDeletedFiles){
&backupFolder($folderName.'\\'.$folder->{name}, $servDir.'/'.$folder->{name}, 1);
} else {
my $needBackup = 1;
my $oldVersionOnServ = 0;
foreach my $servFile (@servFiles){
# if already on serv
if ($servFile->{isDir} && ($servFile->{name} eq $folder->{name}) ) {
# if serv mtime more recent nothing to do
if ($servFile->{mtime} >= $folder->{mtime}){
$needBackup = 0;
}
$oldVersionOnServ = 1;
# print "dir found, oldVersionOnServ= $oldVersionOnServ\n" if ($debug);
last;
}
}

if ($needBackup){
&log("\t+ Folder $folder->{name}\n");
my $errorCreateFolder = 0;
if (!$oldVersionOnServ){
# print "Create folder\n" if ($debug);
try {
$ftp->mkdir($folder->{name});
} catch {
&log("Error creating folder on the server...\n");
$errorCreateFolder = 1;
};

if (! $errorCreateFolder){
&dbPutFile($folder->{name}, 0, $folder->{mtime}, $folderName, 1);
}
} else {
# print "Update folder\n" if ($debug);
&dbUpdateFile($folder->{name}, 0, $folder->{mtime}, $folderName, 1);
}

if (!$errorCreateFolder){
&backupFolder($folderName.'\\'.$folder->{name}, $servDir.'/'.$folder->{name}, 0);
$ftp->cwd($servDir) || &quit("ERROR Cannot access server directory '$servDir', $ftp->message");
if ($debug){
my $pwdRemote=$ftp->pwd();
&log("Directory on the server: $pwdRemote\n");
}
}

# No need to backup anything,
# just check if there are files on server that have been deleted locally
} else {
&backupFolder($folderName.'\\'.$folder->{name}, $servDir.'/'.$folder->{name}, 1);
}
}# onlyCheckDeletedFiles
} # foreach

} # end function


sub log(){
my $txt = shift;
print $txt;
print $logFile $txt;
}


sub ftpConnect(){
my $nbTry = 0;
my $connected = 0;
$ftp = undef;
while ( !$connected && ($nbTry < $nbMaxTry) ){
try{
$ftp=Net::FTP->new($FTP{host}, (Passive =>$FTP{passive},Timeout => 120, Debug => 0));
}
catch {
&log("[Error dans le module FTP] TimeOut sur la connection :s\n");
};
++$nbTry;
if (defined($ftp)){
$connected=1;
}
else{
sleep($timeBeforeTryAgain);
}
}

if ($nbTry < $nbMaxTry){
$nbTry = 0;
while ( !($ftp->login($FTP{login},$FTP{pass})) && ($nbTrycwd($FTP{path}) || return "Cannot go to directory '$FTP{path}', $ftp->message\n";
return 1;
}
else{
return "Cannot go to path $FTP{path}, ".$ftp->message."\n";
}
=cut
}


sub ftpQuit(){
try{
$ftp->quit if (defined($ftp));
}
catch{
&log("[Error dans le module FTP] le Quit a eu un pb... :s\n");
};
}


sub dbListDir(){
my ($folder, $servFilesRef) = @_;
$folder =~ s/\\/\//g;
&http_req("action=ls&folder=$folder");
my @lines = split("\n", $resHTTP->content);

my $nbFiles = 0;

for (my $k=0; $k [$k] = { isDir => $1,
folder => $2,
mtime => $3,
size => $4,
name => $5 };
++$nbFiles;
}
}

return $nbFiles;
}


sub dbUpdateFile(){
my ($name, $size, $mtime, $path, $isDir) = @_;
$path =~ s/\\/\//g;
&http_req("action=update&folder=$path&file=$name&size=$size&mtime=$mtime&isDir=$isDir");
}


sub dbPutFile(){
my ($name, $size, $mtime, $path, $isDir) = @_;
$path =~ s/\\/\//g;
&http_req("action=put&folder=$path&file=$name&size=$size&mtime=$mtime&isDir=$isDir");
}


sub dbDelFile(){
my ($name, $path, $isDir) = @_;
$path =~ s/\\/\//g;
&http_req("action=del&folder=$path&file=$name&isDir=$isDir");
}


sub http_req(){
my $data = shift;

$http = HTTP::Request->new(POST => $HTTP);
$http->content_type('application/x-www-form-urlencoded');

print "Data: $data\n" if ($debug);
$http->content($data);

my $nbTry = 0;
my $respOK = 0;
while ( !$respOK && ($nbTry < $nbMaxTry) ){
$resHTTP = $ua->request($http);
if (!$resHTTP->is_success) {
print "ERROR sending POST HTTP req to $HTTP (data: $data)\n";
} else {
if ($resHTTP->content !~ /^ERROR/) {
$respOK = 1;
}
}
}

if (!$respOK){
&quit("ERROR connecting the webserver $HTTP (data: $data)");
}

print $resHTTP->content."\n" if ($debug);
}


sub getReadableSize{
my $byte = shift;

if ($byte > 1024){
my $kb = int($byte/1024);
$byte -= $kb*1024;

if ($kb > 1024){
my $mb = int($kb/1024);
$kb -= $mb*1024;

if ($mb > 1024){
my $gb = int(100*$mb/1024);
$gb /= 100;
return "$gb Gb";
}

$mb+=int(100*$kb/1024)/100;
return "$mb Mb";
}
return "$kb Kb";
}

return "$byte b";
}


sub getReadableDuration {
my $sec=shift;
my $min;
my $hour;
if ($sec > 60){
$min=int($sec/60);
$sec-=$min*60;
if ($min>60){
$hour=int($min/60);
$min-=$hour*60;
return sprintf("%ih %imn %is",$hour,$min,$sec);
}
return sprintf("%imn %is",$min,$sec);
}
return sprintf("%is",$sec);
}


sub syntax(){
print
Téléchargement
Compatibilité
Linux Mac Windows
0  0 
Détails
Éditeur : ramislebob   +
Licence : GPL
Date de mise en ligne : 13 août 2014





 
Developpez.com décline toute responsabilité quant à l'utilisation des différents éléments téléchargés.
Responsable bénévole de la rubrique Perl : djibril -

Partenaire : Hébergement Web