backup interativo em dialog

Publicado por Perfil removido (última atualização em 05/10/2012)

[ Hits: 11.027 ]

Download 5539.backup.sh




Este script em shell foi feito com o proposito de criar backups NÃO AUTOMATIZADOS, permitindo que o usuário preencha informações da forma que desejar.

O tamanho do script pode assustar os principiantes, mas é bem simples. Alterem seu conteúdo conforme sua necessidade, seja para interagir ou para automatizar o backup.

  



Esconder código-fonte

#!/bin/bash 
         #########################################################################################################
         ##############################               #########################################
         ##################           backup.sh          #################################
         ##############################               #########################################
         #########################################################################################################

         #########################################################################################################
         #########################################################################################################
         ######## O nome do script é backup.sh                        #########
         ######## Desenvolvido por Edson de Abreu Oliveira.                  #########
         ######## Versão: 2.0                              #########
         ######## Atualizado em 12/09/2012                        #########
         ######## -------------------------------------------------------------------------------------- #########
         ######## Script para ser executado em distros baseadas no debian, no proprio debian e CentOS   #########
         ######## Este script faz backups de arquivos e diretórios salvando localmente e remotamente.   #########
         ######## O script usa funções para ser executado.                  #########
         ######## a função iniciar é para iniciar o script.                  #########
         ######## a função parar é para parar o script.                     #########
         ######## Existe outras funções que tem a finalidade de inciar uma tarefa especifica      #########
         ######## Dentro da função start existe outras funções para fazer backups tais como      #########
         ######## Backup completo, backup de dados alterados recentemente            #########
         ######## backup remoto e funções para resturar cada tipo de backup feito.         #########
         #########################################################################################################
         #########################################################################################################

          data=$(date +%d-%m-%Y)
 iniciar()
 {
            #############################################################
            ############# Verifica Requisitos do sistema ################
            #############################################################

                                if [ -e $(which dd) -a -e $(which tar) -a -e $(which gzip) -a -e $(which dialog) -a -e $(which rsync) ]; then
                                   dialog --infobox ' checando sistema... ' 3 30
                                   sleep 2
            else
                                    echo "checando sistema..."
                echo -e "Pacotes necessários para script:{FONTE}33[31;1mrsync dialog gzip coreutils tar{FONTE}33[m,instale os pacotes para rodar sem problemas"
                exit 2
            fi

            ###################################################
            ########### Tela de apresentação do script  #######
            ###################################################

          NU=$( dialog --stdout --title 'OPÇÕES' --menu 'Escolha o tipo de backup ou restauração:' 0 0 0 \
         bkp-com  '- Backup Completo' \
         bkp-inc  '- Backup de dados alterados recentemente' \
         bkp-rem  '- Backup Remoto - salvar remotamente' \
         rest-bkp '- Restauração' \
         rest-rem '- Restauração de backup remoto' \
         sair     '- Sair do script' ) 

          [ -n "$NU" ] && OP="$NU" || OP=$(($NU + 1))

         case $OP in
          bkp-com)bkp-com;;
          bkp-inc)bkp-inc;;
          bkp-rem)bkp-rem;;
          rest-bkp)rest-bkp;;
         rest-rem)rest-rem;;
          sair)dialog --title "Opção escolhida" --infobox 'saindo do script' 3 20;exit 1;;
          1)dialog --title "CANCELAMENTO" --infobox 'O Botão CANCELAR foi apertado ou ESC foi presionado. saindo do script' 3 60;exit 1;;
          *) echo "Opção Inválida!!!";iniciar;;
 
         esac

 }

      #################################################################################################
      #################################################################################################
      ################    Backup Comnpleto de arquivos e ou diretorios           #################
      #################################################################################################
      #################################################################################################

 bkp-com()
 {

       dialog --title "Opção" --infobox ' Você escolheu a opção para fazer backup Completo de seus arquivos ' 3 75
        sleep 2

       ###################################################################################################
       # Entrada de informação: nome do backup, local de origem, local de destino, exclude e verificação #
       ###################################################################################################
         
         arq=$(dialog --stdout --ok-label "OK" --inputbox "Digite o nome do backup" 0 0)
         pat=$(dialog --stdout --title "Escolha o local de origem do backup" --ok-label "OK" --dselect / 10 70)
         patd=$(dialog --stdout --title "Escolha o local de destino do backup" --ok-label "OK" --dselect / 10 70)
         excluir=$(dialog --stdout --title "Escolha o diretório que deseja não incluir no backup" --ok-label "OK" --dselect $pat 10 70)

      ###############################################
      # Verifica se o valor das variáveis são nulas #
      ###############################################

                if [ -z "$arq" -o -z "$pat" -o -z "$patd" ];then
                        dialog --infobox "informação insuficiente, saindo do script..." 3 60 
         exit 1
      fi 

      #####################################################
      # Verifica se os locais de origem e destino existem #
      #####################################################

                if [  -e "$pat" -a -e "$patd" ];then
         sleep 0.23 
      else
         dialog --infobox "Local de origem ou destino não existe, saindo do script" 3 75
         exit 1
      fi

          ###########################################
          # Criando e Compactando arquivo do backup #
          ###########################################
         
         if [ -z $excluir ];then
            tar -zpcvf "$patd"/"$arq"-"$data".tar.gz "$pat" 2> /dev/null |dialog --progressbox " Dados sendo copiados e compactados:" 30 140
            sleep 2
         else
               tar --exclude $excluir -zpcvf "$patd"/"$arq"-"$data".tar.gz "$pat" 2> /dev/null |dialog \
                                       --progressbox " Dados sendo copiados e compactados:" 30 140
               sleep 2
         fi
          #########################################
          # verifica se o backup foi feito ou não #
          #########################################

           if test -e "$patd"/"$arq"-"$data".tar.gz;then
               dialog --title 'Tamanho do Backup' --infobox " Tamanho do backup é:$(du -h "$patd"/"$arq"-"$data".tar.gz)" 3 35
               sleep 4
               dialog --infobox 'Backup concluido com exeto...' 3 35
                exit 0
          else
              dialog --title "Erro" --infobox " backup não foi conlcuido com êxito " 3 35
               exit 1
          fi 
 
 }

         #########################################################################################
         #########################################################################################
         #############      Backup de dados alterados recentemente      #################
         #########################################################################################
         #########################################################################################

 bkp-inc()
 {

   dialog --title "Opção" --infobox 'Você escolheu a opção para fazer backup de dados criados e ou alterados recentemente' 3 95
    sleep 2
         
         ##########################################################################################
         ######################## Entrada de dados para fazer backup ##############################
         ##########################################################################################
         
               arq=$(dialog --stdout --ok-label "OK" --inputbox "Digite o nome do backup" 0 0)
                              pat=$(dialog --stdout --ok-label "OK" --title "Escolha o diretório de origem de backup" --dselect / 10 70)
                              patd=$(dialog --stdout --ok-label "OK" --title "Escolha de diretório para gravação de backup" --dselect / 10 70)

                  ###############################################
                  # Verifica se o valor das variáveis são nulas #
                  ###############################################

                               if [ -z "$arq" -o -z "$pat" -o -z "$patd" ];then
                                       dialog --infobox "informação insuficiente, saindo do script..." 3 60 
                        exit 1
                     fi 

                  #####################################################
                  # Verifica se os locais de origem e destino existem #
                  #####################################################

                               if [  -e "$pat" -a -e "$patd" ];then
                        sleep 0.23 
                     else
                        dialog --infobox "Local de origem ou destino não existe, saindo do script" 3 75
                        exit 1
                     fi

               ########################       
               #### Fazendo backup ####
               ########################

               find "$pat" -mtime -7 -type f -print |tar -zcpvf "$patd"/"$arq"-"$data".tar.gz -T - |dialog \
                                          --progressbox "Dados sendo copiados e empacotados:" 30 140
                #########################################
                # verifica se o backup foi feito ou não #
                #########################################

                if test -e "$patd"/"$arq"-"$data".tar.gz;then
                     dialog --title 'Tamanho do Backup' --infobox " Tamanho do backup é:$(du -h "$patd"/"$arq"-"$data".tar.gz)" 3 35
                     sleep 4
                     dialog --infobox 'Backup concluido com exeto...' 3 35
                      exit 0
                else
                  dialog --title "Erro" --infobox " backup não foi conlcuido com êxito " 3 35
                     exit 1
                fi

         
 }

            #################################################################################################
            #################################################################################################
            ########################      Backup    Remoto      #################################
            #################################################################################################
            #################################################################################################

 bkp-rem()
 {

      dialog --title "Opção" --infobox ' Você escolheu a opção para fazer backup e salvar em um host remoto' 3 75
      sleep 2
         ##########################################################################################
                        ######################## Entrada de dados para fazer backup ##############################
                        ##########################################################################################
                        
         texto="Insira o endereço do host remoto que salvará o backup, porta de acesso do ssh, diretório de destino e o nome do usuário que irá logar e salvar as alterações. NOTA: faça login com um usuário que tenha permissão de gravação no diretório do host remoto"

         ent=$(dialog --stdout \
         --ok-label "OK" \
         --title "Dados de entrada" \
         --form "$texto" 16 70 4 \
         "IP do host" 1 1 "" 1 20 50 0 \
         "Porta" 2 1 "22" 2 20 50 0 \
         "Local de Destino" 3 1 "" 3 20 50 0 \
         "Usuário" 4 1 "$USER" 4 20 50 0 )

               IP=$(echo "$ent" |head -1)
               PORT=$(echo "$ent" |head -2 |tail -1)
               patd=$(echo "$ent" |head -3 |tail -1)
               usu=$(echo "$ent" |tail -1)

         #####################################
         ### Verificando dados de entrada #### 
         #####################################
            
                if [ -z "$ent" ];then
                  dialog --infobox "Operação cancelada, saindo do script" 3 60
                  exit 1
                         elif [ -z "$IP" -o -z "$PORT" -o -z "$usu" ];then
                                 dialog --infobox "informação insuficiente, saindo do script..." 3 60 
                  exit 1
               fi 
               

                                        arq=$(dialog --stdout --ok-label "OK" --inputbox "Digite o nome do backup" 0 0)
                                        pat=$(dialog --stdout --ok-label "OK" --title "Escolha o diretório de origem de backup" --dselect / 10 70)

                                                ###############################################
                                                # Verifica se o valor das variáveis são nulas #
                                                ###############################################

                                                        if [ -z "$arq" -o -z "$pat" ];then
                                                                dialog --infobox "informação insuficiente, saindo do script..." 3 60 
                                                                exit 1
                                                        fi 

                                                #####################################################
                                                # Verifica se os locais de origem e destino existem #
                                                #####################################################

                                                        if [  -e "$pat" -a "$(echo "$(ssh -p "$PORT" "$usu"@"$IP" [ -e "$patd" ] && echo "0" || echo "1")")" -eq "0" ];then
                                                                sleep 0.23 
                                                        else  
                                                                dialog --infobox "Local de origem ou destino não existe, saindo do script" 3 75
                                                                exit 1
                                                        fi
               
               ########################
                #### Fazendo backup ####
               ########################

                                        tar -zcpvf - "$pat" 2> /dev/null | ssh -p "$PORT" "$usu"@"$IP" dd of="$patd"/"$arq"-"$data".tar.gz > /dev/null

                                         #########################################
                                         # verifica se o backup foi feito ou não #
                                         #########################################

                                        if [ "$(echo "$(ssh -p "$PORT" "$usu"@"$IP" [ -e "$patd"/"$arq"-"$data".tar.gz ] && echo "0" || echo "1")")" -eq "0" ];then
                                                dialog --title 'Tamanho do Backup' \
                  --infobox " Tamanho do backup é:$(ssh -p "$PORT" "$usu"@"$IP" du -h "$patd"/"$arq"-"$data".tar.gz)" 3 35
                                                sleep 3
                                                dialog --infobox 'Backup concluido com exeto...' 3 35
                                                exit 0
                                        else
                                                dialog --title "Erro" --infobox " backup não foi conlcuido com êxito " 3 35
                                                exit 1
                                        fi

                     

 }
            ################################################################################################
            ################################################################################################
            ####        Restauração do Backups completos e de dados alterados recentemente           #####
            ################################################################################################
            ################################################################################################

 rest-bkp()
 {

             #########################################################################################################
             #    questiona o usuário qual arquivo contém os dados a serem restaurados e aonde serão restaurados   #
             #########################################################################################################

           dialog --title "Opção" --infobox 'Você escolheu a opção para restaurar um backup completo e de dados alterados recentemente' 3 85
                   sleep 2

                        pat=$(dialog --stdout --title "Escolha o arquivo de backup para restaurar" --fselect / 10 65)
                        patd=$(dialog --stdout --title "Escolha o diretório para restauração do backup" --dselect / 10 65)

                   if [ -z "$pat" -o -z "$patd" ];then
                           dialog --title "Erro" --infobox "informação insuficiente, saindo do script..." 3 60
                           exit 1
                   elif [ ! -e $patd ];then
                           dialog --title "Erro" --infobox "Diretório "$patd" não existe, saindo do script..." 3 65
                           exit 1
                   fi

                #########################################################
                ########   Restauração do arquivo       #########
                #########################################################

                tar -zxvf $pat -C $patd 2> /dev/null |dialog --progressbox " Dados sendo restaurados: " 30 140
                 sleep 1

 }
            ##################################################################################################################
            ##################################################################################################################
            #####            Restauração de um Backup Remoto                    ########
            ##################################################################################################################
            ##################################################################################################################

 rest-rem()
 {
 
            dialog --title "Opção" --infobox 'Você escolheu a opção para restaurar um backup remoto' 3 65
            sleep 2

         ##########################################################################################
                        ######################## Entrada de dados para fazer backup ##############################
                        ##########################################################################################
                        
         texto="Insira o endereço do host remoto que tem o backup, porta de acesso do ssh, O caminho completo do arquivo de backup e o nome do usuário que irá logar e salvar as alterações. NOTA: faça login com um usuário que tenha permissão de gravação no diretório do host remoto"

         ent=$(dialog --stdout \
         --ok-label "OK" \
         --title "Dados de entrada" \
         --form "$texto" 16 70 4 \
         "IP do host"       1 1 "" 1 20 50 0 \
         "Porta"       2 1 "22" 2 20 50 0 \
         "Backup"       3 1 "" 3 20 50 0 \
         "Usuário"       4 1 "$USER" 4 20 50 0)

               IP=$(echo "$ent" |head -1)
               PORT=$(echo "$ent" |head -2 |tail -1)
               bkp=$(echo "$ent" |head -3 |tail -1)
               usu=$(echo "$ent" |tail -1)
         
          patd=$(dialog --stdout --title "Escolha para onde será restaurada a imagem de backup" --dselect / 10 70)

               #####################################
               ### Verificando dados de entrada #### 
               #####################################
            
                   if [ -z "$ent" -o -z "$patd" ];then
                  dialog --infobox "Operação cancelada, saindo do script" 3 50
                  exit 1
                         elif [ -z "$IP" -o -z "$PORT" -o -z "$usu" ];then
                                 dialog --infobox "informação insuficiente, saindo do script..." 3 55
                  exit 1
                  fi 

               #####################################################
                                        # Verifica se os locais de origem e destino existem #
                                        #####################################################

                                        if [  -e "$patd" -a "$(echo "$(ssh -p "$PORT" "$usu"@"$IP" [ -e "$bkp" ] && echo "0" || echo "1")")" -eq "0" ];then
                                                  sleep 0.23 
                                        else  
                                                  dialog --infobox "Local de origem ou destino não existe, saindo do script" 3 65
                                                  exit 1
                                        fi

                #########################################################
                ########   Restauração do arquivo       #########
                #########################################################

                ssh -p "$PORT" "$usu"@"$IP" dd if="$bkp" |tar -zxvf - -C $patd |dialog --progressbox "Dados sendo restaurados:" 30 140
                 sleep 1


 }

         ########################################################################################################
         ########################################################################################################
         #######################         Parando o script      ################################
         ########################################################################################################
         ########################################################################################################

 parar()
 { 

       dialog --yesno " Deseja realmente parar o script ? isto pode fazer com que alguma tarefa em execução não seja concluida e ocasionar perda de dados. " 0 0 
           if [ "$?" = "0" ];then
            pkill -term rsync 2> /dev/null
              pkill -term tar 2> /dev/null
                pkill -term backup.sh 2> /dev/null
                echo " processos finalizados..."
          else
              dialog --infobox " script continua em execução..." 0 0
          fi

 }
 
          case "$1" in
          start)iniciar;;
          stop)parar;;
          *)echo "O Paramentro é invalido,use start,stop ou restart.";;

          esac

Scripts recomendados

Cadastrando usuários no Squid através de Shell Script

Nautilus-script: Edite com o Gimp

pegaMAC - pega o endereço MAC da eth0

Script para instalar e configurar o samba no Damn Small Linux

Menu


  

Comentários
[1] Comentário enviado por gpxlnx em 04/09/2012 - 16:45h

Pabrens pelo script porem to com um problema ao executar

5539.backup.sh: 73: Syntax error: Bad function name

Baixei direto do site a linha é da funcao

73 bkp-com()
74 {

Ja verifiquei e a } fechando a funcao esta la porem nao funcionou no debian 6 pelos menos aqui cara

[2] Comentário enviado por removido em 04/09/2012 - 19:56h

Tudo bem amigo gpxlnx ?

baixei o script pelos links contidos nesta página e em seguida rodei o mesmo e executou sem problemas. também copiei o conteúdo do script apresentado acima e colei em um arquivo salvei e dei permissão de execução e rodou sem problemas. uso o Debian versão 6 também, mas já rodei o script no CentOS, Linux Mint e ubuntu e rodou sem problemas.

deixe seu endereço de e-mail para enviar o script em anexo para você.

qualquer coisa é só postar aqui, blz ?

abraço.

[3] Comentário enviado por gpxlnx em 05/09/2012 - 10:56h

Poxa eabreu, desculpe incomodalo, mas achei seu script mto bom por isso estou insistindo nele hehe parabens novamente

[4] Comentário enviado por removido em 05/09/2012 - 11:13h

Conseguiu rodar o script gpxlnx?


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts