passa2 - Um sistema de backup/sincronização/cópia de arquivos em SHell Script

Publicado por Marcelo 22/11/2008

[ Hits: 6.757 ]

Homepage: sites.google.com/sites/foo4funreborn/

Download passa2




Este script automatiza a cópia de diretórios e arquivos para um pendrive (ou pasta) organizando-os por data e nome do host. Ele permite arquivar e restaurar tentando manter sempre a mesma estrutura de arquivos. Exemplo:

passa2 -config (na máquina 1)
passa2 -saveit /home/mbianchi/projetos/tese (na máquina 1)
passa2 -restore (na máquina 2)

  



Esconder código-fonte

#!/bin/bash
##########################################################################
# This file is in UTF-8
# Este arquivo esta formatado em UTF-8
#  Writen by Bianchi @ 2008 under GPL
##
##### Changelog 
#
#0.5.0 - 31/08/2008
#
# - Added the machine part to identify 
#   in which machine the tar was created.
#
#0.3.0 - 15/03/2008
#
# - Changed archive method. The tar file is created compressed directly on the pendrive
#   the info file is created at the directory that you invoked the passa2 script.
#
# - Every change and comments and user interaction should be made in english to give
#   a little chance for other people to use it.
#    
# - Removed the option to compress the tar file, the file from now on are always compressed
#   with gzip
#
# - Added pre-startup check of need binaries
#   
#0.2.7 - Sem chanelog ....
#####

function about()
{
 cat << EOF 
Passa2 - Version 0.5

Modo de Uso:
  passa2 [options] [FILE||DIRECTORY]
 
Opções:

  -h|-about   - Sobre (esta ajuda)
  -saveit   - Salva um arquivo ou diretório para o diretório de arquivo
  -restore   - Restaura um arquivo do diretório de arquivo
  -list      - Lista os arquivos disponíveis no diretório de arquivos
  -config   - Configura o script
EOF
}
 
function termina()
{
 #Final 
 echo -e "\nI:> Done !"
 exit
}

function inicializa()
{
 ans=""
 while [ ! -d "$ans" ]
 do
  echo "Entre com o nome do diretório a ser usado para arquivo ?"
  read ans
  export destd=$ans
 done
}

function loadconfig()
{
 export v=0
 for i in gzip gunzip tar mktemp awk sed cut basename dirname
 do
   [ ! -x "`which $i`" ] && echo "No $i program, can't run." && exit
   [ $v -eq 1 ] && echo "$i pronto !"
 done
 
 if [ -f ~/.passa2rc ] 
 then
   source ~/.passa2rc
 else
  echo "Ooops sem arquivo de configuração."
  inicializa
  saveconfig
  loadconfig
 fi
 
 [ "Z$destd" = "Z" ] && echo "Diretório de transporte não definido, run config !" && exit 
 [ ! -d $destd ] && echo "Diretório de transporte ($destd) não existe !" && exit 
}

function saveconfig()
{
 echo "export destd=$destd" > ~/.passa2rc
}

function getlistoffiles()
{
 if [ "Z`ls -1 $destd/`" != "Z" ]
 then
  ls -1 $destd/* | sort
 fi
}

function listfiles()
{
 n=1
 echo -e "\n\e[0;31;1mArquivos existentes:\e[m"
 for i in `getlistoffiles`
 do
  nome=`basename $i .tar.gz`
  tamanho=`du -hs $i| awk '{print $1}'`

  ref=`echo $nome | awk -F"_" '{ if (NF == 3) {print $3} else  {print $2}}'`
  machine=`echo $nome | awk -F"_" '{ if (NF == 3) {print $2} else  {print "---"}}'`
  data=`echo $nome | awk -F"_" '{print $1}'`

  ano=`echo $data | cut -c1-4`
  dia=`echo $data | cut -c7-8`
  mes=`echo $data | cut -c5-6`
  hora=`echo $data | cut -d"-" -f 2 | awk '{print substr($1,1,2)":"substr($1,3,2)":"substr($1,5,2)}'`
  echo -e "\e[0;34;1m  $n:\e[m $ref\t ($dia/$mes/$ano)-($hora) [$tamanho] (\e[0;32;1m${machine}\e[m) "
  n=$(( n + 1 ))
 done
}

############## Real begin

#########################################################################################
#########################################################################################
if [ "Z$1" = "Z-h" -o "Z$1" = "Z-about" ]
then
  about
  termina
fi

#########################################################################################
#########################################################################################
if [ "Z$1" = "Z-config" ]
then 
 inicializa
 saveconfig
 loadconfig
 termina
fi

#########################################################################################
#########################################################################################
# Configuração Inicial, carregando preferencias
loadconfig

#########################################################################################
#########################################################################################
if [ "Z$1" == "Z-list" ]
then
 listfiles
 termina
fi

#########################################################################################
#########################################################################################
if [ "Z$1" == "Z-saveit" ]
then
 shift
 
 element=$1
 if [ "Z$element" == "Z" ]
 then
  echo "Elemento não é válido !"
  exit
 fi
 
 from=`dirname $element`
 fromfilename=`basename $element`

 cd $from
 [ $? -eq 0 ] && realfrom=`pwd` || exit

 cd $realfrom 
 # We do not accept .... 
 [ -L $fromfilename ] && type="link" && echo "I:> Elemento é um dispositivo tipo LINK !" && exit
 [ -c $fromfilename ] && type="char" && echo "I:> Elemento é um dispositivo tipo CHAR !" && exit
 [ -b $fromfilename ] && type="block" && echo "I:> Elemento é um dispositivo tipo BLOCK!" && exit
 [ -p $fromfilename ] && type="pipe" && echo "I:> Elemento é um dispositivo tipo PIPE !" && exit
 
 # We accept ...
 [ -d $fromfilename ] && type="dir" && echo "I:> Elemento é um directório  !"
 [ -f $fromfilename ] && type="file" && echo "I:> Elemento é um arquivo !"
 
 #Data do arquivo
 data=`date +%Y%m%d-%H%M%S`
 
 #Nome da máquina
 machine=`uname -n`
 if [ "Z${machine}" == "Z" ] 
 then
     machine="UNK"
 fi

 #Gerando arquivo de informações (filesystem)
 export TMPDIR=.
 tmfile=`mktemp`
 unset TMPDIR

 cat << EOF > $tmfile
#PASSA2AT
export from=$from
export fromfilename=$fromfilename
export realfrom=$realfrom
export type=$type
export data=$data
export machine=$machine
EOF

 #Nome do arquivo tar
 tarfile=$destd/${data}_${machine}_${fromfilename}.tar.gz
 
 #Add the info file + path
 echo -e "I:> Adicionando ... \n"
 tar cvf - $tmfile $fromfilename | gzip -c > $tarfile
 
 #erasing tmfile
 rm $tmfile
 
 termina
fi

#########################################################################################
#########################################################################################
if [ "Z$1" == "Z-restore" ]
then
 listfiles
 echo -n "Extract which file: "
 read ans
 f=`getlistoffiles | head -n $ans | tail -1`
 f=`basename $f`
 
 [ ! -f $destd/$f ] && echo "Where is the file: $f ?" && exit
 tempd=`mktemp  -d`
 [ $? -ne 0 ] && echo "Error criating the temporary directory !" && exit
 echo "" 
 echo "I:> Restoring: $f"
 cd $tempd 2> /dev/null
 [ $? -ne 0 ] && echo "Where is the temporary directory?" && exit
 
 echo "I:> Extracting"
 gunzip -c $destd/$f  | tar xf -
 
 # Lendo o index
 indexfile=`ls -1 tmp.??????????`
 [ "Z$indexfile" == "Z" -o ! -f ${indexfile} ] && echo "Can't find index file" && exit
 echo -n "I:> Index file is: $indexfile: "
 
 if [ "Z`sed  -ne '1p' $indexfile`" != "Z#PASSA2AT" ]
 then 
   echo "Fail in `pwd`."
   exit
 else
  echo "Ok."
  source $indexfile
  echo " I:> Restaurando em: ($from) objeto: ($fromfilename) tipo: ($type)"
 fi

 if [ -d $realfrom  ]
 then
   echo "I:> Usando caminho real: $realfrom"
   cd $realfrom
 else
  if [ -d $HOME/$from ]
  then
   echo " I:> Usando caminho absoluto de $HOME/$from"
   cd $HOME/$from
  else
   echo " E:> Não sei onde restaurar."
   echo "  I:> OP1 -> $HOME/$from Não Existe."
   echo "  I:> OP2 -> $realfrom Não Existe."
   echo "  I:> Arquivo foi extraido em: $tempd, saindo agora."
   exit
  fi
 fi

 case "$type" in
 dir)
  echo " I:> Restaurando diretório: ($fromfilename)."
  if [ -e $fromfilename ]
  then 
   echo " E:> Objeto existe, o que fazer?"
   echo "  I:> Arquivo foi extraido em: $tempd, saindo agora."
   exit
  else
   res=`mv $tempd/$fromfilename . 2>&1`
   if [ $? -eq 0 ]
   then 
    rm -rf $tempd
    echo -e " I:> Restauração concluida.\n"
    ls -l1d $fromfilename
   else
    echo " E:> Restauração falhou."
    echo "  I:> Comando mv não conseguio mover de: $tempd/$fromfilename para `pwd`"
    echo "   L:> Erro retornado pelo comando:"
    echo "       $res"
    echo "  I:> Arquivo foi extraido em: $tempd, saindo agora."
    exit
   fi
  fi
 ;;

 file)
  echo "Não sei restaurar arquivos."
 ;;

 *) 
  echo "Opa !! Nao deveria acontecer tipo '*'."
  exit
 ;;
 esac
 termina
fi


#########################################################################################
#########################################################################################
# Você não forneceu nenhuma opção (mostrando a ajuda)
about

Scripts recomendados

Instalação automática do Nagios

Fluxbox - Slideshow de wallpapers aleatórios

Limpando memória em cache do sistema!!!

Go Script - Inicia sessões ssh

Load Balance


  

Comentários
[1] Comentário enviado por HelioCampos em 23/11/2008 - 16:36h

Boa senhor... hehehe

[2] Comentário enviado por m.tchelo em 24/11/2008 - 10:19h

Sempre as ordens .....


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts