electroZ microsystems

ServerSettings


Voici un script perl simple et joli qui permet de modifier des paramètres d'un serveur a partir d'une bas de donnée.

L'idée est de copier un fichier de configuration dans une variable, effectuer des modifications sur cette variable a partir d'une base de donnée en utilisant les expressions régulières puis si le contenu de la variable diffère du fichier original, ce dernier est réecrit.

#!/usr/bin/perl
use DBI;  #mysql connections
# This script is started by a cron job.
# E.Droz 2 dec 2009

$bkpDir =   "/www/htaccess.bkp";
$logFile =  "/var/log/updateHtaccessFileFromDb.log";
$htaccess = "/www/.htaccess"; 

$now  = `date +%Y%m%d-%H%M%S`;  

#Read .htaccess file
$originalFile=$file=`cat $htaccess`;


#Remove auto lines ->> TequilaAllowIf uniqueid=128933 #auto until 21/12/2009 Batilus Lablet (Brutus Melina)#\n
$file =~ s/#auto until [0-9]{4}-[0-9]{2}-[0-9]{2}[ \w\-\(\)\:\.]*#\s*\nTequilaAllowIf uniqueid=[G0-9]{5,10}\s*\n//g;

# Connect to DB from DB
$dbh = DBI->connect( "DBI:mysql:database=webserver;host=localhost",'HtAccessExcept','somePass') or die "Database connexion echec! $DBI::errstr";

#Get data form DB
$sth = $dbh->prepare("SELECT * from HtAccessExceptions")  or die "Couldn't prepare statement: " . $dbh->errstr;
$sth->execute();


#Form .htaccess automatic lines
while ( ($id,$uid,$beginDate,$endDate,$name,$responsible,$status) = $sth->fetchrow_array())
{
   #data verifications
   if ($uid=~/^[G0-9]{5,10}$/ and $endDate=~/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/ 
   and $name=~/^[ \w\-\(\)\:\.]{3,}$/ and $responsible=~/[\w\-\(\)\:\.]{3,}/) 
   {
      $file .="#auto until $endDate $name (Responsible:$responsible)#\nTequilaAllowIf uniqueid=$uid\n";
      $dbh->do("UPDATE HtAccessExceptions SET status='active' WHERE id=$id") or print "Update error\n";
   }
   else
   {
      `echo "$now error on db data id=$id">> $logFile`;
      $dbh->do("UPDATE HtAccessExceptions SET status='error' WHERE id=$id") or print "Update error\n";
   }
};

#print $file;


if ($file ne $originalFile) 
{ 
   print "$now There is modification(s) in $htaccess\n" ;
   #bakup original file
   `cp $htaccess $bkpDir/htaccess.$now`; 
 
   #write new file
   open  FILE, ">$htaccess"; 
   print FILE $file; 
   close FILE;
}