Bonjour,
Je vous propose un nouvel élément à utiliser : script de backup recursif sur FTP avec upload uniquement des fichiers nouveaux ou modifiés (sans probleme d'affichage?..)
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 : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 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;;
Interface cgi pour la base de donnée:
Simple interface en post. 4 actions:
- ls: to list a directory:
Data: action=ls&folder=D:/Mat/backupTest
- put: pour ajouter un fichier ou un dossier
Data: action=put&folder=D:/Mat/backupTest&file=2014-7-13.13.45.backupFTP.txt&size=0&mtime=1407912313&isDir=0
- update: pour actualiser la date de derniere modification et la taille du fichier (et donc uploader la nouvelle version)
Data: action=update&folder=D:/Mat/backupTest&file=2014-7-13.13.44.backupFTP.txt&size=1733&mtime=1407912282&isDir=0
- del: pour supprimer un fichier ou un dossier (recursivement on supprime tous les sous dossiers/fichiers)
Data: action=del&folder=D:/Mat/backupTest/txt&file=codecs.txt&isDir=0
Le code (En haut du fichier, juste les parametres de la base de donnée a changer):
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285 #!/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)); }
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):
[code]
#!/usr/bin/perl
#########################################################
# * Auteur : Matthieu Bruel #
# * 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://www.aec-lataste.com/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(){
Qu'en pensez-vous ?
Partager