├── conf ├── bacula-dir.conf ├── bacula-fd.conf ├── bacula-sd.conf ├── bconsole.conf ├── clients-and-jobs.conf ├── clients-and-jobs │ ├── srv_bacula-fd.conf │ ├── srv_bacula-filesets.conf │ ├── srv_bacula-jobs.conf │ ├── srv_windows-fd.conf │ ├── srv_windows-filesets.conf │ └── srv_windows-jobs.conf ├── counters.conf ├── messages.conf ├── openssl.cnf.template ├── pools.conf ├── readme-english.md ├── readme.md ├── schedules.conf ├── scripts │ ├── _autochanger.sh │ ├── _bacula_certificates_generator.sh │ ├── _bacula_community_package.sh │ ├── _create_mysql_function │ ├── _delete_bootstrap_files │ ├── _delete_multiples_volumes.sh │ ├── _disable_backup_holidays.sh │ ├── _list_files_by_extension.ps1 │ ├── _password_generator.sh │ ├── _query.sql │ ├── _rclone_sync.sh │ ├── _send_telegram_mysql.sh │ └── _verify_jobs_mysql.sh └── storages.conf ├── convert_mysql_to_postgresql ├── import_postgresql.sh ├── mysql_to_postresql.sh └── readme.md ├── dicas ├── heartbeat_interval.md ├── maximum_concurrent_jobs.md └── mysql_sql-mode.md ├── firebird ├── delete_firebird_backup.ps1 ├── delete_firebird_backup.sh ├── make_firebird_backup.ps1 ├── make_firebird_backup.sh ├── readme-english.md └── readme.md ├── hyper-v ├── delete_backup_virtual_machine.ps1 ├── hyper-v_backup.ps1 └── make_backup_virtual_machine.ps1 ├── mssql ├── make_mssql_backup.ps1 ├── readme-english.md └── readme.md ├── mysql ├── _backup_mysql.sh ├── readme-english.md └── readme.md ├── pfsense ├── README.md └── _backup_pfsense.sh ├── postfix ├── generic ├── main.cf ├── readme-english.md ├── readme.md ├── sasl_passwd └── sender_relay ├── readme-english.md ├── readme.md ├── telegram ├── _send_telegram.sh ├── readme-english.md └── readme.md └── tutorial ├── bacula_install_centos7.txt ├── bacula_install_debian10.txt ├── bacula_install_debian9.txt ├── bacula_install_ubuntu_22.0.4.txt ├── baculum_install_centos7.sh ├── baculum_install_debian9.sh ├── upgrade_bacula.md ├── webacula_install_centos7.txt └── webacula_install_debian9.txt /conf/bacula-dir.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # bacula-dir.conf 3 | 4 | 5 | ######################################################################################## 6 | # Configuração do Diretor do Bacula 7 | Director{ 8 | Name = bacula-dir 9 | Description = "Sistema de Backup" 10 | DIRport = 9101 11 | QueryFile = "/etc/bacula/scripts/_query.sql" 12 | WorkingDirectory = "/etc/bacula/working" 13 | PidDirectory = "/etc/bacula/working" 14 | Heartbeat Interval = 300 seconds 15 | Statistics Retention = 365 days 16 | Maximum Concurrent Jobs = 50 17 | Password = "mKC0Bxz1hhrWj51J76qCnGYWXcKBdQPchlltirFaR/3s" 18 | Messages = Daemon 19 | } 20 | 21 | ######################################################################################## 22 | # Definições de Counters 23 | @/etc/bacula/counters.conf 24 | 25 | # Definição de Clients and Jobs 26 | @/etc/bacula/clients-and-jobs.conf 27 | 28 | # Definições de Schedules 29 | @/etc/bacula/schedules.conf 30 | 31 | # Definições de Pools 32 | @/etc/bacula/pools.conf 33 | 34 | # Definições de Storages 35 | @/etc/bacula/storages.conf 36 | 37 | # Definições de Messages 38 | @/etc/bacula/messages.conf 39 | 40 | 41 | ######################################################################################## 42 | # Configuração do serviço de catálogo 43 | Catalog { 44 | Name = MyCatalog 45 | dbdriver = "mysql" 46 | dbaddress = "localhost" 47 | dbport = "3306" 48 | dbname = "bacula" 49 | dbuser = "bacula" 50 | dbpassword = "bacula" 51 | } 52 | 53 | 54 | ######################################################################################## 55 | # Monitor do console 56 | Console { 57 | Name = bacula-mon 58 | Password = "CUKrbQL/wd5xHTbT9islSlU9sd6SIrusGz4IShs56d3u" 59 | CommandACL = status, .status 60 | } 61 | -------------------------------------------------------------------------------- /conf/bacula-fd.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # bacula-sd.conf 3 | 4 | # 5 | # List Directors who are permitted to contact this File daemon 6 | # 7 | Director { 8 | Name = bacula-dir 9 | Password = "wC9Tj32Wye8T4dLIZkEfHzWWzF6ipclKPSN9qFZpqsuV" 10 | } 11 | 12 | # 13 | # Restricted Director, used by tray-monitor to get the 14 | # status of the file daemon 15 | # 16 | Director { 17 | Name = bacula-mon 18 | Password = "U8SuezrkXs6A/AJu3OHEcmdAfbYwVMe10MGh2270oSIe" 19 | Monitor = yes 20 | } 21 | 22 | # 23 | # "Global" File daemon configuration specifications 24 | # 25 | FileDaemon { # this is me 26 | Name = bacula-fd 27 | FDport = 9102 # where we listen for the director 28 | WorkingDirectory = /etc/bacula/working 29 | Pid Directory = /etc/bacula/working 30 | Maximum Concurrent Jobs = 50 31 | Heartbeat Interval = 300 seconds 32 | # Plugin Directory = /etc/bacula/plugins 33 | } 34 | 35 | # Send all messages except skipped files back to Director 36 | Messages { 37 | Name = Standard 38 | director = bacula-dir = all, !skipped, !restored 39 | } 40 | -------------------------------------------------------------------------------- /conf/bacula-sd.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # bacula-sd.conf 3 | 4 | ######################################################################################## 5 | # Configuração Padrão do Storage 6 | Storage{ 7 | Name = bacula-sd 8 | SDPort = 9103 9 | WorkingDirectory = "/etc/bacula/working" 10 | Pid Directory = "/etc/bacula/working" 11 | Maximum Concurrent Jobs = 50 12 | Heartbeat Interval = 300 seconds 13 | } 14 | 15 | 16 | ######################################################################################## 17 | # Diretor autorizado com acesso total 18 | Director { 19 | Name = bacula-dir 20 | Password = "pZNOKm69Ps58ihJ4NcIwODOTsjrxpNs4KM2WaJoayeAQ" 21 | } 22 | 23 | 24 | ######################################################################################## 25 | # Local onde será salvo o backup 26 | Device { 27 | Name = DiscoLocal1 28 | Media Type = File 29 | Device Type = File 30 | Archive Device = "/mnt/disco01" 31 | LabelMedia = yes 32 | Random Access = Yes 33 | RemovableMedia = no 34 | AlwaysOpen = yes 35 | Maximum Concurrent Jobs = 50 36 | } 37 | 38 | 39 | ######################################################################################## 40 | # Local onde será salvo o backup 41 | Device { 42 | Name = DiscoLocal2 43 | Media Type = File 44 | Device Type = File 45 | Archive Device = "/mnt/disco02" 46 | LabelMedia = yes 47 | RemovableMedia = no 48 | Random Access = Yes 49 | AlwaysOpen = yes 50 | Maximum Concurrent Jobs = 50 51 | } 52 | 53 | 54 | ######################################################################################## 55 | # Configuração das Mensagens do Storage 56 | Messages { 57 | Name = Standard 58 | director = bacula-dir = all 59 | } 60 | -------------------------------------------------------------------------------- /conf/bconsole.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # bconsole.conf 3 | 4 | Director { 5 | Name = bacula-dir 6 | DIRport = 9101 7 | address = 192.168.1.3 8 | Password = "mKC0Bxz1hhrWj51J76qCnGYWXcKBdQPchlltirFaR/3s" 9 | } 10 | 11 | -------------------------------------------------------------------------------- /conf/clients-and-jobs.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # clients-and-jobs.conf 3 | 4 | ######################################################################################## 5 | # Configuração do Job Default 6 | JobDefs { 7 | Name = "Backup_Padrao" 8 | Type = Backup 9 | Level = Incremental 10 | Client = srv_bacula-fd 11 | FileSet = "FileSet_SRV_Bacula" 12 | Schedule = "Agenda_GFS_Noite" 13 | Messages = Standard 14 | Pool = "Pool-Default" 15 | SpoolAttributes = yes 16 | Priority = 10 17 | Enabled = yes 18 | Write Bootstrap = "/etc/bacula/bootstrap/%j_%l_%i_%c.bsr" 19 | RunScript { 20 | Command = "/etc/bacula/scripts/_send_telegram_mysql.sh %i" 21 | RunsWhen = After 22 | RunsOnFailure = yes 23 | RunsOnClient = no 24 | RunsOnSuccess = yes # default, you can drop this line 25 | } 26 | } 27 | 28 | ################################################################################################### 29 | # JobDefs, Jobs e Clientes (Cadastro dos Máquinas p/ Fazer Backup) 30 | @/etc/bacula/clients-and-jobs/srv_bacula-fd.conf # Máquina Linux 31 | @/etc/bacula/clients-and-jobs/srv_windows-fd.conf # Máquina Windows 32 | -------------------------------------------------------------------------------- /conf/clients-and-jobs/srv_bacula-fd.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | Client { 3 | Name = srv_bacula-fd 4 | Address = 192.168.1.3 5 | Catalog = MyCatalog 6 | Password = "wC9Tj32Wye8T4dLIZkEfHzWWzF6ipclKPSN9qFZpqsuV" 7 | File Retention = 365 days 8 | Job Retention = 365 days 9 | AutoPrune = yes 10 | Maximum Concurrent Jobs = 50 11 | Heartbeat Interval = 300 seconds 12 | } 13 | @/etc/bacula/clients-and-jobs/srv_bacula-jobs.conf 14 | @/etc/bacula/clients-and-jobs/srv_bacula-filesets.conf 15 | -------------------------------------------------------------------------------- /conf/clients-and-jobs/srv_bacula-filesets.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # Backup do Servidor Bacula 3 | FileSet { 4 | Name = "FileSet_SRV_Bacula" 5 | Include { 6 | Options{ 7 | wilddir = "/etc/bacula/working" 8 | wilddir = "/etc/bacula/bootstrap" 9 | exclude = yes 10 | } 11 | Options { 12 | signature = md5 13 | compression = gzip 14 | onefs = no 15 | ignorecase = yes 16 | } 17 | File = "/etc" 18 | File = "/root" 19 | File = "/var/spool/cron/crontabs/root" 20 | File = "/var/www/webacula" 21 | File = "/var/www/bweb" 22 | File = "/usr/local/bin" 23 | File = "/usr/local/backup_mysql" 24 | File = "/usr/src" 25 | } 26 | } 27 | 28 | ######################################################################################## 29 | # Backup do Catálogo 30 | FileSet { 31 | Name = "FileSet_Catalogo" 32 | Include { 33 | Options { 34 | signature = md5 35 | compression = gzip 36 | } 37 | File = "/etc/bacula/working/bacula.sql" 38 | File = "/etc/bacula/bootstrap" 39 | } 40 | } 41 | 42 | ######################################################################################## 43 | # Backup dos Arquivos Bootstrap 44 | FileSet { 45 | Name = "FileSet_Arquivos_Bootstrap" 46 | Include { 47 | Options { 48 | signature = md5 49 | compression = gzip 50 | } 51 | File = "/etc/bacula/bootstrap" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /conf/clients-and-jobs/srv_bacula-jobs.conf: -------------------------------------------------------------------------------- 1 | ################################################################################################### 2 | # Job de Backup do Próprio Diretor 3 | Job { 4 | Name = "Backup_Servidor_Bacula" 5 | JobDefs = "Backup_Padrao" 6 | Client = srv_bacula-fd 7 | FileSet = "FileSet_SRV_Bacula" 8 | Priority = 10 9 | } 10 | 11 | ######################################################################################## 12 | # Backup do Catálogo 13 | Job { 14 | Name = "Backup_Catalogo" 15 | JobDefs = "Backup_Padrao" 16 | Level = Full 17 | FileSet= "FileSet_Catalogo" 18 | Schedule = "Agenda_GFS_Noite" 19 | RunBeforeJob = "/etc/bacula/scripts/make_catalog_backup.pl MyCatalog" 20 | RunAfterJob = "/etc/bacula/scripts/_delete_bootstrap_files" 21 | RunScript { 22 | Console = "update stats" 23 | Console = "prune stats yes" 24 | RunsWhen = After 25 | Runs OnClient = no 26 | } 27 | Write Bootstrap = "/etc/bacula/bootstrap/%j_%l_%i_%c.bsr" 28 | Priority = 99 29 | } 30 | 31 | ######################################################################################## 32 | # Backup de Arquivos Bootstrap 33 | Job { 34 | Name = "Backup_Arquivos_Bootstrap" 35 | JobDefs = "Backup_Padrao" 36 | Level = Full 37 | FileSet= "FileSet_Arquivos_Bootstrap" 38 | Schedule = "Agenda_GFS_Noite" 39 | RunAfterJob = "/etc/bacula/scripts/_delete_bootstrap_files" 40 | Write Bootstrap = "/etc/bacula/bootstrap/%j_%l_%i_%c.bsr" 41 | Priority = 99 42 | } 43 | 44 | ######################################################################################## 45 | # Job Padrão de Restauração dos Dados 46 | Job { 47 | Name = "Restore_Files" 48 | Type = Restore 49 | Client = srv_bacula-fd 50 | FileSet= "FileSet_SRV_Bacula" 51 | Storage = "StorageLocal1" 52 | Pool = "Pool-Default" 53 | Messages = Standard 54 | Where = "/bacula_restore" 55 | Enabled = no 56 | Write Bootstrap = "/etc/bacula/bootstrap/%i_%c.bsr" 57 | } 58 | 59 | 60 | ################################################################################################### 61 | # Job de Migracao 62 | Job{ 63 | Name = "Migracao_Backup" 64 | Type = Migrate 65 | JobDefs = "Backup_Padrao" 66 | Client = srv_bacula-fd 67 | FileSet = "FileSet_SRV_Bacula" 68 | Pool = "Diaria" 69 | NextPool = "Pool-Temp" 70 | Selection Type = SqlQuery 71 | Selection Pattern = "select distinct JobId from JobMedia where MediaId in (select MediaId from Media where VolumeName like 'Volume-Temporario-%');" 72 | Purge Migration Job = yes 73 | Enabled = no 74 | } 75 | 76 | ################################################################################################### 77 | # Job de Verificação VolumeToCatalog 78 | Job{ 79 | Name = "Verify_VolumeToCatalog" 80 | Type = Verify 81 | Level = VolumeToCatalog 82 | JobDefs = "Backup_Padrao" 83 | Enabled = no 84 | } 85 | 86 | 87 | ################################################################################################### 88 | # Job de Verificação DiskToCatalog 89 | Job{ 90 | Name = "Verify_DiskToCatalog" 91 | Type = Verify 92 | Level = DiskToCatalog 93 | JobDefs = "Backup_Padrao" 94 | Enabled = no 95 | } 96 | 97 | 98 | ################################################################################################### 99 | # Job de Verificação Data 100 | Job{ 101 | Name = "Verify_Data" 102 | Type = Verify 103 | Level = Data 104 | JobDefs = "Backup_Padrao" 105 | Enabled = no 106 | } 107 | 108 | 109 | ################################################################################################### 110 | # Job de Verificação InitCatalog 111 | Job{ 112 | Name = "Verify_InitCatalog" 113 | Type = Verify 114 | Level = InitCatalog 115 | JobDefs = "Backup_Padrao" 116 | Enabled = no 117 | } 118 | 119 | 120 | ################################################################################################### 121 | # Job de Verificação Catalog 122 | Job{ 123 | Name = "Verify_Catalog" 124 | Type = Verify 125 | Level = Catalog 126 | JobDefs = "Backup_Padrao" 127 | Enabled = no 128 | } 129 | 130 | ################################################################################################### 131 | # Job Admin para purgar e truncat volumes expirados 132 | Job { 133 | Name = "Bacula_Admin_Job" 134 | Type = "Admin" 135 | Client = "bacula-fd" 136 | Priority = 12 137 | JobDefs = "Backup_Padrao" 138 | Schedule = "Agenda_Admin_Job" 139 | Runscript { 140 | Console = "prune volume expired yes" 141 | FailJobOnError = no 142 | RunsOnClient = no 143 | RunsWhen = Before 144 | } 145 | Runscript { 146 | Console = "purge volume action=truncate pool=Diaria storage=StorageLocal1" # Apenas 1 pool 147 | #Console = "purge volume action=truncate allpools storage=StorageLocal1" # Todas Pools 148 | FailJobOnError = no 149 | RunsOnClient = no 150 | RunsWhen = Before 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /conf/clients-and-jobs/srv_windows-fd.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | Client { 3 | Name = srv_windows-fd 4 | Address = 192.168.1.51 5 | FDPort = 9102 6 | Catalog = MyCatalog 7 | Password="XTO5huUERG_BfSXH2FXVi7YrqZnBoxdJ02IG/tg20Gs3" 8 | File Retention = 365 days 9 | Job Retention = 365 days 10 | Maximum Concurrent Jobs = 10 11 | Heartbeat Interval = 300 seconds 12 | } 13 | @|"sh -c 'cat /etc/bacula/clients-and-jobs/srv_windows-jobs.conf'" 14 | @|"sh -c 'cat /etc/bacula/clients-and-jobs/srv_windows-filesets.conf'" 15 | -------------------------------------------------------------------------------- /conf/clients-and-jobs/srv_windows-filesets.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # FileSet Backup Servidor Windows 3 | FileSet { 4 | Name = "FileSet_SRV_Windows" 5 | Include { 6 | Options { 7 | signature = md5 8 | compression = gzip 9 | onefs = no 10 | ignorecase = yes 11 | accurate = pins5 12 | verify = pins5 13 | } 14 | File = "c:/dados" 15 | File = "c:/Program Files/Bacula" 16 | } 17 | } 18 | 19 | 20 | FileSet { 21 | Name = "FileSet_Arquivos_PDF" 22 | Include { 23 | Options { 24 | signature = md5 25 | compression = gzip 26 | onefs = no 27 | ignorecase = yes 28 | accurate = pins5 29 | verify = pins5 30 | } 31 | File = "\\| powershell.exe C:/'Program Files'/Bacula/scripts/_list_files_by_extension.ps1 '.pdf' 'C:/Dados' " 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /conf/clients-and-jobs/srv_windows-jobs.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | Job { 3 | Name = "Backup_Servidor_Windows" 4 | JobDefs = "Backup_Padrao" 5 | Client = srv_windows-fd 6 | FileSet = "FileSet_SRV_Windows" 7 | } 8 | -------------------------------------------------------------------------------- /conf/counters.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # counters.conf 3 | 4 | ######################################################################################## 5 | # Contador NumVolsPoolDefault 6 | Counter { 7 | Name = "NumVolsPoolDefault" 8 | Minimum = 1 9 | Maximum = 1000 10 | Catalog = MyCatalog 11 | } 12 | 13 | 14 | ######################################################################################## 15 | # Contador NumVolsPoolTemp 16 | Counter { 17 | Name = "NumVolsPoolTemp" 18 | Minimum = 1 19 | Maximum = 1000 20 | Catalog = MyCatalog 21 | } 22 | 23 | ######################################################################################## 24 | # Contador NumVolsDiaria 25 | Counter { 26 | Name = "NumVolsDiaria" 27 | Minimum = 1 28 | Maximum = 1000 29 | Catalog = MyCatalog 30 | } 31 | 32 | 33 | ######################################################################################## 34 | # Contador NumVolsSemanal 35 | Counter { 36 | Name = "NumVolsSemanal" 37 | Minimum = 1 38 | Maximum = 1000 39 | Catalog = MyCatalog 40 | } 41 | 42 | 43 | ######################################################################################## 44 | # Contador NumVolsMensal 45 | Counter { 46 | Name = "NumVolsMensal" 47 | Minimum = 1 48 | Maximum = 1000 49 | Catalog = MyCatalog 50 | } 51 | -------------------------------------------------------------------------------- /conf/messages.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # messages.conf 3 | 4 | ######################################################################################## 5 | # Configuração das mensagens de Jobs 6 | Messages { 7 | Name = Standard 8 | 9 | MailCommand = "/usr/sbin/bsmtp -h localhost -f \"Bacula \" -s \"Bacula: %t %e of %c %l\" %r" 10 | Mail = email@domain.com.br = all, !skipped # Envia email de todos os jobs 11 | 12 | #MailOnSuccess = email1@domain.com = all, !skipped # Envia email em caso de sucesso 13 | MailOnError = email2@domain.com = all, !skipped # Envia email em caso de erro 14 | 15 | OperatorCommand = "/usr/sbin/bsmtp -h localhost -f \"Bacula \" -s \"Bacula: Intervention needed for %j\" %r" 16 | Operator = email@domain.com = mount 17 | 18 | console = all, !skipped, !saved 19 | append = "/var/log/bacula/bacula.log" = all, !skipped 20 | catalog = all, !skipped, !saved 21 | } 22 | 23 | 24 | ######################################################################################## 25 | # Configuração das mensagens do daemon 26 | Messages { 27 | Name = Daemon 28 | MailCommand = "/usr/sbin/bsmtp -h localhost -f \"Bacula \" -s \"Bacula daemon message\" %r" 29 | Mail = email@domain.com = all, !skipped 30 | console = all, !skipped, !saved 31 | append = "/var/log/bacula/bacula.log" = all, !skipped 32 | } 33 | -------------------------------------------------------------------------------- /conf/openssl.cnf.template: -------------------------------------------------------------------------------- 1 | HOME = XXX_SSL_DIR_XXX 2 | RANDFILE = $ENV::HOME/.rnd 3 | 4 | #################################################################### 5 | [ ca ] 6 | default_ca = CA_default # The default ca section 7 | 8 | #################################################################### 9 | [ CA_default ] 10 | 11 | dir = XXX_SSL_DIR_XXX # Where everything is kept 12 | certs = $dir/certs # Where the issued certs are kept 13 | crl_dir = $dir/crl # Where the issued crl are kept 14 | database = $dir/index.txt # database index file. 15 | unique_subject = no # Set to 'no' to allow creation of 16 | # several ctificates with same subject. 17 | new_certs_dir = $dir/certs # default place for new certs. 18 | 19 | certificate = $dir/certs/XXX_ROOT_CA_XXX # The CA certificate 20 | serial = $dir/serial # The current serial number 21 | crlnumber = $dir/crlnumber # the current crl number 22 | # must be commented out to leave a V1 CRL 23 | 24 | x509_extensions = usr_cert # The extentions to add to the cert 25 | 26 | name_opt = ca_default # Subject Name options 27 | cert_opt = ca_default # Certificate field options 28 | 29 | default_days = 36500 # how long to certify for (default: 100 years) 30 | default_crl_days= 30 # how long before next CRL 31 | default_md = sha256 # use public key default MD 32 | preserve = no # keep passed DN ordering 33 | 34 | policy = policy_match 35 | 36 | # For the CA policy 37 | [ policy_match ] 38 | countryName = match 39 | stateOrProvinceName = match 40 | organizationName = match 41 | organizationalUnitName = optional 42 | commonName = supplied 43 | emailAddress = optional 44 | 45 | # For the 'anything' policy 46 | [ policy_anything ] 47 | countryName = optional 48 | stateOrProvinceName = optional 49 | localityName = optional 50 | organizationName = optional 51 | organizationalUnitName = optional 52 | commonName = supplied 53 | emailAddress = optional 54 | 55 | #################################################################### 56 | [ req ] 57 | default_bits = 4096 58 | default_keyfile = XXX_ROOT_CA_XXX 59 | distinguished_name = req_distinguished_name 60 | attributes = req_attributes 61 | x509_extensions = v3_ca # The extentions to add to the self signed cert 62 | string_mask = utf8only 63 | 64 | [ req_distinguished_name ] 65 | countryName = Country Name (2 letter code) 66 | countryName_default = XXX_COUNTRY_NAME_XXX 67 | countryName_min = 2 68 | countryName_max = 2 69 | 70 | stateOrProvinceName = State or Province Name (full name) 71 | stateOrProvinceName_default = XXX_STATE_OR_PROVINCE_NAME_XXX 72 | 73 | localityName = Locality Name (eg, city) 74 | localityName_default = XXX_LOCALITY_NAME_XXX 75 | 76 | 0.organizationName = Organization Name (eg, company) 77 | 0.organizationName_default = XXX_ORGANIZATION_NAME_XXX 78 | 79 | commonName = Common Name (e.g. server FQDN or YOUR name) 80 | commonName_max = 64 81 | commonName_default = XXX_COMMON_NAME_XXX 82 | 83 | emailAddress = Email Address 84 | emailAddress_max = 64 85 | emailAddress_default = XXX_EMAIL_ADDRESS_XXX 86 | 87 | [ req_attributes ] 88 | challengePassword = A challenge password 89 | challengePassword_min = 4 90 | challengePassword_max = 20 91 | 92 | unstructuredName = An optional company name 93 | 94 | [ v3_ca ] 95 | 96 | subjectKeyIdentifier=hash 97 | authorityKeyIdentifier=keyid:always,issuer 98 | 99 | # With OpenSSL 1.1, enforce basicConstraints = CA:true in the certificate creation to avoid this issue 100 | basicConstraints = CA:true 101 | 102 | [ usr_cert ] 103 | 104 | basicConstraints=CA:true 105 | nsComment = "OpenSSL Generated Certificate" 106 | 107 | # PKIX recommendations harmless if included in all certificates. 108 | subjectKeyIdentifier=hash 109 | authorityKeyIdentifier=keyid,issuer 110 | -------------------------------------------------------------------------------- /conf/pools.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # pools.conf 3 | 4 | ######################################################################################## 5 | # Configuração da Pool Padrão 6 | Pool{ 7 | Name = "Pool-Default" # Nome da Pool 8 | Pool Type = Backup # Tipo da Pool 9 | Recycle = yes # Pode reciclar a Pool 10 | Recycle Oldest Volume = yes # Reciclar o volume mais antigo 11 | # Purge Oldest Volume = yes # Purgar volume mais antigo (CUIDADO). Esta opção não respeita a retenção 12 | # Action On Purge = Truncate # Opção para poder truncar o volume e diminuir o espaço em disco 13 | AutoPrune = yes # Limpar dados do catálogo automaticamente 14 | Volume Retention = 30 days # Tempo de retenção do volume 15 | Volume Use Duration = 23 hours # Tempo que o volume permanece aberto para escrita 16 | # Formato do nome do Volume 17 | # O label format vai escrever o nome do volume assim: 18 | # Volume-Default-0001 e vai seguir a sequencia do counter 'NumVolsPoolDefault' 19 | # A numeração vai utilizar 4 caracteres e será alinhada à direita com zeros à esquerda 20 | LabelFormat = "Volume-Default-${NumVolsPoolDefault+:p/4/0/r}" 21 | Maximum Volume Bytes = 4GB # Tamanho máximo de cada volume 22 | Maximum Volumes = 10 # Número máximo de volumes 23 | NextPool = "Pool-Temp" # Pool utilizada para fazer migração ou job de cópia 24 | Storage = StorageLocal1 # Storage onde se encontra a Pool 25 | } 26 | 27 | ######################################################################################## 28 | # Configuração da Pool Diaria 29 | Pool{ 30 | Name = "Pool-Temp" 31 | Pool Type = Backup 32 | Recycle = yes 33 | Recycle Oldest Volume = yes 34 | # Purge Oldest Volume = yes 35 | Action On Purge = Truncate 36 | Autoprune = yes 37 | LabelFormat = "Volume-Temp-${NumVolsPoolTemp+:p/4/0/r}" 38 | Maximum Volume Bytes = 4GB 39 | Maximum Volumes = 15 40 | NextPool = "Pool-Default" 41 | Storage = StorageLocal2 42 | } 43 | 44 | ######################################################################################## 45 | # Configuração da Pool Diaria 46 | Pool{ 47 | Name = "Diaria" 48 | Pool Type = Backup 49 | Recycle = yes 50 | Recycle Oldest Volume = yes 51 | # Purge Oldest Volume = yes 52 | Action On Purge = Truncate 53 | Autoprune = yes 54 | LabelFormat = "Volume-Diario-${NumVolsDiaria+:p/4/0/r}" 55 | Maximum Volume Bytes = 4Gb 56 | Maximum Volumes = 15 57 | NextPool = "Pool-Temp" 58 | Storage = StorageLocal1 59 | } 60 | 61 | 62 | ######################################################################################## 63 | # Configuração da Pool Semanal (100 GB) 64 | Pool{ 65 | Name = "Semanal" 66 | Pool Type = Backup 67 | Recycle = yes 68 | Recycle Oldest Volume = yes 69 | # Purge Oldest Volume = yes 70 | Action On Purge = Truncate 71 | Autoprune = yes 72 | LabelFormat = "Volume-Semanal-${NumVolsSemanal+:p/4/0/r}" 73 | Maximum Volume Bytes = 4Gb 74 | Maximum Volumes = 25 75 | NextPool = "Pool-Temp" 76 | Storage = StorageLocal1 77 | } 78 | 79 | 80 | ######################################################################################## 81 | # Configuração da Pool Mensal 280( GB) 82 | Pool{ 83 | Name = "Mensal" 84 | Pool Type = Backup 85 | Recycle = yes 86 | Recycle Oldest Volume = yes 87 | # Purge Oldest Volume = yes 88 | Action On Purge = Truncate 89 | Autoprune = yes 90 | LabelFormat = "Volume-Mensal-${NumVolsMensal+:p/4/0/r}" 91 | Maximum Volume Bytes = 4Gb 92 | Maximum Volumes = 70 93 | NextPool = "Pool-Temp" 94 | Storage = StorageLocal1 95 | } 96 | 97 | 98 | ######################################################################################## 99 | # Configuração da Pool Scratch 100 | Pool { 101 | Name = Scratch 102 | Pool Type = Backup 103 | } 104 | -------------------------------------------------------------------------------- /conf/readme-english.md: -------------------------------------------------------------------------------- 1 | ## How to configure bacula-dir.conf in separated files 2 | -------------------------------------------------------------------------------- /conf/readme.md: -------------------------------------------------------------------------------- 1 | ## Exemplo de configuração do bacula em arquivos separados 2 | -------------------------------------------------------------------------------- /conf/schedules.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # schedule.conf 3 | 4 | ######################################################################################## 5 | # Agenda GFS Noite 6 | Schedule { 7 | Name = "Agenda_GFS_Noite" 8 | Run = Level=Differential Pool=Diaria on Monday-Thursday at 23:30 9 | Run = Level=Full Pool=Semanal on 2nd-6th Friday at 23:30 10 | Run = Level=Full Pool=Mensal on 1st Friday at 23:30 11 | } 12 | 13 | Schedule { 14 | Name = "Agenda_Quinzenal" 15 | Run = Level=Full Pool=Pool-Default on 10,25 at 21:30 16 | } 17 | 18 | Schedule { 19 | Name = "Agenda_Admin_Job" 20 | Run = Level=Full on Monday-Friday at 23:59 21 | } 22 | -------------------------------------------------------------------------------- /conf/scripts/_autochanger.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # A menu driven shell script sample template 3 | ## ---------------------------------- 4 | # Step #1: Define variables 5 | # ---------------------------------- 6 | RED='\033[0;41;30m' 7 | STD='\033[0;0;39m' 8 | BLUE='\033[1;40;34m' 9 | GREEN='\033[1;40;32m' 10 | YELLOW='\033[0;40;33m' 11 | bconsole=$(which bconsole) 12 | POOL="" 13 | DEVICE="" 14 | DEVICES="/etc/autochanger.conf" 15 | 16 | # ---------------------------------- 17 | # Step #2: User defined function 18 | # ---------------------------------- 19 | pause(){ 20 | read -p "Press [Enter] key to continue..." fackEnterKey 21 | } 22 | ############################################################################################ 23 | # List pools 24 | list_pool(){ 25 | clear 26 | echo "+----------------------------+" 27 | echo "| Pools |" 28 | echo "+----------------------------+" 29 | 30 | pools=(`echo "llist pool" | $bconsole | grep "Name:" | cut -d":" -f2 | sed 's/\s//g' | sort`) 31 | count=0 32 | for i in ${pools[@]}; do count=`expr $count + 1`; printf "%3s) %s\n" $count $i; done 33 | echo "" 34 | pause 35 | } 36 | 37 | 38 | ############################################################################################ 39 | # List volume by pool 40 | list_volumes(){ 41 | clear 42 | select_pool 43 | count=0 44 | volumes=(`echo "llist volume pool=$POOL" | $bconsole | grep "VolumeName:" | cut -d":" -f2 | sed 's/\s//g' | sort`) 45 | echo "+----------------------------+" 46 | echo "| Volumes |" 47 | echo "+----------------------------+" 48 | for i in ${volumes[@]}; do count=`expr $count + 1`; printf "%3s) %s\n" $count $i; done 49 | if [ ${#volumes[@]} -eq 0 ]; then 50 | echo "The Pool \"$POOL\" does not contain any volumes!" 51 | fi 52 | echo "" 53 | pause 54 | } 55 | 56 | ############################################################################################ 57 | # Select pools 58 | select_pool(){ 59 | #clear 60 | echo "+----------------------------+" 61 | echo "| Pools |" 62 | echo "+----------------------------+" 63 | 64 | pools=(`echo "llist pool" | $bconsole | grep "Name:" | cut -d":" -f2 | sed 's/\s//g' | sort`) 65 | count=0 66 | for i in ${pools[@]}; do count=`expr $count + 1`; printf "%3s) %s\n" $count $i; done 67 | echo -ne "Choose a pool (1-$count): " 68 | read pool_option 69 | 70 | 71 | while [ -n $pool_option ]; do 72 | if [ $pool_option -ge 1 ] && [ $pool_option -le ${#pools[@]} ]; then 73 | pool_name=${pools[$pool_option-1]}; 74 | break 75 | else 76 | echo -ne "Choose a pool (1-$count): "; 77 | read pool_option 78 | fi 79 | done 80 | 81 | POOL=$pool_name 82 | echo -ne "\nPool selected: $pool_name\n\n" 83 | } 84 | 85 | ############################################################################################ 86 | # Select device 87 | select_device(){ 88 | #clear 89 | echo "+----------------------------+" 90 | echo "| Devices |" 91 | echo "+----------------------------+" 92 | 93 | devices=(`cat $DEVICES | grep -i "d:" | sed 's/d://gI'`) 94 | count=0 95 | for i in ${devices[@]}; do count=`expr $count + 1`; printf "%3s) %s\n" $count $i; done 96 | echo -ne "Choose a device (1-$count): " 97 | read device_option 98 | 99 | while [ -n $device_option ]; do 100 | if [ $device_option -ge 1 ] && [ $device_option -le ${#devices[@]} ]; then 101 | device_name=${devices[$device_option-1]}; 102 | break 103 | else 104 | echo -ne "Choose a device (1-$count): "; 105 | read device_option 106 | fi 107 | done 108 | 109 | DEVICE=$device_name 110 | echo -ne "\nDevice selected: $device_name\n\n" 111 | } 112 | 113 | 114 | 115 | ############################################################################################ 116 | # Create volumes 117 | create_single_volume(){ 118 | clear 119 | select_pool 120 | select_device 121 | count=0 122 | volumes=(`echo "llist volume pool=$POOL" | $bconsole | grep "VolumeName:" | cut -d":" -f2 | sed 's/\s//g' | sort`) 123 | echo "+----------------------------+" 124 | echo "| Volumes |" 125 | echo "+----------------------------+" 126 | for i in ${volumes[@]}; do count=`expr $count + 1`; printf "%3s) %s\n" $count $i; done 127 | echo -ne "\nType the volume name: "; 128 | read volume_name 129 | if [ "x$volume_name" != "x" ]; then 130 | echo "label media pool=$POOL volume=$volume_name slot=0" | $bconsole 131 | mv /backup/$volume_name $DEVICE 132 | ln -s $DEVICE/$volume_name /backup/$volume_name 133 | chmod 775 $DEVICE/$volume_name 134 | fi 135 | pause 136 | } 137 | 138 | 139 | ############################################################################################ 140 | # Create multiples volumes 141 | create_multiples_volumes(){ 142 | clear 143 | select_pool 144 | select_device 145 | count=0 146 | volumes=(`echo "llist volume pool=$POOL" | $bconsole | grep "VolumeName:" | cut -d":" -f2 | sed 's/\s//g' | sort`) 147 | echo "+----------------------------+" 148 | echo "| Volumes |" 149 | echo "+----------------------------+" 150 | for i in ${volumes[@]}; do count=`expr $count + 1`; printf "%3s) %s\n" $count $i; done 151 | echo -ne "\nType the prefix of volume name: "; 152 | read prefix_name 153 | echo -ne "\nType the start number of volume: "; 154 | read start_volume 155 | echo -ne "\nType the amount of volumes to create: "; 156 | read count_volume 157 | a=$start_volume 158 | b=`expr $a + $count_volume - 1` 159 | echo "" 160 | if [ "x$prefix_name" != "x" ]; then 161 | for i in $(eval echo {$a..$b}) ; do 162 | volume_name=`printf "$prefix_name%04d" $i` 163 | echo "label media pool=$POOL volume=$volume_name slot=0" | $bconsole 164 | mv /backup/$volume_name $DEVICE 165 | ln -s $DEVICE/$volume_name /backup/$volume_name 166 | chmod 775 $DEVICE/$volume_name 167 | done 168 | 169 | fi 170 | pause 171 | } 172 | 173 | ############################################################################################ 174 | # Recreate symlinks 175 | create_symlink(){ 176 | clear 177 | echo "+----------------------------+" 178 | echo "| Symbolic Links |" 179 | echo "+----------------------------+" 180 | vdevice=(`cat $DEVICES | grep -i "v:" | sed 's/v://gI'`) 181 | devices=(`cat $DEVICES | grep -i "d:" | sed 's/d://gI'`) 182 | count=0 183 | find $vdevice -type l -delete 184 | for i in ${devices[@]}; do 185 | count=`expr $count + 1`; 186 | for v in `find $i -type f | sort`; do 187 | volume_name=`basename $v`; 188 | echo "$v => $vdevice/$volume_name" 189 | ln -s $v $vdevice/$volume_name 190 | done 191 | echo "" 192 | done 193 | pause 194 | } 195 | 196 | ############################################################################################ 197 | # Help 198 | show_help(){ 199 | clear 200 | echo "+----------------------------+" 201 | echo "| Help |" 202 | echo "+----------------------------+" 203 | echo "1) This script is used to manage a Bacula Autochanger with multiples disks " 204 | echo " with symlinks for a single folder" 205 | echo "" 206 | echo "" 207 | echo "2) Create the file /etc/autochanger.conf with devices" 208 | echo " # Example " 209 | echo " # D = Phisical Device (real volume storage)" 210 | echo " # V = Virtual Device (fake storage, folder with the symlinks for the real storage)" 211 | echo " V:/backup" 212 | echo " D:/mnt/disco01" 213 | echo " D:/mnt/disco02" 214 | echo " D:/mnt/disco03" 215 | echo "" 216 | echo "" 217 | echo "3) The volume labels must have a prefix followed by 4 digits number " 218 | echo " Example:" 219 | echo " Volume Name: Volume-Daily-0001, VolumeWeekly-0015, Volume_Monthly_0034, Volume0007" 220 | echo " Prefix Volume-Daily-, VolumeWeekly-, Volume_Monthly_, Volume" 221 | echo " This is useful to create multiples volumes at the same time" 222 | echo "" 223 | echo "" 224 | pause 225 | 226 | } 227 | ############################################################################################ 228 | # function to display menus 229 | show_menus() { 230 | clear 231 | echo "+----------------------------+" 232 | echo "| Bacula Autochanger Manager |" 233 | echo "| Version 0.1 |" 234 | echo "| Author Wanderlei Hüttel |" 235 | echo "+----------------------------+" 236 | echo "----------------------------" 237 | echo " Menu options" 238 | echo "----------------------------" 239 | echo "1) Create a single volume" 240 | echo "2) Create multiples volumes" 241 | echo "3) Recreate symbolic links" 242 | echo "4) List pools" 243 | echo "5) List volumes by pool" 244 | echo "h) Help" 245 | echo "q) Quit" 246 | 247 | } 248 | 249 | ############################################################################################ 250 | # Menu read options 251 | read_options(){ 252 | local choice 253 | read -p "Enter your choice (1-4): " choice 254 | echo "" 255 | case $choice in 256 | 1) create_single_volume ;; 257 | 2) create_multiples_volumes ;; 258 | 3) create_symlink ;; 259 | 4) list_pool ;; 260 | 5) list_volumes ;; 261 | "h") show_help ;; 262 | "q") exit 0;; 263 | *) echo -ne "${RED}Error...${STD}" && sleep 1 264 | esac 265 | } 266 | 267 | ############################################################################################ 268 | # ---------------------------------------------- 269 | # Step #3: Trap CTRL+C, CTRL+Z and quit singles 270 | # ---------------------------------------------- 271 | trap '' SIGINT SIGQUIT SIGTSTP 272 | 273 | ############################################################################################ 274 | # ----------------------------------- 275 | # Step #4: Main logic - infinite loop 276 | # ------------------------------------ 277 | while true 278 | do 279 | show_menus 280 | read_options 281 | done 282 | -------------------------------------------------------------------------------- /conf/scripts/_bacula_community_package.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script to install Bacula with packages 3 | # 4 | # Author: Wanderlei Huttel 5 | # Email: wanderlei@bacula.com.br 6 | version="1.0.7 - 19 May 2020" 7 | 8 | 9 | #=============================================================================== 10 | # Read bacula key 11 | function read_bacula_key() 12 | { 13 | clear 14 | echo " --------------------------------------------------" 15 | echo " Inform your Bacula Key" 16 | echo " This key is obtained with a registration in Bacula.org." 17 | echo " https://www.bacula.org/bacula-binary-package-download/" 18 | read -p " Please, fill with your Bacula Key: " bacula_key 19 | } 20 | 21 | 22 | #=============================================================================== 23 | # Download Bacula Key 24 | function download_bacula_key() 25 | { 26 | wget -c https://www.bacula.org/downloads/Bacula-4096-Distribution-Verification-key.asc -O /tmp/Bacula-4096-Distribution-Verification-key.asc 27 | if [ "$OS" == "debian" -o "$OS" == "ubuntu" ]; then 28 | apt-key add /tmp/Bacula-4096-Distribution-Verification-key.asc 29 | elif [ "$OS" == "centos" ]; then 30 | rpm --import /tmp/Bacula-4096-Distribution-Verification-key.asc 31 | else 32 | echo "Is not possible to install the Bacula Key" 33 | fi 34 | rm -f /tmp/Bacula-4096-Distribution-Verification-key.asc 35 | } 36 | 37 | 38 | 39 | #=============================================================================== 40 | # Download Bacula Key 41 | function create_bacula_repository() 42 | { 43 | while : 44 | do 45 | clear 46 | echo " --------------------------------------------------" 47 | echo " Inform the Bacula version" 48 | url="https://www.bacula.org/packages/${bacula_key}/debs/" 49 | IFS=$'\n' 50 | versions=$(curl --insecure --silent --fail -r 0-0 "${url}" | grep -o '.*/' | sed 's/\(\|\/<\/a>\)//g') 51 | for i in ${versions}; do 52 | echo " - $i"; 53 | done 54 | read -p " Type your the Bacula Version: " bacula_version 55 | 56 | if [ "$OS" == "debian" -o "$OS" == "ubuntu" ]; then 57 | url="http://www.bacula.org/packages/${bacula_key}/debs/${bacula_version}/${codename}/amd64" 58 | echo "# Bacula Community 59 | deb ${url} ${codename} main" > /etc/apt/sources.list.d/bacula-community.list 60 | 61 | elif [ "$OS" == "centos" ]; then 62 | url="https://www.bacula.org/packages/${bacula_key}/rpms/${bacula_version}/el${codename}/x86_64/" 63 | echo "[Bacula-Community] 64 | name=CentOS - Bacula - Community 65 | baseurl=${url} 66 | enabled=1 67 | protect=0 68 | gpgcheck=0" > /etc/yum.repos.d/bacula-community.repo 69 | else 70 | echo "Is not possible to install the Bacula Key" 71 | fi 72 | 73 | if wget --spider ${url} 2>/dev/null; then 74 | break 75 | else 76 | echo " Unfortunately this version (${bacula_version}) still not available for this OS." 77 | echo " Please, choose another one!" 78 | read -p " Press [enter] key to continue..." readenterkey 79 | fi 80 | 81 | done 82 | } 83 | 84 | 85 | 86 | #=============================================================================== 87 | # Install MySQL 88 | function install_with_mysql() 89 | { 90 | wget -c https://repo.mysql.com/RPM-GPG-KEY-mysql -O /tmp/RPM-GPG-KEY-mysql --no-check-certificate 91 | if [ "$OS" == "debian" -o "$OS" == "ubuntu" ]; then 92 | apt-key add /tmp/RPM-GPG-KEY-mysql 93 | echo "deb http://repo.mysql.com/apt/debian/ ${codename} mysql-apt-config 94 | deb http://repo.mysql.com/apt/debian/ ${codename} mysql-5.7 95 | deb http://repo.mysql.com/apt/debian/ ${codename} mysql-tools 96 | deb http://repo.mysql.com/apt/debian/ ${codename} mysql-tools-preview 97 | deb-src http://repo.mysql.com/apt/debian/ ${codename} mysql-5.7" > /etc/apt/sources.list.d/mysql.list 98 | apt-get update 99 | apt-get install -y mysql-community-server 100 | apt-get install -y bacula-mysql 101 | systemctl enable mysql 102 | systemctl start mysql 103 | 104 | elif [ "$OS" == "centos" ]; then 105 | rpm --import /tmp/RPM-GPG-KEY-mysql 106 | wget -c http://dev.mysql.com/get/mysql57-community-release-el7-9.noarch.rpm -O /tmp/mysql57-community-release-el7-9.noarch.rpm 107 | rpm -ivh /tmp/mysql57-community-release-el7-9.noarch.rpm 108 | yum install -y mysql-community-server 109 | mysqld --initialize-insecure --user=mysql 110 | systemctl enable mysqld 111 | systemctl start mysqld 112 | yum install -y bacula-mysql 113 | fi 114 | 115 | /opt/bacula/scripts/create_mysql_database 116 | /opt/bacula/scripts/make_mysql_tables 117 | /opt/bacula/scripts/grant_mysql_privileges 118 | 119 | systemctl enable bacula-fd.service 120 | systemctl enable bacula-sd.service 121 | systemctl enable bacula-dir.service 122 | 123 | systemctl start bacula-fd.service 124 | systemctl start bacula-sd.service 125 | systemctl start bacula-dir.service 126 | 127 | for i in $(ls /opt/bacula/bin); do 128 | ln -s /opt/bacula/bin/$i /usr/sbin/$i; 129 | done 130 | sed '/[Aa]ddress/s/=\s.*/= localhost/g' -i /opt/bacula/etc/bconsole.conf 131 | echo 132 | echo "Bacula with MySQL installed with success!" 133 | echo 134 | } 135 | 136 | # Install PostgreSQL 137 | function install_with_postgresql() 138 | { 139 | if [ "$OS" == "debian" -o "$OS" == "ubuntu" ]; then 140 | apt-get update 141 | apt-get install -y postgresql postgresql-client 142 | apt-get install -y bacula-postgresql 143 | 144 | elif [ "$OS" == "centos" ]; then 145 | yum install -y postgresql-server 146 | yum install -y bacula-postgresql --exclude=bacula-mysql 147 | postgresql-setup initdb 148 | fi 149 | 150 | systemctl enable postgresql 151 | systemctl start postgresql 152 | su - postgres -c "/opt/bacula/scripts/create_postgresql_database" 153 | su - postgres -c "/opt/bacula/scripts/make_postgresql_tables" 154 | su - postgres -c "/opt/bacula/scripts/grant_postgresql_privileges" 155 | 156 | systemctl enable bacula-fd.service 157 | systemctl enable bacula-sd.service 158 | systemctl enable bacula-dir.service 159 | 160 | systemctl start bacula-fd.service 161 | systemctl start bacula-sd.service 162 | systemctl start bacula-dir.service 163 | 164 | for i in $(ls /opt/bacula/bin); do 165 | ln -s /opt/bacula/bin/$i /usr/sbin/$i; 166 | done 167 | sed '/[Aa]ddress/s/=\s.*/= localhost/g' -i /opt/bacula/etc/bconsole.conf 168 | echo 169 | echo "Bacula with PostgreSQL installed with success!" 170 | echo 171 | } 172 | 173 | #=============================================================================== 174 | # Menu 175 | function menu() 176 | { 177 | while : 178 | do 179 | clear 180 | echo " ==================================================" 181 | echo " Bacula Community Package Install" 182 | echo " Author: Wanderlei Huttel" 183 | echo " Email: wanderlei@bacula.com.br" 184 | echo " OS Supported: Debian | Ubuntu | CentOS" 185 | echo " Version: ${version}" 186 | echo " ==================================================" 187 | echo 188 | echo " What do you want to do?" 189 | echo " 1) Install Bacula with PostgreSQL" 190 | echo " 2) Install Bacula with MySQL" 191 | echo " 3) Exit" 192 | read -p " Select an option [1-3]: " option 193 | echo 194 | case $option in 195 | 1) # Install Bacula with PostgreSQL 196 | install_with_postgresql 197 | read -p "Press [enter] key to continue..." readenterkey 198 | ;; 199 | 2) # Install Bacula with MySQL 200 | install_with_mysql 201 | read -p "Press [enter] key to continue..." readenterkey 202 | ;; 203 | 3) echo 204 | exit 205 | ;; 206 | esac 207 | done 208 | } 209 | 210 | 211 | #=============================================================================== 212 | # Detect Debian users running the script with "sh" instead of bash 213 | OS="" 214 | codename="" 215 | bacula_key="" 216 | export DEBIAN_FRONTEND=noninteractive 217 | clear 218 | if readlink /proc/$$/exe | grep -q "dash"; then 219 | echo "This script needs to be run with bash, not sh" 220 | exit 221 | fi 222 | 223 | if [[ "$EUID" -ne 0 ]]; then 224 | echo "Sorry, you need to run this as root" 225 | exit 226 | fi 227 | 228 | if [[ -e /etc/debian_version ]]; then 229 | OS=$(cat /etc/os-release | egrep "^ID=" | sed 's/.*=//g') 230 | codename=$(cat /etc/os-release | grep "VERSION_CODENAME" | sed 's/.*=//g') 231 | elif [[ -e /etc/centos-release || -e /etc/redhat-release ]]; then 232 | setenforce 0 233 | sudo sed -i "s/enforcing/disabled/g" /etc/selinux/config 234 | sudo sed -i "s/enforcing/disabled/g" /etc/sysconfig/selinux 235 | firewall-cmd --permanent --zone=public --add-port=9101-9103/tcp 236 | systemctl restart firewalld 237 | OS=centos 238 | codename=$(cat /etc/os-release | grep "VERSION_ID" | sed 's/[^0-9]//g') 239 | else 240 | echo "Looks like you aren't running this installer on Debian, Ubuntu or CentOS" 241 | exit 242 | fi 243 | 244 | if [ "$OS" == "debian" -o "$OS" == "ubuntu" ]; then 245 | apt-get install -y zip wget apt-transport-https bzip2 curl 246 | elif [ "$OS" == "centos" ]; then 247 | yum install -y zip wget apt-transport-https bzip2 curl 248 | fi 249 | 250 | download_bacula_key 251 | read_bacula_key 252 | create_bacula_repository 253 | menu 254 | -------------------------------------------------------------------------------- /conf/scripts/_create_mysql_function: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Copyright (C) 2000-2015 Kern Sibbald 4 | # License: BSD 2-Clause; see file LICENSE-FOSS 5 | # 6 | # shell script to create Bacula database(s) 7 | # 8 | 9 | bindir=/usr/bin 10 | db_name=bacula 11 | db_user=${db_user:-bacula} 12 | 13 | if $bindir/mysql $* -f < /dev/null 12 | 13 | bconsole=$(which bconsole) 14 | today=$(date +%m-%d) 15 | 16 | # Ann array with holidays (%m-%d) 17 | holidays=("01-01, 03-25, 03-27, 04-21, 05-01, 05-26, 09-07, 10-12, 11-02, 11-15, 12-25") 18 | 19 | # Get schedules from Bacula 20 | schedules=$(echo ".schedule" | ${bconsole} | sed '1,4d;' | grep -v "You have messages") 21 | 22 | # Disable schedules 23 | for holiday in $(echo "${holidays}" | tr "," "\n"); do 24 | # Check if today is a holiday 25 | if [ "${holiday}" == "${today}" ]; then 26 | echo -e "Today is a holiday! All schedules were disabled!\n" 27 | # Disable as schedules and finish 28 | for schedule in $(echo ${schedules}); do 29 | echo "disable schedule=${schedule}" | ${bconsole} > /dev/null 30 | echo "The schedule \"${schedule}\" are disable in ${today}!" 31 | done 32 | exit 0 33 | fi 34 | done 35 | 36 | 37 | # Enable schedules 38 | echo -e "Is not holiday today! All schedules were enabled!\n" 39 | for schedule in $( echo ${schedules} ); do 40 | echo "enable schedule=${schedule}" | ${bconsole} > /dev/null 41 | echo "The schedule \"${schedule}\" are enable in ${today}!" 42 | done 43 | 44 | exit 0 45 | -------------------------------------------------------------------------------- /conf/scripts/_list_files_by_extension.ps1: -------------------------------------------------------------------------------- 1 | ############################################################### 2 | # Config Variables 3 | $data = Get-Date -f "yyyyMMddhhmmss" 4 | $file_extension = $args[0] 5 | $root_folder = $args[1] 6 | $file_list = "C:\Program Files\Bacula\scripts\$data.txt" 7 | 8 | ############################################################### 9 | # Get all files by extension 10 | $files = Get-ChildItem -Recurse -path $root_folder | Where-Object {$_.Extension -eq $file_extension} 11 | 12 | ############################################################### 13 | # Test if the file_list exists and exclude 14 | if (Test-Path $file_list){ 15 | Remove-Item $file_list 16 | } 17 | 18 | ############################################################### 19 | # Create a new list 20 | foreach ($file in $files){ 21 | $filename = $file.FullName 22 | Out-File -filepath $file_list -inputobject "$filename" -Append 23 | } 24 | 25 | ############################################################### 26 | # Print the content of list 27 | if (Test-Path $file_list){ 28 | Get-Content $file_list 29 | Remove-Item $file_list 30 | } 31 | exit 0 32 | -------------------------------------------------------------------------------- /conf/scripts/_password_generator.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "Usage _password_generator.sh [number of passwords to generate] [password size]" 4 | echo "Default [number of passwords to generate] = 1" 5 | echo "Default [passwords size] = 44" 6 | 7 | # No parameters 8 | if [ $# -eq 0 ]; then 9 | size=44 10 | number=1 11 | elif [ $# -eq 1 ]; then 12 | number=$1 13 | size=44 14 | elif [ $# -eq 2 ]; then 15 | number=$1 16 | size=$2 17 | fi 18 | 19 | 20 | #for i in $(eval echo {$A..$B}) do volume=`printf "$PREFIX%04d" $i` 21 | 22 | 23 | echo -e "size: $size" 24 | for i in $(eval echo {1..$number}); 25 | do 26 | password=`tr -dc A-Za-z0-9_/ < /dev/urandom | head -c $size` 27 | #printf "password %02d: $password\n" $i 28 | printf "$password\n" 29 | done 30 | -------------------------------------------------------------------------------- /conf/scripts/_query.sql: -------------------------------------------------------------------------------- 1 | # 2 | # This file contains sample queries that you can possibly use in 3 | # your query.sql file. However, please note that these examples 4 | # are not supported. They may or may not work -- in fact, they may 5 | # work with one SQL engine and not another. As a consequence, 6 | # please do not submit bug reports on either query.sql or 7 | # sample-query.sql 8 | # 9 | # If you find that they work for MySQL and not for PostgreSQL, 10 | # then please send us a whole new file corrected for PostgreSQL 11 | # and we will post it in the examples directory for everyone 12 | # to use. 13 | # 14 | 15 | # 1 16 | :List up to 20 places where a File is saved regardless of the directory 17 | *Enter Filename (no path): 18 | SELECT DISTINCT Job.JobId as JobId, Client.Name as Client, 19 | Path.Path,Filename.Name,StartTime,Level,JobFiles, human_size(JobBytes) as JobBytes 20 | FROM Client,Job,File,Filename,Path WHERE Client.ClientId=Job.ClientId 21 | AND JobStatus IN ('T','W') AND Job.JobId=File.JobId 22 | AND Path.PathId=File.PathId AND Filename.FilenameId=File.FilenameId 23 | AND Filename.Name='%1' 24 | ORDER BY Job.EndTime DESC LIMIT 20; 25 | # 2 26 | :List where the most recent copies of a file are saved 27 | *Enter path with trailing slash: 28 | *Enter filename: 29 | *Enter Client name: 30 | SELECT DISTINCT Job.JobId,StartTime AS JobStartTime,VolumeName,Client.Name AS ClientName 31 | FROM Job,File,Path,Filename,Media,JobMedia,Client 32 | WHERE File.JobId=Job.JobId 33 | AND Path.Path='%1' 34 | AND Filename.Name='%2' 35 | AND Client.Name='%3' 36 | AND Path.PathId=File.PathId 37 | AND Filename.FilenameId=File.FilenameId 38 | AND JobMedia.JobId=Job.JobId 39 | AND JobMedia.MediaId=Media.MediaId 40 | AND Client.ClientId=Job.ClientId 41 | ORDER BY Job.StartTime DESC LIMIT 5; 42 | # 3 43 | :List last 20 Full Backups for a Client 44 | *Enter Client name: 45 | SELECT DISTINCT Job.JobId,Client.Name AS Client,StartTime,JobFiles,human_size(JobBytes) as JobBytes, 46 | JobMedia.StartFile as VolFile,VolumeName 47 | FROM Client,Job,JobMedia,Media 48 | WHERE Client.Name='%1' 49 | AND Client.ClientId=Job.ClientId 50 | AND Level='F' AND JobStatus IN ('T', 'W') 51 | AND JobMedia.JobId=Job.JobId AND JobMedia.MediaId=Media.MediaId 52 | ORDER BY Job.StartTime DESC LIMIT 20; 53 | # 4 54 | :List all backups for a Client after a specified time 55 | *Enter Client Name: 56 | *Enter time in YYYY-MM-DD HH:MM:SS format: 57 | SELECT DISTINCT Job.JobId,Client.Name as Client,Level,StartTime,JobFiles,human_size(JobBytes) as JobBytes,VolumeName 58 | FROM Client,Job,JobMedia,Media 59 | WHERE Client.Name='%1' 60 | AND Client.ClientId=Job.ClientId 61 | AND JobStatus IN ('T', 'W') 62 | AND JobMedia.JobId=Job.JobId AND JobMedia.MediaId=Media.MediaId 63 | AND Job.StartTime >= '%2' 64 | ORDER BY Job.StartTime; 65 | # 5 66 | :List all backups for a Client 67 | *Enter Client Name: 68 | SELECT DISTINCT Job.JobId as JobId,Client.Name as Client, 69 | FileSet.FileSet AS FileSet,Level,StartTime, 70 | JobFiles,human_size(JobBytes) as JobBytes,VolumeName 71 | FROM Client,Job,JobMedia,Media,FileSet 72 | WHERE Client.Name='%1' 73 | AND Client.ClientId=Job.ClientId AND Job.Type='B' 74 | AND Job.JobStatus IN ('T','W') AND Job.FileSetId=FileSet.FileSetId 75 | AND JobMedia.JobId=Job.JobId AND JobMedia.MediaId=Media.MediaId 76 | ORDER BY Job.StartTime; 77 | # 6 78 | :List Volume Attributes for a selected Volume 79 | *Enter Volume name: 80 | SELECT Slot,MaxVolBytes,VolCapacityBytes,VolStatus,Recycle,VolRetention, 81 | VolUseDuration,MaxVolJobs,MaxVolFiles 82 | FROM Media 83 | WHERE VolumeName='%1'; 84 | # 7 85 | :List Volumes used by selected JobId 86 | *Enter JobId: 87 | SELECT DISTINCT Job.JobId,VolumeName 88 | FROM Job,JobMedia,Media 89 | WHERE Job.JobId=%1 90 | AND Job.JobId=JobMedia.JobId 91 | AND JobMedia.MediaId=Media.MediaId; 92 | # 8 93 | :List Volumes to Restore All Files 94 | *Enter Client Name: 95 | !DROP TABLE temp; 96 | !DROP TABLE temp2; 97 | CREATE TABLE temp (JobId BIGINT NOT NULL, 98 | JobTDate BIGINT, 99 | ClientId BIGINT, 100 | Level CHAR, 101 | StartTime TEXT, 102 | VolumeName TEXT, 103 | StartFile BIGINT, 104 | VolSessionId BIGINT, 105 | VolSessionTime BIGINT ); 106 | CREATE TABLE temp2 (JobId BIGINT NOT NULL, 107 | StartTime TEXT, 108 | VolumeName TEXT, 109 | Level CHAR, 110 | StartFile BIGINT, 111 | VolSessionId BIGINT, 112 | VolSessionTime BIGINT); 113 | # Select last Full save 114 | INSERT INTO temp SELECT Job.JobId,JobTDate,Job.ClientId,Job.Level, 115 | StartTime,VolumeName,JobMedia.StartFile,VolSessionId,VolSessionTime 116 | FROM Client,Job,JobMedia,Media WHERE Client.Name='%1' 117 | AND Client.ClientId=Job.ClientId 118 | AND Level='F' AND JobStatus IN ('T', 'W') 119 | AND JobMedia.JobId=Job.JobId 120 | AND JobMedia.MediaId=Media.MediaId 121 | ORDER BY Job.JobTDate DESC LIMIT 1; 122 | # Copy into temp 2 getting all volumes of Full save 123 | INSERT INTO temp2 SELECT Job.JobId,Job.StartTime,Media.VolumeName,Job.Level, 124 | JobMedia.StartFile,Job.VolSessionId,Job.VolSessionTime 125 | FROM temp,Job,JobMedia,Media WHERE temp.JobId=Job.JobId 126 | AND Job.Level='F' AND Job.JobStatus IN ('T', 'W') 127 | AND JobMedia.JobId=Job.JobId 128 | AND JobMedia.MediaId=Media.MediaId; 129 | # Now add subsequent incrementals 130 | INSERT INTO temp2 SELECT DISTINCT Job.JobId,Job.StartTime,Media.VolumeName, 131 | Job.Level,JobMedia.StartFile,Job.VolSessionId,Job.VolSessionTime 132 | FROM Job,temp,JobMedia,Media 133 | WHERE Job.JobTDate>temp.JobTDate 134 | AND Job.ClientId=temp.ClientId 135 | AND Job.Level IN ('I','D') AND JobStatus IN ('T', 'W') 136 | AND JobMedia.JobId=Job.JobId 137 | AND JobMedia.MediaId=Media.MediaId; 138 | # list results 139 | SELECT DISTINCT VolumeName from temp2; 140 | !DROP TABLE temp; 141 | !DROP TABLE temp2; 142 | # 9 143 | :List Pool Attributes for a selected Pool 144 | *Enter Pool name: 145 | SELECT Recycle,VolRetention,VolUseDuration,MaxVolJobs,MaxVolFiles,MaxVolBytes 146 | FROM Pool 147 | WHERE Name='%1'; 148 | # 10 149 | :List total files/bytes by Job 150 | SELECT count(*) AS Jobs,sum(JobFiles) AS Files, human_size(sum(JobBytes)) AS Bytes,Name AS Job 151 | FROM Job GROUP by Name; 152 | # 11 153 | :List total files/bytes by Volume 154 | SELECT count(*) AS Jobs,sum(JobFiles) AS Files, human_size(sum(JobBytes)) AS Bytes,VolumeName 155 | FROM Job,JobMedia,Media 156 | WHERE JobMedia.JobId=Job.JobId 157 | AND JobMedia.MediaId=Media.MediaId 158 | GROUP by VolumeName; 159 | # 12 160 | :List Files for a selected JobId 161 | *Enter JobId: 162 | SELECT Path.Path,Filename.Name FROM File,Filename,Path WHERE File.JobId=%1 163 | AND Filename.FilenameId=File.FilenameId 164 | AND Path.PathId=File.PathId ORDER BY 165 | Path.Path,Filename.Name; 166 | # 13 167 | :List Jobs stored on a selected MediaId 168 | *Enter MediaId: 169 | SELECT DISTINCT Job.JobId,Job.Name,Job.StartTime,Job.Type, 170 | Job.Level,Job.JobFiles, human_size(Job.JobBytes) as Bytes,Job.JobStatus 171 | FROM JobMedia,Job 172 | WHERE JobMedia.JobId=Job.JobId 173 | AND JobMedia.MediaId=%1 174 | ORDER by Job.StartTime; 175 | # 14 176 | :List Jobs stored for a given Volume name 177 | *Enter Volume name: 178 | SELECT DISTINCT Job.JobId as JobId,Job.Name as Name,Job.StartTime as StartTime, 179 | Job.Type as Type,Job.Level as Level,Job.JobFiles as Files, 180 | human_size(Job.JobBytes) as Bytes,Job.JobStatus as Status 181 | FROM Media,JobMedia,Job 182 | WHERE Media.VolumeName='%1' 183 | AND Media.MediaId=JobMedia.MediaId 184 | AND JobMedia.JobId=Job.JobId 185 | ORDER by Job.StartTime; 186 | # 15 187 | :List Volumes Bacula thinks are in changer 188 | SELECT MediaId,VolumeName,VolBytes/(1024*1024*1024) AS GB,Storage.Name 189 | AS Storage,Slot,Pool.Name AS Pool,MediaType,VolStatus 190 | FROM Media,Pool,Storage 191 | WHERE Media.PoolId=Pool.PoolId 192 | AND Slot>0 AND InChanger=1 193 | AND Media.StorageId=Storage.StorageId 194 | ORDER BY MediaType ASC, Slot ASC; 195 | # 16 196 | :List Volumes likely to need replacement from age or errors 197 | SELECT VolumeName AS Volume,VolMounts AS Mounts,VolErrors AS Errors, 198 | VolWrites AS Writes,VolStatus AS Status 199 | FROM Media 200 | WHERE (VolErrors>0) OR (VolStatus='Error') OR (VolMounts>50) OR 201 | (VolStatus='Disabled') OR (VolWrites>3999999) 202 | ORDER BY VolStatus ASC, VolErrors,VolMounts,VolumeName DESC; 203 | # 17 204 | :List Volumes Bacula thinks are eligible for the changer 205 | SELECT VolumeName,VolStatus,Storage.Name AS Location, 206 | human_size(VolBytes) as Bytes,MediaId,MediaType,Pool.Name AS Pool 207 | FROM Media,Pool,Storage 208 | WHERE Media.PoolId=Pool.PoolId 209 | AND Media.StorageId=Storage.StorageId 210 | AND InChanger=0 211 | AND ((VolStatus='Purged') OR (VolStatus='Append') OR (VolStatus='Recycle')) 212 | ORDER BY VolMounts ASC, Pool.Name ASC, VolumeName ASC 213 | # 18 214 | :List Volumes by Volume: 215 | SELECT VolumeName, Job.JobId as JobID, Job.Name as JobName, Job.StartTime as 216 | Start, sum(JobFiles) AS Files, lpad(human_size(sum(JobBytes)),10,' ') AS Bytes 217 | FROM Job,JobMedia,Media 218 | WHERE JobMedia.JobId=Job.JobId 219 | AND JobMedia.MediaId=Media.MediaId 220 | GROUP by VolumeName, Job.JobID, Job.Name, Job.StartTime 221 | ORDER by VolumeName; 222 | # 19 223 | :List Volumes by Jobs: 224 | SELECT Job.Name as JobName, Job.JobId as JobID, VolumeName, Job.StartTime as 225 | Start, sum(JobFiles) AS Files,human_size(sum(Job.JobBytes)) AS Bytes 226 | FROM Job,JobMedia,Media 227 | WHERE JobMedia.JobId=Job.JobId 228 | AND JobMedia.MediaId=Media.MediaId 229 | GROUP by VolumeName, Job.JobID, Job.Name, Job.StartTime 230 | ORDER by JobName, Start; 231 | # 20 232 | :List Volumes for a jobname: 233 | *Enter Job name: 234 | SELECT Job.Name as JobName, Job.JobId as JobID, VolumeName, Job.StartTime as 235 | Start, sum(JobFiles) AS Files, human_size(sum(JobBytes)) AS Bytes 236 | FROM Job,JobMedia,Media 237 | WHERE Job.Name='%1' 238 | AND JobMedia.JobId=Job.JobId 239 | AND JobMedia.MediaId=Media.MediaId 240 | GROUP by VolumeName, Job.JobID, Job.Name, Job.StartTime 241 | ORDER by JobName, Start; 242 | # 21 243 | :List Counters 244 | SELECT Counters.Counter, Counters.MinValue, Counters.MaxValue, Counters.CurrentValue FROM Counters; 245 | # 22 246 | :List JobTotals 247 | SELECT count(*) AS Jobs,sum(JobFiles) AS Files, Type, human_size(sum(JobBytes)) AS JobBytes, Name AS Job FROM Job WHERE Type in ('B','R') GROUP BY Name; 248 | SELECT count(*) AS Jobs,sum(JobFiles) AS Files, Type, human_size(sum(JobBytes)) AS JobBytes FROM Job WHERE Type in ('B','R') GROUP BY Type; 249 | # 23 250 | :Find localization of File in JobId 251 | *Enter JobID: 252 | *Enter Filename: 253 | select A.JobId, cast(D.Name as char) as JobName, cast(concat(C.Path, B.Name) as char) as Filename 254 | from File A 255 | left join Filename B on (A.FilenameId = B.FilenameId) 256 | left join Path C on (A.PathId = C.PathId) 257 | left join Job D on (A.JobId = D.JobId) 258 | where A.JobId = '%1' and cast(concat(C.Path, B.Name) as char) like concat('%',lower('%2'),'%'); 259 | # 24 260 | :List Jobs where a given File is saved 261 | *Enter client name: 262 | *Enter Filename (without path): 263 | *Enter Path or leave empty: 264 | SELECT Job.JobId as JobId,cast(CONCAT(Path.Path,Filename.Name) as char) as Name, StartTime,cast(Type as char) as JobType, cast(JobStatus as char) as JobStatus,JobFiles,JobBytes 265 | FROM Client,Job,File,Filename,Path 266 | WHERE Client.Name='%1' AND Client.ClientId=Job.ClientId AND Job.JobId=File.JobId 267 | AND File.FileIndex > 0 AND Path.PathId=File.PathId AND Filename.FilenameId=File.FilenameId 268 | AND Filename.Name='%2' and Path.Path like '%3%' 269 | ORDER BY StartTime DESC limit 100; 270 | -------------------------------------------------------------------------------- /conf/scripts/_rclone_sync.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Author: Wanderlei Hüttel 3 | # Email: wanderlei.huttel@gmail.com 4 | # Version: 2.1 5 | # Date: April 07, 2022 6 | 7 | #============================================================================================================= 8 | # Copy Bacula Volumes to Onedrive/Wasabi S3 Cloud and notify by telegram 9 | #============================================================================================================= 10 | 11 | 12 | #============================================================================================================= 13 | # Debug Mode 14 | # false=disabled verbose mode | true=enabled verbose mode 15 | debug_verbose=true # false=disabled verbose mode | true=enabled verbose mode 16 | 17 | 18 | #============================================================================================================= 19 | # Global Variables 20 | # Do not modify the variables below 21 | g_retval=0 # global return value 22 | g_count=0 # global count files transferred 23 | g_message="" # global message 24 | 25 | # Binaries 26 | rclone=$(which rclone) 27 | jq=$(which jq) 28 | curl=$(which curl) 29 | 30 | # Date Variables 31 | starttime=$(date +%s) 32 | dayofweek=$(date +%u) 33 | dayofmonth=$(date +%-d) 34 | 35 | # These ones you can modify 36 | # Rclone Default Parameters 37 | log_file_tmp="/var/log/bacula/rclone.tmp" 38 | log_file="/var/log/bacula/rclone.log" 39 | dry_run="--dry-run" # --dry-run = # Do a trial run without permanent changes. 40 | debug="--log-file ${log_file_tmp} --log-level INFO ${dry_run}" 41 | options="--stats=1000m --rc --rc-web-gui --rc-addr 0.0.0.0:5572 --rc-user admin --rc-pass admin --rc-web-gui-no-open-browser" 42 | 43 | 44 | # Telegram API (Send messages) 45 | api_token="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 46 | chat_id="YYYYYYYYY" 47 | 48 | 49 | #============================================================================================================= 50 | # JSON with rclone commands 51 | json='[ 52 | {"name":"/etc/bacula","command":"sync","provider":"onedrive","bucket":"bacula-backup","source":"/etc/bacula","destination":"/etc/bacula","params":"--onedrive-no-versions --exclude=\"*.pid\" --exclude=\"*.state\" --exclude=\"*.conmsg\" --exclude=\"*.trace\""}, 53 | {"name":"Pools: Diária, Semanal e Mensal","command":"copyto","provider":"onedrive","bucket":"bacula-backup","source":"/backup/disco01","destination":"/StorageLocal1","params":"--onedrive-no-versions --include=\"Volume-Diario-*\" --include=\"Volume-Semanal-*\" --include=\"Volume-Mensal-*\""}, 54 | {"name":"Pool: VM", "command":"copyto" , "provider":"onedrive", "bucket":"bacula-backup", "source":"/backup/disco02", "destination":"/StorageLocal2", "params":"--onedrive-no-versions --include=\"Volume-VM-*\""} 55 | ]' 56 | 57 | 58 | #============================================================================================================= 59 | # Creates a lockfile during script execution 60 | # If any other script is running it aborts the script 61 | script_name=$(basename $0) 62 | lockfile="/var/run/${script_name}.pid" 63 | if [[ -e "$lockfile" ]]; then 64 | pid=$(cat $lockfile) 65 | if [[ -e /proc/${pid} ]]; then 66 | echo "${script_name}: Process ${pid} is still running, exiting." 67 | exit 1 68 | else 69 | # Clean up previous lock file 70 | rm -f $lockfile 71 | fi 72 | fi 73 | trap "rm -f $lockfile; exit $?" INT TERM EXIT 74 | # write $$ (PID) to the lock file 75 | echo "$$" > $lockfile 76 | 77 | 78 | #============================================================================================================= 79 | # Function to show messages on debug and send to log file 80 | function fn_show_message(){ 81 | if $debug_verbose; then 82 | # echo -ne "$(date +"%Y/%m/%d %H:%M:%S ")$*\n" 83 | echo "$(date +"%Y/%m/%d %H:%M:%S ")$*" 84 | fi 85 | echo "$(date +"%Y/%m/%d %H:%M:%S ")$*" >> $log_file 86 | } 87 | 88 | 89 | #============================================================================================================= 90 | # Function to read rclone log and extract data summary 91 | function fn_rclone_sync(){ 92 | fn_show_message "$(<$1)" 93 | g_retval=$(grep "There was nothing to transfer" $1 | wc -l) 94 | fn_show_message "Transfers had ocurred (g_retval: $g_retval)" 95 | if (( g_retval == 0 )); then 96 | log=$(grep -E "^(Transferred:|Elapsed time:)" $1 | sed -E 's/.*:\s+//g; s/\s?\/.*$//g' | tr '\n' '|') 97 | bytes=$(cut -d'|' -f1 <<< $log) 98 | files=$(cut -d'|' -f2 <<< $log) 99 | elapsed=$(cut -d'|' -f3 <<< $log) 100 | fn_show_message "log sed: $log" 101 | fn_show_message "variables: bytes=$bytes|files=$files|elapsed=$elapsed" 102 | g_message="Tamanho=$bytes/nArquivos=$files/nDuração=$elapsed/n" 103 | (( g_count+=files )) 104 | else 105 | fn_show_message "There was nothing to transfer (g_retval: $g_retval)" 106 | fi 107 | rm -f $log_file_tmp 108 | } 109 | 110 | 111 | #============================================================================================================= 112 | # Message 113 | header=">>>>> 💾 RCLONE BACKUP TO CLOUD 📤 <<<< 0 )); then 152 | message="${message}Total de arquivos enviados: $g_count/n/n" 153 | else 154 | message="${message}Nenhum arquivo foi enviado!/n/n" 155 | fi 156 | 157 | endtime=$(date +%s) 158 | (( totaltime = endtime - starttime + 10800 )) 159 | 160 | 161 | fn_show_message "Rclone copy start: $(date -d @${starttime} +%H:%M:%S)" 162 | fn_show_message "Rclone copy finished: $(date -d @${endtime} +%H:%M:%S)" 163 | fn_show_message "Rclone copy elapsed time: $(date -d @${totaltime} +%H:%M:%S)" 164 | fn_show_message "##### Rclone Copy Bacula Backup to Cloud ##### - finished" 165 | 166 | 167 | # Send Telegram Message 168 | message="${message}Rclone Finished/n$(date -d @${endtime} +'%d/%m/%Y %H:%M:%S')/n/n" 169 | message="${message}Rclone Elapsed Time/n$(date -d @${totaltime} +%H:%M:%S)/n/n" 170 | #message=$(echo ${message} | sed 's/\/n/%0A/g') 171 | message=$(sed 's/\/n/%0A/g' <<< $messsage) 172 | url="https://api.telegram.org/bot${api_token}/sendMessage?chat_id=${chat_id}&text=${message}" 173 | $curl -s "$url" > /dev/null 174 | -------------------------------------------------------------------------------- /conf/scripts/_send_telegram_mysql.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 4 | # Function to convert bytes for human readable 5 | b2h(){ 6 | # Spotted Script @: http://www.linuxjournal.com/article/9293?page=0,1 7 | SLIST=" bytes, KB, MB, GB, TB, PB, EB, ZB, YB" 8 | POWER=1 9 | VAL=$( echo "scale=2; $1 / 1" | bc) 10 | VINT=$( echo $VAL / 1024 | bc ) 11 | while [ ! $VINT = "0" ] 12 | do 13 | let POWER=POWER+1 14 | VAL=$( echo "scale=2; $VAL / 1024" | bc) 15 | VINT=$( echo $VAL / 1024 | bc ) 16 | done 17 | echo $VAL$( echo $SLIST | cut -f$POWER -d, ) 18 | } 19 | # end function 20 | 21 | # Variables 22 | HOUR=$(date +%d/%m/%Y\ %H:%M:%S) 23 | 24 | 25 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 26 | # Config 27 | DBHOST="localhost" 28 | DBPORT="3306" 29 | DBNAME="bacula" 30 | DBUSER="bacula" 31 | DBPASSWD="bacula" 32 | # Use @BotFather to create a bot an get the API token 33 | # Telegram config 34 | API_TOKEN="CHANGE_WITH_YOUR_API_KEY" 35 | # Send a message to bot and 36 | # Open in browser the url https://api.telegram.org/bot${API_TOKEN}/getUpdates and get the id value os user 37 | ID="CHANGE_WITH_YOUR_USER_ID" 38 | LOG="/var/log/telegram.log" 39 | 40 | 41 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 42 | # SQL query to get data from Job (PostreSQL) 43 | sql_query="select Job.Name, Job.JobId,(select Client.Name from Client where Client.ClientId = Job.ClientId) as Client, Job.JobBytes, Job.JobFiles, case when Job.Level = 'F' then 'Full' when Job.Level = 'I' then 'Incremental' when Job.Level = 'D' then 'Differential' end as Level, (select Pool.Name from Pool where Pool.PoolId = Job.PoolId) as Pool, (select Storage.Name from JobMedia left join Media on (Media.MediaId = JobMedia.MediaId) left join Storage on (Media.StorageId = Storage.StorageId) where JobMedia.JobId = Job.JobId limit 1 ) as Storage, date_format( Job.StartTime , '%d/%m/%Y %H:%i:%s' ) as StartTime, date_format( Job.EndTime , '%d/%m/%Y %H:%i:%s' ) as EndTime, sec_to_time(TIMESTAMPDIFF(SECOND,Job.StartTime,Job.EndTime)) as Duration, Job.JobStatus, (select Status.JobStatusLong from Status where Job.JobStatus = Status.JobStatus) as JobStatusLong 44 | from Job where Job.JobId=$1" 45 | 46 | 47 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 48 | # Execute SQL and get data from Job table 49 | str=`echo -e "$sql_query" | mysql -u $DBUSER -p$DBPASSWD -D $DBNAME -h $DBHOST -P $DBPORT -B | while read; do sed 's/\t/\|/g'; done` 50 | JobName=`echo $str | cut -d"|" -f1` 51 | JobId=`echo $str | cut -d"|" -f2` 52 | Client=`echo $str | cut -d"|" -f3` 53 | JobBytes=`b2h $(echo $str | cut -d"|" -f4)` 54 | JobFiles=`echo $str | cut -d"|" -f5` 55 | Level=`echo $str | cut -d"|" -f6` 56 | Pool=`echo $str | cut -d"|" -f7` 57 | Storage=`echo $str | cut -d"|" -f8` 58 | StartTime=`echo $str | cut -d"|" -f9` 59 | EndTime=`echo $str | cut -d"|" -f10` 60 | Duration=`echo $str | cut -d"|" -f11` 61 | JobStatus=`echo $str | cut -d"|" -f12` 62 | Status=`echo $str | cut -d"|" -f13` 63 | 64 | 65 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 66 | # Emojis 67 | # OK 68 | # http://emojipedia.org/white-heavy-check-mark/ 69 | # Not OK 70 | # http://emojipedia.org/cross-mark/ 71 | # Floppy Disk 72 | # http://emojipedia.org/floppy-disk/ 73 | # Different header in case of error 74 | if [ "$JobStatus" == "T" ] ; then 75 | HEADER=">>>>> 💾 BACULA BACKUP ✅ <<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 82 | # Format output of message 83 | MESSAGE="$HEADER/nJobName=$JobName/nJobid=$JobId/nClient=$Client/nJobBytes=$JobBytes/nJobFiles=$JobFiles/nLevel=$Level/nPool=$Pool/nStorage=$Storage/nStartTime=$StartTime/nEndTime=$EndTime/nDuration=$Duration/nJobStatus=$JobStatus/nStatus=$Status" 84 | MESSAGELOG="Message: JobName=$JobName | Jobid=$JobId | Client=$Client | JobBytes=$JobBytes | Level=$Level | Status=$Status" 85 | MESSAGE=`echo $MESSAGE | sed 's/\/n/%0A/g'` 86 | URL="https://api.telegram.org/bot${API_TOKEN}/sendMessage?chat_id=${ID}&text=$MESSAGE" 87 | 88 | 89 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 90 | # Loop multiple tries 91 | COUNT=1 92 | while [ $COUNT -le 20 ]; do 93 | 94 | echo "$(date +%d/%m/%Y\ %H:%M:%S) - Start message send (attempt $COUNT) ..." >> $LOG 95 | echo "$(date +%d/%m/%Y\ %H:%M:%S) - $MESSAGELOG" >> $LOG 96 | /usr/bin/curl -s "$URL" > /dev/null 97 | RET=$? 98 | 99 | if [ $RET -eq 0 ]; then 100 | echo "$(date +%d/%m/%Y\ %H:%M:%S) - Attempt $COUNT executed successfully!" >> $LOG 101 | exit 0 102 | else 103 | echo "$(date +%d/%m/%Y\ %H:%M:%S) - Attempt $COUNT failed!" >> $LOG 104 | echo "$(date +%d/%m/%Y\ %H:%M:%S) - Waiting 30 seconds before retry ..." >> $LOG 105 | sleep 30 106 | (( COUNT++ )) 107 | fi 108 | 109 | done 110 | -------------------------------------------------------------------------------- /conf/scripts/_verify_jobs_mysql.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script to Verify Jobs in Bacula 3 | 4 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 5 | # Bacula Database Config 6 | DBHOST="localhost" 7 | DBPORT="3306" 8 | DBNAME="bacula" 9 | DBUSER="bacula" 10 | DBPASSWD="bacula" 11 | 12 | BCONSOLE="/sbin/bconsole" 13 | MYSQL="/usr/bin/mysql" 14 | 15 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 16 | # Check day of Week 17 | # The normal backups are executed from monday-friday 18 | # If verify jobs run on monday, sql needs to get jobs from last friday 19 | WEEKDAY=$(date +%w) 20 | if [ $WEEKDAY -eq 1 ] ; then 21 | NUMBEROFDAYS=3 22 | else 23 | NUMBEROFDAYS=1 24 | fi 25 | 26 | 27 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 28 | # SQL query to get data from Job (MySQL) 29 | if [ $# -eq 1 ]; then 30 | sql_query="SELECT Job.JobId, Job.Name, Client.Name as Client, FileSet.FileSet, 31 | (SELECT DISTINCT Storage.Name FROM JobMedia LEFT JOIN Media ON (JobMedia.MediaId = Media.MediaId) 32 | LEFT JOIN Storage ON (Media.StorageId = Storage.StorageId) WHERE JobMedia.JobId = Job.JobId 33 | ) AS Storage 34 | FROM Job, Client, FileSet 35 | WHERE Job.ClientId = Client.ClientId and Job.FileSetId = FileSet.FileSetId 36 | AND Job.JobStatus = 'T' AND Job.Jobid = $1"; 37 | else 38 | sql_query="SELECT Job.JobId, Job.Name, Client.Name as Client, FileSet.FileSet, 39 | (SELECT DISTINCT Storage.Name FROM JobMedia LEFT JOIN Media ON (JobMedia.MediaId = Media.MediaId) 40 | LEFT JOIN Storage ON (Media.StorageId = Storage.StorageId) WHERE JobMedia.JobId = Job.JobId 41 | ) AS Storage 42 | FROM Job, Client, FileSet 43 | WHERE Job.ClientId = Client.ClientId and Job.FileSetId = FileSet.FileSetId 44 | AND Job.EndTime > (NOW() - INTERVAL $NUMBEROFDAYS DAY) AND Job.JobStatus = 'T' ORDER BY RAND() LIMIT 5;" 45 | fi 46 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 47 | # Verify Jobs Used 48 | #verify_array=( "Verify_Data" "Verify_VolumeToCatalog") 49 | verify_array=( "Verify_Data") 50 | 51 | 52 | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 53 | # Execute SQL and get data from Job table 54 | query=`echo "$sql_query" | $MYSQL -u $DBUSER -p$DBPASSWD -D $DBNAME -h $DBHOST -P $DBPORT -N -t` 55 | c=10 56 | 57 | echo "$query" | grep -v "\-\-\-" | while read row; do 58 | JobId=`echo $row | cut -d"|" -f2 | sed 's/^ \(.*\) $/\1/'`; 59 | JobName=`echo $row | cut -d"|" -f3 | sed 's/^ \(.*\) $/\1/'`; 60 | Client=`echo $row | cut -d"|" -f4 | sed 's/^ \(.*\) $/\1/'`; 61 | Fileset=`echo $row | cut -d"|" -f5 | sed 's/^ \(.*\) $/\1/'`; 62 | Storage=`echo $row | cut -d"|" -f6 | sed 's/^ \(.*\) $/\1/'`; 63 | Verify_Job=`printf '%s\n' "${verify_array[@]}" | shuf -n1` 64 | JobIdRun=`echo "run job=$Verify_Job client=$Client fileset=$Fileset jobid=$JobId storage=$Storage priority=$c yes" | $BCONSOLE | grep "JobId" | sed 's/[^0-9]*//g'` 65 | # Execute the job in bconsole 66 | echo "run job=$Verify_Job client=$Client fileset=$Fileset jobid=$JobId storage=$Storage priority=$c yes" 67 | (( c++ )) 68 | sleep 1 69 | # The MySQL command update Job name including the Job that was verified 70 | if [ "$JobIdRun" != "" ]; then 71 | $MYSQL -u $DBUSER -p$DBPASSWD -D $DBNAME -h $DBHOST -P $DBPORT -e "update Job set Name = '$JobName (V)' where JobId = $JobIdRun;" 72 | fi 73 | done 74 | -------------------------------------------------------------------------------- /conf/storages.conf: -------------------------------------------------------------------------------- 1 | ######################################################################################## 2 | # storage.conf 3 | 4 | ######################################################################################## 5 | # Dispositivo de Armazenamento 1 6 | Storage { 7 | Name = StorageLocal1 8 | Address = 192.168.1.3 9 | SDPort = 9103 10 | Password = "pZNOKm69Ps58ihJ4NcIwODOTsjrxpNs4KM2WaJoayeAQ" 11 | Device = DiscoLocal1 12 | Media Type = File 13 | Maximum Concurrent Jobs = 50 14 | Heartbeat Interval = 300 seconds 15 | } 16 | 17 | 18 | ######################################################################################## 19 | # Dispositivo de Armazenamento 2 20 | Storage { 21 | Name = StorageLocal2 22 | Address = 192.168.1.3 23 | SDPort = 9103 24 | Password = "pZNOKm69Ps58ihJ4NcIwODOTsjrxpNs4KM2WaJoayeAQ" 25 | Device = DiscoLocal2 26 | Media Type = File 27 | Maximum Concurrent Jobs = 50 28 | Heartbeat Interval = 300 seconds 29 | } 30 | -------------------------------------------------------------------------------- /convert_mysql_to_postgresql/import_postgresql.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ####################################### 4 | # Config Parameters 5 | 6 | # Create file /root/.pgpass with PostgreSQL credentials 7 | 8 | # begin of file 9 | # #hostname:port:database:username:password 10 | # localhost:5432:bacula:bacula:bacula 11 | # end of file 12 | 13 | sequence="sequence.sql" 14 | db_user="bacula" 15 | db_name="bacula" 16 | row_count="RowCountPg.log" 17 | psql=$(which psql) 18 | # List of Bacula Tables 19 | # tables (Status and Version) are not imported, they are generated during make_postgresql_tables script 20 | tables="BaseFiles CDImages Client Counters Device File FileSet Filename Job JobHisto JobMedia Location LocationLog Log Media MediaType Path PathHierarchy PathVisibility Pool RestoreObject Snapshot Storage UnsavedFiles" 21 | 22 | ####################################### 23 | # Start Import 24 | echo "-----------------------------------------------" 25 | echo " Import Bacula Catalog from MySQL to PostgreSQL" 26 | echo " Author: Wanderlei Hüttel" 27 | echo " Email: wanderlei.huttel@gmail.com" 28 | echo " Version: 1.3 - 20/11/2018" 29 | echo "-----------------------------------------------" 30 | echo 31 | echo "Importing MySQL tables ..." 32 | echo "--------------------------------------------" 33 | echo "Table Time" 34 | echo "--------------------------------------------" 35 | 36 | totalstarttime=$(date -u +%s) 37 | for table in ${tables}; do 38 | log="${table}.log" 39 | starttime=$(date -u +%s) 40 | ${psql} -U ${db_user} -d ${db_name} -f "${table}.sql" > /dev/null 2>> ${log} 41 | endtime=$(date -u +%s) 42 | elapsedtime=$(expr ${endtime} - ${starttime}) 43 | printf "%-15s %8s\n" ${table} $(date -ud @${elapsedtime} +%H:%M:%S) 44 | done 45 | 46 | 47 | ####################################### 48 | # Update sequences 49 | echo " 50 | SELECT SETVAL('basefiles_baseid_seq', (SELECT MAX(baseid) FROM basefiles)); 51 | SELECT SETVAL('client_clientid_seq', (SELECT MAX(clientid) FROM client)); 52 | SELECT SETVAL('device_deviceid_seq', (SELECT MAX(deviceid) FROM device)); 53 | SELECT SETVAL('file_fileid_seq', (SELECT MAX(fileid) FROM file)); 54 | SELECT SETVAL('filename_filenameid_seq', (SELECT MAX(filenameid) FROM filename)); 55 | SELECT SETVAL('fileset_filesetid_seq', (SELECT MAX(filesetid) FROM fileset)); 56 | SELECT SETVAL('job_jobid_seq', (SELECT MAX(jobid) FROM job)); 57 | SELECT SETVAL('jobmedia_jobmediaid_seq', (SELECT MAX(jobmediaid) FROM jobmedia)); 58 | SELECT SETVAL('location_locationid_seq', (SELECT MAX(locationid) FROM location)); 59 | SELECT SETVAL('locationlog_loclogid_seq', (SELECT MAX(loclogid) FROM locationlog)); 60 | SELECT SETVAL('log_logid_seq', (SELECT MAX(logid) FROM log)); 61 | SELECT SETVAL('media_mediaid_seq', (SELECT MAX(mediaid) FROM media)); 62 | SELECT SETVAL('mediatype_mediatypeid_seq', (SELECT MAX(mediatypeid) FROM mediatype)); 63 | SELECT SETVAL('path_pathid_seq', (SELECT MAX(pathid) FROM path)); 64 | SELECT SETVAL('pool_poolid_seq', (SELECT MAX(poolid) FROM pool)); 65 | SELECT SETVAL('restoreobject_restoreobjectid_seq', (SELECT MAX(restoreobjectid) FROM restoreobject)); 66 | SELECT SETVAL('snapshot_snapshotid_seq', (SELECT MAX(snapshotid) FROM snapshot)); 67 | SELECT SETVAL('storage_storageid_seq', (SELECT MAX(storageid) FROM storage)); 68 | " > ${sequence} 69 | ${psql} -U ${db_user} -d ${db_name} -f ${sequence} > /dev/null 2>> sequence.log 70 | totalendtime=$(date -u +%s) 71 | totalelapsedtime=$(expr ${totalendtime} - ${totalstarttime}) 72 | 73 | echo "--------------------------------------------" 74 | echo "Elapsed time: $(date -ud @${totalelapsedtime} +%H:%M:%S)" 75 | echo "--------------------------------------------" 76 | echo 77 | echo 78 | echo "" > ${row_count} 79 | 80 | ####################################### 81 | # Count rows by tables 82 | tables="BaseFiles CDImages Client Counters Device File FileSet Filename Job JobHisto JobMedia Location LocationLog Log Media MediaType Path PathHierarchy PathVisibility Pool RestoreObject Snapshot Status Storage UnsavedFiles Version" 83 | echo "Total tables row count" 84 | echo "--------------------------------------------" 85 | echo "Table Row Count" 86 | echo "--------------------------------------------" 87 | 88 | sql_query="select table_name from information_schema.tables where table_catalog = 'bacula' and table_schema = 'public' and table_name not like 'webacula_%' order by table_name" 89 | for table in ${tables}; do 90 | sql_query="select '$table' tabela, count(*) total from $table;"; 91 | ${psql} -U ${db_user} ${db_name} -t -c "$sql_query" | tr '[:upper:]' '[:lower:]' >> ${row_count}; 92 | done 93 | sed -i 's/\s//g' ${row_count} 94 | sed -i '/^$/d' ${row_count} 95 | sort ${row_count} -o ${row_count} 96 | output=$(<${row_count}) 97 | output=$(echo -e $output | sed 's/[|]/\t/g') 98 | printf "%-15s %8s\n" $output 99 | echo "--------------------------------------------" 100 | echo 101 | echo 102 | 103 | ####################################### 104 | # Update break line in table LogText 105 | echo "--------------------------------------------" 106 | echo "Updating break line in table LogText..." 107 | ${psql} -U ${db_user} ${db_name} -c "UPDATE Log SET LogText = replace(LogText,'\n',E'\n');"; 108 | echo "--------------------------------------------" 109 | echo 110 | echo "Done" 111 | -------------------------------------------------------------------------------- /convert_mysql_to_postgresql/mysql_to_postresql.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ####################################### 4 | # Config Parameters 5 | db_username="root" 6 | db_password="" 7 | db_name="bacula" 8 | db_host="localhost" 9 | row_count="RowCountMySQL.log" 10 | 11 | echo "--------------------------------------------" 12 | echo " Convert Bacula Catalog MySQL to PostgreSQL" 13 | echo " Author: Wanderlei Hüttel" 14 | echo " Email: wanderlei.huttel@gmail.com" 15 | echo " Version: 1.3 - 20/11/2018" 16 | echo 17 | echo "--------------------------------------------" 18 | echo "Please inform your database credentials..." 19 | read -p "MySQL db_name: " -i "${db_name}" -e db_name 20 | read -p "MySQL db_username: " -i "${db_username}" -e db_username 21 | read -p "MySQL db_host: " -i "${db_host}" -e db_host 22 | read -p "MySQL db_password ${db_username}: " -s db_password 23 | echo 24 | echo "--------------------------------------------" 25 | 26 | mysql=$(which mysql) 27 | mysqldump=$(which mysqldump) 28 | 29 | # List of Bacula Tables 30 | tables="BaseFiles CDImages Client Counters Device File FileSet Filename Job JobHisto JobMedia Location LocationLog Log Media MediaType Path PathHierarchy PathVisibility Pool RestoreObject Snapshot Status Storage UnsavedFiles Version" 31 | 32 | ####################################### 33 | # Check if the password is not empty 34 | if [ ! -z ${db_password} ]; then 35 | db_password="-p${db_password}" 36 | fi 37 | 38 | ####################################### 39 | # 40 | echo 41 | echo "Dumping MySQL tables ..." 42 | echo "--------------------------------------------" 43 | echo "Table Time" 44 | echo "--------------------------------------------" 45 | totalstarttime=$(date -u +%s) 46 | for table in ${tables}; do 47 | starttime=$(date -u +%s) 48 | 49 | echo "\set AUTOCOMMIT OFF" >> "${table}.sql" 50 | ${mysqldump} --no-create-info \ 51 | --no-create-db \ 52 | --complete-insert \ 53 | --compatible=postgresql \ 54 | --skip-quote-names \ 55 | --disable-keys \ 56 | --lock-tables \ 57 | --compact \ 58 | --skip-opt \ 59 | --quick \ 60 | -h ${db_host} -u ${db_username} ${db_password} ${db_name} ${table} | \ 61 | sed -e 's/0000-00-00 00:00:00/1970-01-01 00:00:00/g' | \ 62 | sed -e 's/\\0//g' | \ 63 | sed -e 's/\\"/"/g' | \ 64 | sed -e 's/\\\\/\\/g' | \ 65 | sed -e "s/\\\'/\'\'/g" | \ 66 | sed -e "s/_binary//g" \ 67 | >> "${table}.sql" 68 | echo "COMMIT;" >> "${table}.sql" 69 | 70 | endtime=$(date -u +%s) 71 | elapsedtime=$(expr ${endtime} - ${starttime}) 72 | printf "%-15s %8s\n" ${table} $(date -ud @${elapsedtime} +%H:%M:%S) 73 | done 74 | totalendtime=$(date -u +%s) 75 | totalelapsedtime=$(expr ${totalendtime} - ${totalstarttime}) 76 | echo "--------------------------------------------" 77 | echo "Elapsed time: $(date -ud @${totalelapsedtime} +%H:%M:%S)" 78 | echo "--------------------------------------------" 79 | echo 80 | echo 81 | echo "" > ${row_count} 82 | 83 | ####################################### 84 | # Count rows by tables 85 | for table in ${tables} ; do 86 | sql_query="select '$table' as tabela, count(*) as total from $table;" 87 | ${mysql} -h ${db_host} -u ${db_username} -D ${db_name} ${db_password} -N -B -e "$sql_query" \ 88 | | sed 's/\t/\|/g' | tr '[:upper:]' '[:lower:]' >> ${row_count} 89 | done 90 | 91 | sed -i 's/\s//g' ${row_count} 92 | sed -i '/^$/d' ${row_count} 93 | sort ${row_count} -o ${row_count} 94 | echo "Total tables row count" 95 | echo "--------------------------------------------" 96 | echo "Table Row Count" 97 | echo "--------------------------------------------" 98 | output=$(<${row_count}) 99 | output=$(echo -e $output | sed 's/[|]/\t/g') 100 | printf "%-15s %8s\n" $output 101 | echo "--------------------------------------------" 102 | echo 103 | echo "Done" 104 | -------------------------------------------------------------------------------- /convert_mysql_to_postgresql/readme.md: -------------------------------------------------------------------------------- 1 | ### Script do convert MySQL to PostgreSQL 2 | Based on Bacula Manual 3 | https://www.bacula.org/9.2.x-manuals/en/main/Installing_Configuring_Post.html#SECTION004450000000000000000 4 | 5 | This script is used to convert a Bacula Database from MySQL to PostgreSQL. 6 | It was tested using MySQL 5.6 and 5.7 to a PostgreSQL 9.4 and 9.6 and Bacula 9.0.8 and Bacula 9.2.2 7 | 8 | This migration script was simulated in a environment using a compiled Bacula with MySQL running for years. The configuration files was the same. 9 | 10 | The Bacula Daemons was stopped and Bacula was compiled again and was configured like a fresh Bacula environment but now with PostgreSQL. 11 | 12 | So, after the Bacula with PostgreSQL was running OK, I've stopped Bacula Daemons again and run the scripts below to cleanup the PostgreSQL database, for make sure that was a fresh install. 13 | (Even if you only start Bacula Director, Bacula save data into database from config files) 14 | - drop_postgresql_database 15 | - create_postgresql_database 16 | - make_postgresql_tables 17 | - grant_postgresql_privileges 18 | 19 | 20 | #### 1st step - Download the scripts (mysql_to_postresql.sh and import_postgresql.sh) and save in a directory 21 | ```` 22 | mkdir /usr/src/bacula_migration 23 | cd /usr/src/bacula_migration 24 | wget -c https://raw.githubusercontent.com/wanderleihuttel/bacula-utils/master/convert_mysql_to_postgresql/mysql_to_postresql.sh 25 | wget -c https://raw.githubusercontent.com/wanderleihuttel/bacula-utils/master/convert_mysql_to_postgresql/import_postgresql.sh 26 | ```` 27 | 28 | #### 2nd step - Run the script 'mysql_to_postresql.sh' to generate the database dump 29 | The script will ask for your MySQL credentials and if they OK he script will generate the dump of the tables individually 30 | and a file called 'RowCountMySQL.log' with the total of records by table. 31 | This file will be used later to compare the number of records imported in PostgreSQL 32 | 33 | 34 | #### 3rd step - Configure the parameters in script 'import_postgresql.sh' or keep the default ones 35 | ```` 36 | db_user="bacula" 37 | db_name="bacula" 38 | ```` 39 | 40 | #### 4th step - Create a file '/root/.pgpass' with PostgreSQL credentials and apply permission only for root 600. 41 | ```` 42 | touch /root/.pgpass 43 | chmod 600 /root/.pgpass 44 | # File Example (use your credentials) 45 | # hostname:port:database:username:password 46 | localhost:5432:bacula:bacula:bacula 47 | ```` 48 | 49 | #### 5th step - Run the script 'import_postgresql.sh' to import MySQL dump to PostgreSQL. 50 | If everything works fine, you can compare the files 'RowCountMySQL.log' and 'RowCountPg.log'. 51 | If the number of records of every table in MySQL and PostgreSQL are the same you can be proud, 52 | the migration was finished with success! 53 | 54 | 55 | #### 6th step - Take a look in the files with '.log' extension to check if no errors ocurred 56 | If the content of this log files is similar of "psql:File.sql:2:WARNING: there is no transaction in progress". 57 | The migration was completed with success, if not, is necessary to discovery why the errors ocurred 58 | 59 | 60 | ### Troubleshooting 61 | I had some problems in the 'Log' table, most of which was because of the wrong encoding, coming from Windows backup errors. 62 | I manually edited the table (in MySQL side), correcting the errors, generate the dump again and tried to import only this table. 63 | -------------------------------------------------------------------------------- /dicas/heartbeat_interval.md: -------------------------------------------------------------------------------- 1 | #### Heartbeat Interval = intervalo de tempo 2 | 3 | Para ativar essa opção, deve-se incluir a opção acima nos seguintes recursos: 4 | 5 | ### Arquivo bacula-dir.conf (servidor) 6 | 7 | ```` 8 | Director{ 9 | ... 10 | Heartbeat Interval = 300 seconds 11 | ... 12 | } 13 | 14 | Storage{ 15 | ... 16 | Heartbeat Interval = 300 seconds 17 | ... 18 | } 19 | 20 | Client{ 21 | ... 22 | Heartbeat Interval = 300 seconds 23 | ... 24 | } 25 | ```` 26 | ### Arquivo bacula-sd.conf (servidor) 27 | ```` 28 | Storage{ 29 | ... 30 | Heartbeat Interval = 300 seconds 31 | ... 32 | } 33 | ```` 34 | 35 | ### Arquivo bacula-fd.conf (cliente) 36 | ```` 37 | FileDaemon{ 38 | ... 39 | Heartbeat Interval = 300 seconds 40 | ... 41 | } 42 | ```` 43 | -------------------------------------------------------------------------------- /dicas/maximum_concurrent_jobs.md: -------------------------------------------------------------------------------- 1 | #### Maximum Concurrent Jobs = Número de Jobs Simultâneos 2 | Para ativar essa opção, deve-se incluir a opção acima nos seguintes recursos: 3 | 4 | ### Arquivo bacula-dir.conf (servidor) 5 | 6 | ```` 7 | Director{ 8 | ... 9 | Maximum Concurrent Jobs = 10 10 | ... 11 | } 12 | 13 | Storage{ 14 | ... 15 | Maximum Concurrent Jobs = 10 16 | ... 17 | } 18 | 19 | Client{ 20 | ... 21 | Maximum Concurrent Jobs = 10 22 | ... 23 | } 24 | ```` 25 | ### Arquivo bacula-sd.conf (servidor) 26 | ```` 27 | Storage{ 28 | ... 29 | Maximum Concurrent Jobs = 10 30 | ... 31 | } 32 | 33 | Device{ 34 | ... 35 | Maximum Concurrent Jobs = 10 36 | ... 37 | } 38 | 39 | ```` 40 | 41 | ### Arquivo bacula-fd.conf (cliente) 42 | ```` 43 | FileDaemon{ 44 | ... 45 | Maximum Concurrent Jobs = 10 46 | ... 47 | } 48 | ```` 49 | 50 | 51 | Fonte: http://www.bacula.org/9.0.x-manuals/en/problems/Tips_Suggestions.html#SECTION003170000000000000000 52 | -------------------------------------------------------------------------------- /dicas/mysql_sql-mode.md: -------------------------------------------------------------------------------- 1 | ### Resolver problemas de Datas no MySQL/MariaDB 2 | 3 | Se ocorrer algum erro relativo à datas durante a atualização do catálogo ou após alguma atualização do MySQL/MariaDB, pode ser que a configuração do "SQL_MODE" não está permitindo datas com valores zerados. 4 | 5 | ```` 6 | Exemplo de Erros: 7 | ERROR 1067 (42000) at line 5: Invalid default value for 'FirstWritten' 8 | ERROR 1067 (42000) at line 6: Invalid default value for 'FirstWritten' 9 | ERROR 1067 (42000) at line 7: Invalid default value for 'FirstWritten' 10 | ERROR 1067 (42000) at line 8: Invalid default value for 'FirstWritten' 11 | ERROR 1067 (42000) at line 9: Invalid default value for 'FirstWritten' 12 | ERROR 1067 (42000) at line 29: Invalid default value for 'SchedTime' 13 | ```` 14 | 15 | Para resolver isso é preciso alterar o SQL_MODE. Para isso deve-se acessar o console do MySQL/MariaDB e verificar como está configurado o "sql_mode". 16 | 17 | #### Acesse o console do MySQL 18 | ```` 19 | mysql -u root -pSUASENHA ou mysql -u root 20 | ```` 21 | 22 | #### Verificar o sql_mode 23 | ```` 24 | SELECT @@GLOBAL.sql_mode; 25 | 26 | O resultado pode variar, mas vai ser algo parecido com isso: 27 | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION 28 | ```` 29 | 30 | #### Alterar o arquivo mysql.cnf ou my.cnf ou mariadb.cnf 31 | ```` 32 | Procure o seu arquivo com extensão ".cnf". 33 | Tente procurar com o seguinte comando: 34 | grep -rn "\[mysqld\]" /etc/mysql 35 | Inclua a configuração "sql_mode" e cole a linha gerada anteriormente, 36 | removendo as opções de "NO_ZERO_IN_DATE" e "NO_ZERO_DATE" 37 | 38 | Exemplo: 39 | [mysqld] 40 | ... 41 | sql_mode = "ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" 42 | ... 43 | ```` 44 | 45 | #### Reiniciar o MySQL/MariaDB 46 | ```` 47 | /etc/init.d/mysql restart ou systemctl restart mysql.service 48 | ```` 49 | 50 | 51 | #### Verificar o sql_mode novamente 52 | ```` 53 | SELECT @@GLOBAL.sql_mode; 54 | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION 55 | 56 | Se não aparecer as opções NO_ZERO_IN_DATE e NO_ZERO_DATE é porque as configurações estão OK. 57 | ```` 58 | -------------------------------------------------------------------------------- /firebird/delete_firebird_backup.ps1: -------------------------------------------------------------------------------- 1 | ################################################################################## 2 | # Config 3 | $rootFolder = "C:\firebird" # Root folder of firebird database 4 | $backupFolder = $rootFolder + "\" + "backup" # Backup Folder 5 | $fbBackup = "database.fbk" # Backup file (.fbk) 6 | $fbLog = "database.log" # Log file (.log) 7 | 8 | # Verify if firebird dump and firebird log already exists in backup folder and exclude them 9 | $file1 = $backupFolder + "\" + $fbBackup; 10 | $file2 = $backupFolder + "\" + $fbLog; 11 | if( Test-Path $file1){ 12 | Remove-Item $file1 13 | Write-Host "Arquivo $file1 excluido com sucesso!" 14 | } 15 | if( Test-Path $file2){ 16 | Remove-Item $file2 17 | Write-Host "Arquivo $file2 excluido com sucesso!" 18 | } 19 | Exit 0 20 | -------------------------------------------------------------------------------- /firebird/delete_firebird_backup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #============================================== 4 | # Backup Database Firebird Linux 5 | # Author: Wanderlei Hüttel 6 | # Email: wanderlei.huttel@gmail.com 7 | # Version: 1.0 - 04/12/2018 8 | #============================================== 9 | 10 | 11 | #============================================== 12 | # Date/time when script starts 13 | 14 | 15 | #============================================== 16 | # Config 17 | rootFolder="/firebird" # Root folder of firebird database 18 | backupFolder="${rootFolder}/backup" # Backup Folder 19 | fbBackup="database.fbk" # Backup file (.fbk) 20 | fbLog="database.log" # Log file (.log) 21 | 22 | 23 | #============================================== 24 | # Verify if firebird dump and firebird log already exists in backup folder and exclude them 25 | file1="${backupFolder}/${fbBackup}"; 26 | file2="${backupFolder}/${fbLog}"; 27 | 28 | if [ -f ${file1} ]; then 29 | \rm ${file1} 30 | echo "Arquivo ${file1} excluido com sucesso!" 31 | fi 32 | 33 | if [ -f ${file2} ]; then 34 | \rm ${file2} 35 | echo "Arquivo ${file2} excluido com sucesso!" 36 | fi 37 | exit 0 38 | -------------------------------------------------------------------------------- /firebird/make_firebird_backup.ps1: -------------------------------------------------------------------------------- 1 | ################################################################################## 2 | # Set full path for Firebird gbak.exe 3 | Set-Alias -Name gbak -Value "C:\Program Files\Firebird\Firebird_2_5\bin\gbak.exe" 4 | 5 | ################################################################################## 6 | # Config 7 | $startDateTime = Get-Date -f "dd/MM/yyyy HH:mm:ss" # Date/time when script starts 8 | $rootFolder = "C:\firebird" # Root folder of firebird database 9 | $databaseFolder = $rootFolder + "\" + "database" # Database Folder 10 | $backupFolder = $rootFolder + "\" + "backup" # Backup Folder 11 | $fbDatabase = "database.fdb" # Database file (.fdb) 12 | $fbBackup = "database.fbk" # Backup file (.fbk) 13 | $fbLog = "database.log" # Log file (.log) 14 | $fbUser = "sysdba" # Firebird user 15 | $fbPassword = "masterkey" # Firebird password 16 | 17 | # Verify if firebird dump and firebird log already exists in backup folder and exclude them 18 | $file1 = $backupFolder + "\" + $fbBackup; 19 | $file2 = $backupFolder + "\" + $fbLog; 20 | if( Test-Path $file1){ 21 | Remove-Item $file1 22 | } 23 | if( Test-Path $file2){ 24 | Remove-Item $file2 25 | } 26 | 27 | ################################################################################## 28 | # Start firebird backup 29 | write-host "Firebird dump database started in: $startDateTime" 30 | write-host "gbak -B $databaseFolder\$fbDatabase $backupFolder\$fbBackup -Y $backupFolder\$fbLog -user $fbUser -pass $fbPassword" 31 | gbak -B $databaseFolder\$fbDatabase $backupFolder\$fbBackup -Y $backupFolder\$fbLog -user $fbUser -pass $fbPassword 32 | $endDateTime = Get-Date -f "dd/MM/yyyy HH:mm:ss" 33 | write-host "Firebird dump database finished in: $endDateTime" 34 | Exit 0 35 | -------------------------------------------------------------------------------- /firebird/make_firebird_backup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #============================================== 4 | # Backup Database Firebird Linux 5 | # Author: Wanderlei Hüttel 6 | # Email: wanderlei.huttel@gmail.com 7 | # Version: 1.0 - 04/12/2018 8 | #============================================== 9 | 10 | 11 | #============================================== 12 | # Date/time when script starts 13 | starttime=$(date +%s) 14 | 15 | 16 | #============================================== 17 | # Set full path for Firebird gbak 18 | gbak="/opt/firebird/bin/gbak" 19 | 20 | 21 | #============================================== 22 | # Config 23 | rootFolder="/firebird" # Root folder of firebird database 24 | databaseFolder="${rootFolder}/database" # Database Folder 25 | backupFolder="${rootFolder}/backup" # Backup Folder 26 | fbDatabase="database.fdb" # Database file (.fdb) 27 | fbBackup="database.fbk" # Backup file (.fbk) 28 | fbLog="database.log" # Log file (.log) 29 | fbUser="sysdba" # Firebird user 30 | fbPassword="masterkey" # Firebird password 31 | 32 | # Example of folder structure 33 | # rootFolder -| 34 | # |- databaseFolder 35 | # |- backupFolder 36 | 37 | 38 | #============================================== 39 | # Verify if firebird dump and firebird log already exists in backup folder and exclude them 40 | file1="${backupFolder}/${fbBackup}"; 41 | file2="${backupFolder}/${fbLog}"; 42 | 43 | if [ -f $file1 ]; then 44 | \rm $file1 45 | fi 46 | 47 | if [ -f $file2 ]; then 48 | \rm $file2 49 | fi 50 | 51 | 52 | #============================================== 53 | # Start firebird backup 54 | echo "gbak -B ${databaseFolder}/${fbDatabase} ${backupFolder}/${fbBackup} -Y ${backupFolder}/${fbLog} -user ${fbUser} -pass ${fbPassword}" 55 | ${gbak} -B ${databaseFolder}/${fbDatabase} ${backupFolder}/${fbBackup} -Y ${backupFolder}/${fbLog} -user ${fbUser} -pass ${fbPassword} 56 | endtime=$(date +%s) 57 | totaltime=$(expr ${endtime} - ${starttime}) 58 | echo "Firebird dump database started in: $(date -d @${starttime} +%H:%M:%S)" 59 | echo "Firebird dump database finished in: $(date -d @${endtime} +%H:%M:%S)" 60 | echo "Elapsed time: $(date -ud @${totaltime} +%H:%M:%S)" 61 | exit 0 62 | -------------------------------------------------------------------------------- /firebird/readme-english.md: -------------------------------------------------------------------------------- 1 | ## Backup Database Firebird using Bacula 2 | 3 | ### Copy files to bacula client scripts folder 4 | ``` 5 | Usually is C:\Program Files\Bacula\scripts 6 | ``` 7 | ### Configure Fileset 8 | ``` 9 | FileSet { 10 | Name = "FileSet_Firebird" 11 | Include { 12 | Options { 13 | signature = md5 14 | compression = gzip 15 | onefs = no 16 | ignorecase = yes 17 | } 18 | File = "C:/firebird/backup/database.fbk" 19 | File = "C:/firebird/backup/database.log" 20 | } 21 | } 22 | ``` 23 | ### Configure Job 24 | ``` 25 | Job { 26 | Name = "Backup_Firebird" 27 | JobDefs = "DefaultJob" 28 | Client = srv_firebird-fd 29 | FileSet= "FileSet_Firebird" 30 | Level = Full 31 | ClientRunBeforeJob = "powershell C:/'Program Files'/Bacula/scripts/make_firebird_backup.ps1" 32 | ClientRunAfterJob = "powershell C:/'Program Files'/Bacula/scripts/delete_firebird_backup.ps1" 33 | } 34 | ``` 35 | 36 | ### Configure the variables in the script and run a backup 37 | -------------------------------------------------------------------------------- /firebird/readme.md: -------------------------------------------------------------------------------- 1 | ## Backup de Banco de Dados Firebird 2 | 3 | ### Copiar os arquivos para o diretório scripts 4 | ``` 5 | Geralmente é C:\Program Files\Bacula\scripts 6 | ``` 7 | ### Configurar o Fileset 8 | ``` 9 | FileSet { 10 | Name = "FileSet_Firebird" 11 | Include { 12 | Options { 13 | signature = md5 14 | compression = gzip 15 | onefs = no 16 | ignorecase = yes 17 | } 18 | File = "C:/firebird/backup/database.fbk" 19 | File = "C:/firebird/backup/database.log" 20 | } 21 | } 22 | ``` 23 | ### Configurar o Job 24 | ``` 25 | Job { 26 | Name = "Backup_Firebird" 27 | JobDefs = "DefaultJob" 28 | Client = srv_firebird-fd 29 | FileSet= "FileSet_Firebird" 30 | Level = Full 31 | ClientRunBeforeJob = "powershell C:/'Program Files'/Bacula/scripts/make_firebird_backup.ps1" 32 | ClientRunAfterJob = "powershell C:/'Program Files'/Bacula/scripts/delete_firebird_backup.ps1" 33 | } 34 | ``` 35 | 36 | ### Configurar as variáveis do script e executar o backup 37 | -------------------------------------------------------------------------------- /hyper-v/delete_backup_virtual_machine.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanderleihuttel/bacula-utils/9e77130fea34a878d92e99431a033f4711855d26/hyper-v/delete_backup_virtual_machine.ps1 -------------------------------------------------------------------------------- /hyper-v/hyper-v_backup.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | ================================================================================================= 3 | Hot Backup Hyper-V VM's 4 | 5 | Autor: Wanderlei Hüttel 6 | wanderlei@huttel.com.br 7 | Versão 1.1 - 07/02/2019 8 | 9 | Using wbadmin.exe 10 | https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/wbadmin-start-backup 11 | ================================================================================================= 12 | #> 13 | 14 | #============ Configuration ============# 15 | # Backup Target Folder 16 | $backup_target="C:\backup_hyper-v" 17 | #$backup_target="\\server\backup_folder" 18 | 19 | 20 | # If using a local folder leave username and password empty 21 | # Username of shared folder 22 | #$username = "administrator" 23 | $username = "" 24 | 25 | 26 | # Password of shared folder 27 | #$password = "type_your_password" 28 | $password = "" 29 | #============ Configuration ============# 30 | 31 | 32 | # Get all VM's name to backup 33 | $vms = Get-VM | foreach {$_.name} 34 | $vm_name = $vms -join "," 35 | $vm_name = """$vm_name""" 36 | 37 | 38 | # If isset an argument only backup one VM 39 | if ($args.count -eq 1){ 40 | $vm_name = $args[0] 41 | $vm_name = """$vm_name""" 42 | } 43 | 44 | $App = "C:\windows\System32\wbadmin.exe" 45 | $Arg1 = "start" 46 | $Arg2 = "backup" 47 | $Arg3 = "-backuptarget:$backup_target" 48 | $Arg4 = "-hyperv:$vm_name" 49 | $Arg5 = "-vssFull" 50 | $Arg6 = "-user $username" 51 | $Arg7 = "-password $password" 52 | $Arg8 = "-quiet" 53 | 54 | if (-not($username -and $password)){ 55 | $Arg6 = "" 56 | $Arg7 = "" 57 | } 58 | $command = "$App $Arg1 $Arg2 $Arg3 $Arg4 $Arg5 $Arg6 $Arg7 $Arg8" 59 | 60 | write-host $command 61 | Invoke-Expression $command 62 | Exit 0 63 | -------------------------------------------------------------------------------- /hyper-v/make_backup_virtual_machine.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanderleihuttel/bacula-utils/9e77130fea34a878d92e99431a033f4711855d26/hyper-v/make_backup_virtual_machine.ps1 -------------------------------------------------------------------------------- /mssql/make_mssql_backup.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | O Script abaixo contempla o Backup de 'N' Databases. Testado nas versões 2008r2 e 2012r2 do Microsoft Sql Server 3 | Necessário instalar os componentes abaixo: Pesquisar pela sua versão do SQL 4 | Microsoft sql server 2008 r2 management objects 5 | Microsoft Windows PowerShell Extensions for SQL Server 2008 R2 6 | https://www.microsoft.com/en-us/download/details.aspx?id=16978 7 | Não esquecer de desbloquear a execução de scripts utilizando Set-ExecutionPolicy unrestricted -force 8 | Créditos: Victor França 9 | 10 | #> 11 | ##Add-PSSnapin sqlservercmdletsnapin100 12 | <#Variaveis: 13 | $bancos > colocar o nome de cada Database que precisa backupear. Colocar o nome de cada banco entre " " e separar por , 14 | 15 | $UserDb > Sugiro criar um usuário com permissão apenas de backupoperator em cada database pois a senha estará em um arquivo em Plain text 16 | 17 | $PassDb > Senha do banco 18 | 19 | $Sqlinstance > nome ou ip do servidor (caso seja uma instância nomeada, colocar assim: SERVIDOR/INSTANCIA) 20 | 21 | $DirBackup > Diretório local onde será armazenado o Dump de cada Banco (Ex 'c:\') 22 | 23 | $timeout > defina um timeout para a query de backup (segundos) 24 | 25 | #> 26 | $databases=@("DatabaseName1","DatabaseName2","DatabaseName3") 27 | $userDb='UserSql1' 28 | $PassDb='PassSql*' 29 | $Sqlinstance='Address/instance' 30 | $DirBackup='c:\backup_mssql' 31 | $timeout=7200 32 | 33 | Remove-Item "$DirBackup\*.bak" 34 | 35 | foreach($database in $databases){ 36 | $date=get-date -Format dd_MM_yyyy_HH_mm_ss 37 | $FileBkp=$DirBackup+$database+'_'+$date+'.bak' 38 | Write-Host "Dump da base iniciada: database ..." 39 | Invoke-Sqlcmd -User $userDb -Password $PassDb -ServerInstance $Sqlinstance -Query "BACKUP DATABASE [$database] TO DISK = '$FileBkp' WITH INIT" -timeout $timeout 40 | } 41 | -------------------------------------------------------------------------------- /mssql/readme-english.md: -------------------------------------------------------------------------------- 1 | ## Backup Database Microsoft SQL Server 2008 / 2012 using Bacula 2 | 3 | ### Copy files to bacula client scripts folder 4 | ``` 5 | Usually is C:\Program Files\Bacula\scripts 6 | ``` 7 | ### Configure Fileset 8 | ``` 9 | FileSet { 10 | Name = "FileSet_MSSQL" 11 | Include { 12 | Options { 13 | signature = md5 14 | compression = gzip 15 | onefs = no 16 | ignorecase = yes 17 | } 18 | File = "C:/backup_mssql" 19 | } 20 | } 21 | ``` 22 | ### Configure Job 23 | ``` 24 | Job { 25 | Name = "Backup_MSSQL" 26 | JobDefs = "DefaultJob" 27 | Client = srv_windows-fd 28 | FileSet= "FileSet_MSSQL" 29 | Level = Full 30 | ClientRunBeforeJob = "powershell C:/'Program Files'/Bacula/scripts/make_mssql_backup.ps1" 31 | } 32 | ``` 33 | 34 | ### Configure the variables in the script and run a backup 35 | -------------------------------------------------------------------------------- /mssql/readme.md: -------------------------------------------------------------------------------- 1 | ## Backup de Banco de Dados MSSQL Server 2008 / 2012 usando o Bacula 2 | 3 | ### Copiar os arquivos para o diretório scripts 4 | ``` 5 | Geralmente é C:\Program Files\Bacula\scripts 6 | ``` 7 | ### Configurar o Fileset 8 | ``` 9 | FileSet { 10 | Name = "FileSet_MSSQL" 11 | Include { 12 | Options { 13 | signature = md5 14 | compression = gzip 15 | onefs = no 16 | ignorecase = yes 17 | } 18 | File = "C:/backup_mssql" 19 | } 20 | } 21 | ``` 22 | ### Configurar o Job 23 | ``` 24 | Job { 25 | Name = "Backup_MSSQL" 26 | JobDefs = "DefaultJob" 27 | Client = srv_windows-fd 28 | FileSet= "FileSet_MSSQL" 29 | Level = Full 30 | ClientRunBeforeJob = "powershell C:/'Program Files'/Bacula/scripts/make_mssql_backup.ps1" 31 | } 32 | ``` 33 | 34 | ### Configurar as variáveis do script e executar o backup 35 | -------------------------------------------------------------------------------- /mysql/_backup_mysql.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Backup MySQL Databases 3 | 4 | # Directory to store backups 5 | DST=/usr/local/backup_mysql 6 | 7 | # The MySQL username and password 8 | DBUSER="root" 9 | DBPASS="" 10 | 11 | # A regex, passed to egrep -v, for which databases to ignore 12 | IGNREG='^information_schema$|^performance_schema$|^bacula$|^mysql$' 13 | 14 | # Date to create folder 15 | DATE=$(date +%Y-%m-%d) 16 | 17 | # Check if password exist 18 | if [ -n "$DBPASS" ] 19 | then 20 | PASSWD="-p$DBPASS" 21 | else 22 | PASSWD="" 23 | fi 24 | 25 | # Remove older backups 26 | cd ${DST} 27 | find ${DST} -type f -name *.sql -exec rm -f {} \; 28 | rmdir $DST/* 2>/dev/null 29 | 30 | # Create folder with the current date 31 | mkdir -p ${DST}/${DATE} 32 | 33 | # Create MySQL Backups 34 | for db in $(echo 'show databases;' | mysql --silent -u ${DBUSER} ${PASSWD} | egrep -v ${IGNREG}) ; do 35 | echo -n "Backing up ${db}... " 36 | mysqldump --opt -u ${DBUSER} $db --routines --triggers --databases --add-drop-database --complete-insert > ${DST}/${DATE}/${db}.sql 37 | echo "Done" 38 | done 39 | 40 | exit 0 41 | -------------------------------------------------------------------------------- /mysql/readme-english.md: -------------------------------------------------------------------------------- 1 | ## Backup MySQL Databases 2 | 3 | ### Copy file to bacula client scripts folder 4 | ``` 5 | Usually is /etc/bacula/scripts 6 | ``` 7 | 8 | ### Configure the variables 9 | ``` 10 | # Directory to store backups 11 | DST=/path/to/mysql/backup/folder 12 | 13 | # The MySQL username and password 14 | DBUSER="root" 15 | DBPASS="" 16 | 17 | # A regex, passed to egrep -v, for which databases to ignore 18 | IGNREG='^information_schema$|^performance_schema$|^bacula$|^mysql$' 19 | ``` 20 | 21 | ### Configure Fileset 22 | ``` 23 | FileSet { 24 | Name = "FileSet_Firebird" 25 | Include { 26 | Options { 27 | signature = md5 28 | compression = gzip 29 | onefs = no 30 | ignorecase = yes 31 | } 32 | File = "/path/to/mysql/backup/folder" 33 | } 34 | } 35 | ``` 36 | ### Configure Job 37 | ``` 38 | Job { 39 | Name = "Backup_MySQL" 40 | JobDefs = "DefaultJob" 41 | Client = srv_mysql-fd 42 | FileSet= "FileSet_MySQL" 43 | Level = Full 44 | ClientRunBeforeJob = "/etc/bacula/scripts/_backup_mysql.sh" 45 | } 46 | ``` 47 | 48 | ### Run a backup 49 | -------------------------------------------------------------------------------- /mysql/readme.md: -------------------------------------------------------------------------------- 1 | ## Backup de Banco de Dados MySQL 2 | 3 | ### Copiar o arquivo para o diretório scripts 4 | ``` 5 | Geralmente é /etc/bacula/scripts 6 | ``` 7 | 8 | ### Configurar as variáveis 9 | ``` 10 | # Diretório onde armazenar os backups 11 | DST=/path/to/mysql/backup/folder 12 | 13 | # Usuário e senha MySQL 14 | DBUSER="root" 15 | DBPASS="" 16 | 17 | # Regex, passado para o egrep -v, para ignorar os bancos de dados 18 | IGNREG='^information_schema$|^performance_schema$|^bacula$|^mysql$' 19 | ``` 20 | 21 | ### Configurar o Fileset 22 | ``` 23 | FileSet { 24 | Name = "FileSet_MySQL" 25 | Include { 26 | Options { 27 | signature = md5 28 | compression = gzip 29 | onefs = no 30 | ignorecase = yes 31 | } 32 | File = "/path/to/mysql/backup/folder" 33 | } 34 | } 35 | ``` 36 | ### Configurar o Job 37 | ``` 38 | Job { 39 | Name = "Backup_MySQL" 40 | JobDefs = "DefaultJob" 41 | Client = srv_mysql-fd 42 | FileSet= "FileSet_MySQL" 43 | Level = Full 44 | ClientRunBeforeJob = "/etc/bacula/scripts/_backup_mysql.sh" 45 | } 46 | ``` 47 | 48 | ### Executar o backup 49 | -------------------------------------------------------------------------------- /pfsense/README.md: -------------------------------------------------------------------------------- 1 | ## Backup do Firewall PFSENSE 2 | 3 | ### Copiar o arquivo para o diretório scripts 4 | ``` 5 | Geralmente é /etc/bacula/scripts 6 | ``` 7 | 8 | ### Configurar as variáveis 9 | ``` 10 | 11 | USERNAME=admin 12 | PASSWORD=pfsense 13 | PROTOCOL=http # http or https 14 | ADDRESS=$1 15 | PORT=443 16 | URL=${PROTOCOL}://${ADDRESS}:${PORT} 17 | DESTINATION=/tmp/pfsense 18 | FILENAME=config-${ADDRESS}-`date +%Y%m%d%H%M%S`.xml 19 | 20 | ``` 21 | ### Configurar o Fileset 22 | 23 | ``` 24 | FileSet { 25 | Name = "pfsense-fs" 26 | Include { 27 | Options { 28 | signature = md5 29 | compression = gzip 30 | onefs = no 31 | ignorecase = yes 32 | } 33 | File = "/tmp/pfsense" 34 | } 35 | } 36 | ``` 37 | 38 | ### Configurar o Job 39 | 40 | ``` 41 | Job { 42 | Name = "Backup_pfsense_192.168.1.1" 43 | JobDefs = "DefaultJob" 44 | Client = bacula-fd 45 | FileSet= "pfsense-fs" 46 | Level = Full 47 | RunBeforeJob = "/etc/bacula/scripts/_backup_pfsense.sh 192.168.1.1" 48 | RunAfterJob = "rm -rf /tmp/pfsense" 49 | } 50 | ``` 51 | 52 | ### Executar o backup 53 | 54 | 55 | -------------------------------------------------------------------------------- /pfsense/_backup_pfsense.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Backup PfSense 3 | # 4 | # Version 1.1 - 03/05/2020 5 | # 6 | # Working in 2.6.0-RELEASE (amd64) 7 | 8 | USERNAME=admin 9 | PASSWORD=pfsense 10 | PROTOCOL=http # http or https 11 | ADDRESS=192.168.1.254 12 | PORT=80 13 | URL=${PROTOCOL}://${ADDRESS}:${PORT} 14 | DESTINATION=/tmp/pfsense 15 | FILENAME=config-${ADDRESS}-$(date +%Y%m%d%H%M%S).xml 16 | 17 | if [[ ! -d $DESTINATION ]]; then 18 | mkdir -p $DESTINATION 19 | fi 20 | 21 | 22 | curl -s -L -k --cookie-jar cookies.txt ${URL}/ | \ 23 | grep "name='__csrf_magic'" | \ 24 | sed 's/.*value="\(.*\)".*/\1/' > csrf.txt 25 | s1=$? 26 | 27 | curl -s -L -k --cookie cookies.txt --cookie-jar cookies.txt \ 28 | --data-urlencode "login=Login" \ 29 | --data-urlencode "usernamefld=$USERNAME" \ 30 | --data-urlencode "passwordfld=$PASSWORD" \ 31 | --data-urlencode "__csrf_magic=$(cat csrf.txt)" \ 32 | ${URL}/ > /dev/null 33 | s2=$? 34 | 35 | curl -s -L -k --cookie cookies.txt --cookie-jar cookies.txt ${URL}/diag_backup.php \ 36 | | grep "name='__csrf_magic'" \ 37 | | sed 's/.*value="\(.*\)".*/\1/' > csrf.txt 38 | s3=$? 39 | 40 | curl -s -L -k --cookie cookies.txt --cookie-jar cookies.txt \ 41 | --data-urlencode "download=download" \ 42 | --data-urlencode "donotbackuprrd=yes" \ 43 | --data-urlencode "__csrf_magic=$(head -n 1 csrf.txt)" \ 44 | ${URL}/diag_backup.php > ${DESTINATION}/${FILENAME} 45 | s4=$? 46 | 47 | (( status=s1+s2+s3+s4 )) 48 | 49 | if [[ $status == 0 ]]; then 50 | echo "PfSense Backup OK $FILENAME" 51 | exit 0 52 | else 53 | echo "PfSense Backup Error $FILENAME" 54 | exit 1 55 | fi 56 | -------------------------------------------------------------------------------- /postfix/generic: -------------------------------------------------------------------------------- 1 | root@debian.local user@domain.com 2 | -------------------------------------------------------------------------------- /postfix/main.cf: -------------------------------------------------------------------------------- 1 | # See /usr/share/postfix/main.cf.dist for a commented, more complete version 2 | # Debian specific: Specifying a file name will cause the first 3 | # line of that file to be used as the name. The Debian default is /etc/mailname. 4 | 5 | smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU) 6 | biff = no 7 | 8 | # appending .domain is the MUA's job. 9 | append_dot_mydomain = no 10 | 11 | # Uncomment the next line to generate "delayed mail" warnings 12 | #delay_warning_time = 4h 13 | 14 | readme_directory = no 15 | 16 | myhostname = bacula.domain.local 17 | alias_maps = hash:/etc/aliases 18 | alias_database = hash:/etc/aliases 19 | myorigin = /etc/mailname 20 | mydestination = $myhostname localhost.$mydomain localhost $mydomain 21 | mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 22 | mailbox_command = procmail -a "$EXTENSION" 23 | mailbox_size_limit = 0 24 | recipient_delimiter = + 25 | inet_interfaces = all 26 | 27 | #SMTP relayhost 28 | relayhost = [smtp.domain.com]:587 29 | 30 | ## TLS Settings 31 | smtp_use_tls = yes 32 | smtp_tls_loglevel = 1 33 | #smtp_tls_CAfile = /etc/pki/tls/certs/ca-bundle.crt 34 | smtpd_tls_received_header = yes 35 | 36 | # configuracao tls 37 | smtp_sasl_auth_enable = yes 38 | smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd 39 | smtp_sasl_security_options = noanonymous 40 | smtp_sasl_tls_security_options = noanonymous 41 | smtp_sasl_mechanism_filter = plain 42 | 43 | #alias de mapeamento interno para externo 44 | smtp_generic_maps = hash:/etc/postfix/generic 45 | 46 | # sender-dependent sasl authentication 47 | smtp_sender_dependent_authentication = yes 48 | sender_dependent_relayhost_maps = hash:/etc/postfix/sender_relay 49 | compatibility_level = 2 50 | smtputf8_enable = no 51 | -------------------------------------------------------------------------------- /postfix/readme-english.md: -------------------------------------------------------------------------------- 1 | ## Configure Postfix to send mail using an external SMTP server 2 | 3 | 4 | ### Update and Install dependencies 5 | 6 | ``` 7 | apt-get update 8 | apt-get install postfix mailutils libsasl2-modules 9 | 10 | During the installation, a prompt will appear asking for your general type of mail configuration. 11 | - Select Internet 12 | - Type 'localhost' 13 | ``` 14 | ### Copy the files (main.cf, generic and sasl_passwd) to /etc/postfix 15 | 16 | ### Modify the file /etc/postfix/main.cf and change the following lines 17 | ``` 18 | myhostname = debian # CHANGE ME 19 | relayhost = [smtp.domain.com]:587 # CHANGE ME 20 | ``` 21 | 22 | ### Modify the file /etc/postfix/sasl_passwd with your mail credentials 23 | ``` 24 | Example: 25 | [smtp.domain.com]:587 user@domain.com:password 26 | ``` 27 | 28 | ### Modify the file /etc/postfix/generic with your generic mail rewrite 29 | ``` 30 | Example: 31 | root@debian.local user@domain.com 32 | ``` 33 | 34 | ### Create the hash db file for Postfix by running the postmap command 35 | ``` 36 | postmap /etc/postfix/sasl_passwd 37 | postmap /etc/postfix/generic 38 | ``` 39 | 40 | ### Test mail send 41 | ``` 42 | echo "OK" | mail -s "Testing mail postfix external SMTP" user@domain.com 43 | ``` 44 | -------------------------------------------------------------------------------- /postfix/readme.md: -------------------------------------------------------------------------------- 1 | ## Configurar o Postfix para enviar emails usando um servidor SMTP externo 2 | 3 | Se for utilizar uma conta do gmail, é preciso habilitar os aplicativos menos seguros. 4 | Mais detalhes no link: https://support.google.com/accounts/answer/6010255?hl=pt-BR 5 | 6 | ### Atualizar e instalar dependências 7 | 8 | ``` 9 | # Debian 10 | apt-get update 11 | apt-get install postfix mailutils libsasl2-modules 12 | 13 | Durante a instalação vai abrir um prompt perguntando qual o tipo de configuração de email: 14 | - Selecione Internet 15 | - Digite 'localhost' 16 | 17 | # CentOS 18 | yum install postfix cyrus-sasl-plain 19 | yum remove ssmtp 20 | ``` 21 | ### Copiar os arquivos (main.cf, generic, sasl_passwd e sender_relay) para /etc/postfix 22 | 23 | ### Modificar o arquivo /etc/postfix/main.cf e alterar as linhas abaixo 24 | ``` 25 | myhostname = hostname_of_machine 26 | relayhost = [smtp.domain.com]:587 27 | ``` 28 | 29 | ### Modificar o arquivo /etc/postfix/sasl_passwd com as credenciais 30 | ``` 31 | Exemplo: 32 | [smtp.domain.com]:587 sender@domain.com:password 33 | ``` 34 | 35 | ### Modificar o arquivo /etc/postfix/generic com o email genérico para reescrever 36 | ``` 37 | Exemplo: (pode conter mais de uma linha) 38 | root@hostname sender@domain.com 39 | root@hostname.local sender@domain.com 40 | ``` 41 | 42 | ### Modificar o arquivo /etc/postfix/sender_relay com o email do remetente 43 | ``` 44 | Example: 45 | sender@domain.com.br [smtp.domain.com.br]:587 46 | ``` 47 | 48 | ### Verificar o arquivo /etc/mailname e caso esteja com problemas alterar para localhost 49 | ``` 50 | Example: (only for Debian) 51 | echo "localhost" > /etc/mailname 52 | ``` 53 | 54 | ### Criar os hash's db's do Postfix com o comando postmap 55 | ``` 56 | postmap /etc/postfix/sasl_passwd 57 | postmap /etc/postfix/generic 58 | postmap /etc/postfix/sender_relay 59 | ``` 60 | 61 | ### Reiniciar o Postfix 62 | ``` 63 | systemctl restart postfix 64 | ``` 65 | 66 | ### Testar o envio de email 67 | ``` 68 | echo "OK" | mail -s "Testing mail postfix external SMTP" someemail@domain.com 69 | ``` 70 | 71 | ### Resolvendo Problemas 72 | Em caso de erro é preciso checar os logs para maiores informações: 73 | ``` 74 | No CentOS: 75 | tail -f /var/log/maillog 76 | 77 | No Debian 78 | tail -f /var/log/mail.log 79 | ``` 80 | 81 | ### Configurar o email no recurso Messages do bacula-dir.conf 82 | Alterar o mailcommand e o operatorcommand a variável que está entre "<%r> e colocar o email configurado para enviar 83 | ``` 84 | DE: mailcommand = "/usr/sbin/bsmtp -h localhost -f \"\(Bacula\) \<%r\>\" -s \"Bacula: %t %e of %c %l\" %r" 85 | PARA: mailcommand = "/usr/sbin/bsmtp -h localhost -f \"\(Bacula\) \\" -s \"Bacula: %t %e of %c %l\" %r" 86 | ``` 87 | -------------------------------------------------------------------------------- /postfix/sasl_passwd: -------------------------------------------------------------------------------- 1 | [smtp.domain.com]:587 user@domain.com:password 2 | -------------------------------------------------------------------------------- /postfix/sender_relay: -------------------------------------------------------------------------------- 1 | sender@domain.com [smtp.domain.com]:587 2 | -------------------------------------------------------------------------------- /readme-english.md: -------------------------------------------------------------------------------- 1 | ## A collect of utilities to use with bacula 2 | 3 | 4 | 5 | [Conf](/conf) - Example of bacula conf files 6 | 7 | [Convert MySQL to PostgreSQL ](/convert_mysql_to_postgresql) - Script to convert Bacula Catalog MySQL to PostgreSQL 8 | 9 | [Tips](/dicas) - Some tips to use in Bacula config 10 | 11 | [Firebird](/firebird) - Script to backup firebird databases 12 | 13 | [Hyper-V](/hyper-v) - Script to backup Hyper-V VM's using Windows Backup 14 | 15 | [MySQL](/mysql) - Script to backup MySQL databases 16 | 17 | [MSSQL](/mssql) - Script to backup SQL Server 2008/2012 databases 18 | 19 | [Pfsense](/pfsense) - Script to backup PfSense Firewall 20 | 21 | [Postfix](/postfix) - Configure Postfix to send mail using an external SMTP server 22 | 23 | [Telegram scripts](/telegram) - Scripts to send messages of jobs using telegram 24 | 25 | [Tutorial](/tutorial) - Tutorial to install Bacula, Webacula and Baculum 26 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ## Exemplos e utilidades para usar com o bacula 2 | 3 | [Conf](/conf) - Exemplo de configurações 4 | 5 | [Converter MySQL para PostgreSQL](/convert_mysql_to_postgresql) - Scripts para conversão de Banco MySQL para PostgreSQL 6 | 7 | [Dicas](/dicas) - Algumas dicas de configuração do Bacula 8 | 9 | [Firebird](/firebird) - Script para efetuar backup de banco de dados Firebird 10 | 11 | [Hyper-V](/hyper-v) - Script para efetuar backup a quente de VM Hyper-V usando Windows Backup 12 | 13 | [MySQL](/mysql) - Script para efetuar backup de banco de dados MySQL 14 | 15 | [MSSQL](/mssql) - Script para efetuar backup de banco de dados SQL Server 2008/2012 16 | 17 | [Pfsense](/pfsense) - Script para efetuar backup de Firewalls PfSense 18 | 19 | [Postfix](/postfix) - Configurar postfix para enviar email usando um servidor SMTP externo 20 | 21 | [Telegram scripts](/telegram) - Script para enviar mensagem dos jobs usando o Telegram 22 | 23 | [Tutorial](/tutorial) - Tutorial para instalar o Bacula, Webacula e Baculum 24 | 25 |

26 |
27 | Se você gostou deste repositório não esqueça de dar um like (clicando na estrela) :star: 28 |
29 | Se quiser me pagar 💰 um café ☕ ou uma cerveja 🍺: 30 |
31 | Chave PIX: Pagar um Café ou uma Cerveja 32 |
33 |
34 | Linkedin - https://www.linkedin.com/in/wanderleihuttel/ 35 | -------------------------------------------------------------------------------- /telegram/_send_telegram.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | #============================================== 4 | # Send message jobs to telegram bot 5 | # Author: Wanderlei Hüttel 6 | # Email: wanderlei.huttel@gmail.com 7 | # Version: 1.6 - 18/08/2022 8 | #============================================== 9 | 10 | 11 | # Debug Messages 12 | debug=false # false-Disable debug messages / true-Enable debug messages 13 | 14 | 15 | #============================================== 16 | # Executable config 17 | bconsole=$(which bconsole) 18 | curl=$(which curl) 19 | bc=$(which bc) 20 | 21 | 22 | # Telegram config 23 | # Use @BotFather to create a bot an get the API token 24 | # Send a message to the Bot @userinfobot to get your chat_id 25 | # Or send a message to a bot created and 26 | # Open in browser the url https://api.telegram.org/bot${api_token}/getUpdates 27 | # and get the value of id of user where the message line is. 28 | api_token="change_with_your_api_key" 29 | chat_id="change_with_your_chat_id" 30 | log="/var/log/bacula/telegram.log" 31 | 32 | 33 | #============================================== 34 | # Function to convert bytes for human readable 35 | human_bytes(){ 36 | extension="Bytes, KB, MB, GB, TB, PB, EB, ZB, YB" 37 | index=1 38 | val=$( $bc <<< "scale=2; $1 / 1") 39 | vint=$( bc <<< "$val / 1024" ) 40 | while [[ $vint != 0 ]]; do 41 | (( index++ )) 42 | val=$( $bc <<< "scale=2; $val / 1024") 43 | vint=$( $bc <<< "$val / 1024" ) 44 | done 45 | echo "$val $( cut -f $index -d, <<< $extension )" 46 | } 47 | # end function 48 | 49 | 50 | # Function do debug script 51 | message_debug(){ 52 | if [[ $debug == true ]]; then 53 | echo -ne "$1\n" 54 | fi 55 | } 56 | # end function 57 | message_debug "Debug: human_bytes '$(human_bytes 1024)'" 58 | message_debug "Debug: bconsole - '$bconsole'" 59 | message_debug "Debug: curl - '$curl'" 60 | message_debug "Debug: bc - '$bc'" 61 | message_debug "Debug: api_token - '$api_token'" 62 | message_debug "Debug: chat_id - '$chat_id'" 63 | 64 | 65 | #============================================== 66 | # SQL query to get data from Job (MySQL) 67 | query_mysql="select Job.Name, Job.JobId,(select Client.Name from Client where Client.ClientId = Job.ClientId) as Client, Job.JobBytes, Job.JobFiles, case when Job.Level = 'F' then 'Full' when Job.Level = 'I' then 'Incremental' when Job.Level = 'D' then 'Differential' end as Level, (select Pool.Name from Pool where Pool.PoolId = Job.PoolId) as Pool, (select Storage.Name from JobMedia left join Media on (Media.MediaId = JobMedia.MediaId) left join Storage on (Media.StorageId = Storage.StorageId) where JobMedia.JobId = Job.JobId limit 1 ) as Storage, date_format( Job.StartTime , '%d/%m/%Y %H:%i:%s' ) as StartTime, date_format( Job.EndTime , '%d/%m/%Y %H:%i:%s' ) as EndTime, sec_to_time(TIMESTAMPDIFF(SECOND,Job.StartTime,Job.EndTime)) as Duration, Job.JobStatus, (select Status.JobStatusLong from Status where Job.JobStatus = Status.JobStatus) as JobStatusLong from Job where Job.JobId=$1;" 68 | message_debug "Debug: query_mysql - ['$query_mysql']\n" 69 | 70 | 71 | #============================================== 72 | # SQL query to get data from Job (PostgreSQL) 73 | query_pgsql="select Job.Name, Job.JobId,(select Client.Name from Client where Client.ClientId = Job.ClientId) as Client, Job.JobBytes, Job.JobFiles, case when Job.Level = 'F' then 'Full' when Job.Level = 'I' then 'Incremental' when Job.Level = 'D' then 'Differential' end as Level, (select Pool.Name from Pool where Pool.PoolId = Job.PoolId) as Pool, (select Storage.Name from JobMedia left join Media on (Media.MediaId = JobMedia.MediaId) left join Storage on (Media.StorageId = Storage.StorageId) where JobMedia.JobId = Job.JobId limit 1 ) as Storage, to_char(Job.StartTime, 'DD/MM/YY HH24:MI:SS') as StartTime, to_char(Job.EndTime, 'DD/MM/YY HH24:MI:SS') as EndTime, to_char(endtime-starttime,'HH24:MI:SS') as Duration, Job.JobStatus, (select Status.JobStatusLong from Status where Job.JobStatus = Status.JobStatus) as JobStatusLong from Job where Job.JobId=$1;" 74 | message_debug "Debug: query_pgsql - ['$query_pgsql']\n" 75 | 76 | 77 | #============================================== 78 | # Check database driver (PostgreSQL or MySQL) 79 | check_database=$(echo "show catalog" | $bconsole | grep -oi "pgsql\|postgres\|postgresql" | wc -l) 80 | message_debug "Debug: check_database - '$check_database'" 81 | if [[ $check_database -eq 1 ]]; then 82 | sql_query=$query_pgsql 83 | message_debug "Debug: database type - 'PostgreSQL'" 84 | else 85 | sql_query=$query_mysql 86 | message_debug "Debug: database type - 'MySQL'" 87 | fi 88 | 89 | 90 | #============================================== 91 | # Execute command in bconsole 92 | str=$( $bconsole <> $log 155 | echo "$(date +%d/%m/%Y\ %H:%M:%S) - $messagelog" >> $log 156 | $curl -s "$url" > /dev/null 157 | ret=$? 158 | message_debug "Debug: ret - '$ret'" 159 | 160 | if [[ $ret -eq 0 ]]; then 161 | echo "$(date +%d/%m/%Y\ %H:%M:%S) - Attempt $count executed successfully!" >> $log 162 | message_debug "Debug: count - '$count' - Done" 163 | exit 0 164 | else 165 | echo "$(date +%d/%m/%Y\ %H:%M:%S) - Attempt $count failed!" >> $log 166 | echo "$(date +%d/%m/%Y\ %H:%M:%S) - Waiting 30 seconds before retry ..." >> $log 167 | message_debug "Debug: count - '$count'" 168 | sleep 30 169 | (( count++ )) 170 | fi 171 | 172 | done 173 | -------------------------------------------------------------------------------- /telegram/readme-english.md: -------------------------------------------------------------------------------- 1 | ## Send bacula messages using telegram: 2 | 3 | 4 | ### Create a Telegram Bot 5 | 6 | ``` 7 | Add the user @BotFather to your telegram account or access the address https://telegram.me/BotFather 8 | and follow the steps below: 9 | - /newbot - create a new bot 10 | - Type a name for your bot. Example: Bacula Test Bot 11 | - Type a username for your bot. It must end in 'bot' Example: (bacula_test_bot) 12 | 13 | Get the API KEY: 14 | 1234567890:AAFd2sDMplKGyoajsPWARnSOwa9EqHiy17U 15 | 16 | - Replace the url with your API KEY 17 | https://api.telegram.org/bot${API_TOKEN}/getUpdates 18 | https://api.telegram.org/bot1234567890:AAFd2sDMplKGyoajsPWARnSOwa9EqHiy17U/getUpdates 19 | 20 | Open in browser the URL. You will receive a JSON output, get the 'id' value. 21 | 22 | {"ok":true,"result":[{"update_id":565543449, 23 | "message":{"message_id":3,"from":{"id":123456789,"first_name":"Some Name","last_name":"Some Last Name", 24 | "username":"someusername"},"chat":{"id":123456789,"first_name":"Some Name","last_name":"Some Last Name", 25 | "username":"someuser","type":"private"},"date":1472165730,"text":"hello"}}]} 26 | 27 | Or send a message to the @userinfobot bot that it will return the value of your id 28 | 29 | ``` 30 | 31 | ### Add a RunsScript in JobDefs Resource in the file bacula-dir.conf 32 | 33 | ``` 34 | JobDefs { 35 | ... 36 | RunScript { 37 | Command = "/etc/bacula/scripts/_send_telegram.sh %i" 38 | RunsWhen = After 39 | RunsOnFailure = yes 40 | RunsOnClient = no 41 | RunsOnSuccess = yes # default, you can drop this line 42 | } 43 | } 44 | ``` 45 | 46 | ### Config dbdriver option in the Catalog Resource in the file bacula-dir.conf 47 | 48 | ``` 49 | Catalog { 50 | ... 51 | dbdriver = "mysql" or dbdriver = "pgsql" 52 | ... 53 | } 54 | 55 | ``` 56 | 57 | ### Install dependencies 58 | 59 | ``` 60 | ### Debian ### 61 | apt-get install curl bc 62 | 63 | ### CentOS ### 64 | yum -y install curl bc 65 | ``` 66 | -------------------------------------------------------------------------------- /telegram/readme.md: -------------------------------------------------------------------------------- 1 | ## Enviar mensagem do Bacula usando Telegram 2 | 3 | 4 | ### Criar um Bot no Telegram 5 | 6 | ``` 7 | Adicionar o usuário @BotFather para a sua conta do telegram ou acessar o endereço https://telegram.me/BotFather 8 | e seguir os passos abaixo: 9 | - /newbot - criar um novo bot 10 | - Digitar um nome para o bot. Exemplo: Bacula Test Bot 11 | - Digitar um nome de uusário para o bot. Precisar terminar com 'bot' Exemplo: (bacula_test_bot) 12 | - Caso queira incluir o bot em algym grupo (para mais pessoas receberem as notificações), habilite no @BotFather "Allow Groups" 13 | 14 | Anotar o token da API (API TOKEN): 15 | 1234567890:AAFd2sDMplKGyoajsPWARnSOwa9EqHiy17U 16 | 17 | Substituir na url abaixo o valor "@@API_TOKEN@@" pelo token da API 18 | https://api.telegram.org/bot@@API_TOKEN@@/getUpdates 19 | https://api.telegram.org/bot1234567890:AAFd2sDMplKGyoajsPWARnSOwa9EqHiy17U/getUpdates 20 | 21 | Enviar uma mensagem para o BOT pelo aplicativo do telegram, por exemplo "HELLO_BOT" 22 | Abrir o browser e colar a URL obtida anteriormente 23 | Você vai receber uma saída no formato JSON, pegar o valor do 'id' da linha que contém a mensagem enviada anteriomente, que no exemplo acima era "HELLO_BOT" 24 | 25 | {"ok":true,"result":[{"update_id":565543449, 26 | "message":{"message_id":3,"from":{"id":123456789,"first_name":"Some Name","last_name":"Some Last Name", 27 | "username":"someusername"},"chat":{"id":123456789,"first_name":"Some Name","last_name":"Some Last Name", 28 | "username":"someuser","type":"private"},"date":1472165730,"text":"HELLO_BOT"}}]} 29 | 30 | Ou então mande uma mensagem para o bot @userinfobot que ele vai retornar o valor de sua id 31 | 32 | Quando usar o bot em algum grupo, ao invés de mandar mensagem para o bot, mande para o grupo e pegue o id do grupo. 33 | 34 | Agora informe os valores do token da API e o id do usuário no script: 35 | api_token="change_with_your_api_key" 36 | id="change_with_your_user_id" 37 | ``` 38 | 39 | ### Incluir o parâmetro "RunsScript" na configuração do JobDefs no arquivo bacula-dir.conf 40 | 41 | ``` 42 | JobDefs { 43 | ... 44 | RunScript { 45 | Command = "/etc/bacula/scripts/_send_telegram.sh %i" 46 | RunsWhen = After 47 | RunsOnFailure = yes 48 | RunsOnClient = no 49 | RunsOnSuccess = yes # default, you can drop this line 50 | } 51 | } 52 | ``` 53 | 54 | ### Incluir o parâmetro "dbdriver" na configuração do Catálogo no arquivo bacula-dir.conf 55 | ``` 56 | Catalog { 57 | ... 58 | dbdriver = "MySQL" ou dbdriver = "PostgreSQL" 59 | ... 60 | } 61 | 62 | ``` 63 | 64 | ### Instalar dependências 65 | 66 | ``` 67 | ### Debian ### 68 | apt-get install curl bc coreutils 69 | 70 | ### CentOS ### 71 | yum -y install curl bc coreutils 72 | ``` 73 | 74 | 75 | ### Testando o script 76 | ``` 77 | Exemplo: /etc/bacula/scripts/_send_telegram.sh 78 | /etc/bacula/scripts/_send_telegram.sh 123 79 | ``` 80 | 81 | 82 | ### Solucionando problemas 83 | Habilitando no script o modo debug (**debug=1**), é possível verificar possíveis erros. 84 | -------------------------------------------------------------------------------- /tutorial/bacula_install_centos7.txt: -------------------------------------------------------------------------------- 1 | ##################################################################################### 2 | # Passos para Instalação do Bacula via Compilação em CentOS 7 # 3 | # MySQL e PostgreSQL # 4 | # Autor: Wanderlei Hüttel # 5 | # Data atualização: 09/05/2018 # 6 | ##################################################################################### 7 | * Leia tudo antes de começar a instalar só depois inicie a instalação. 8 | * Se você possuir algum erro, revise todo tutorial novamente e verifique se não 9 | esqueceu nenhum passo. 10 | * Este tutorial foi testado em uma instalação nova em CentOS-7-Minimal-x86_64 11 | 12 | +-----------------------------------------------------------------------------------+ 13 | | >>> Desabilitar Selinux <<< | 14 | +-----------------------------------------------------------------------------------+ 15 | setenforce Permissive 16 | sed -i "s/enforcing/disabled/g" /etc/selinux/config 17 | sed -i "s/enforcing/disabled/g" /etc/sysconfig/selinux 18 | 19 | 20 | +-----------------------------------------------------------------------------------+ 21 | | >>> Liberar portas no Firewall <<< | 22 | +-----------------------------------------------------------------------------------+ 23 | firewall-cmd --permanent --zone=public --add-port=9101-9103/tcp 24 | service firewalld restart 25 | 26 | 27 | +-----------------------------------------------------------------------------------+ 28 | | >>> Instalar repositório epel <<< | 29 | +-----------------------------------------------------------------------------------+ 30 | * Executar 2 vezes 31 | yum install epel-release 32 | yum install epel-release 33 | 34 | 35 | +-----------------------------------------------------------------------------------+ 36 | | >>> Atualizar a lista dos pacotes <<< | 37 | +-----------------------------------------------------------------------------------+ 38 | yum update 39 | 40 | 41 | +-----------------------------------------------------------------------------------+ 42 | | >>> Pacotes necessários para compilação padrão <<< | 43 | +-----------------------------------------------------------------------------------+ 44 | yum install vim make gcc gcc-c++ openssl-devel perl mc mtx readline-devel \ 45 | lzop lzo lzo-dev zlib-deve sudo gawk gdb libacl-devel lsscsi deltarpm wget 46 | 47 | 48 | +-----------------------------------------------------------------------------------+ 49 | | >>> Configurações vim e bashrc <<< (OPCIONAL) | 50 | +-----------------------------------------------------------------------------------+ 51 | # Editor vim colorido e desabilitar modo visual do VIM 52 | echo "syntax on 53 | :highlight comment ctermfg=lightblue 54 | set mouse-=a 55 | " >> $HOME/.vimrc 56 | 57 | 58 | +-----------------------------------------------------------------------------------+ 59 | | >>> Pacotes necessários para habilitar o BAT <<< | 60 | +-----------------------------------------------------------------------------------+ 61 | apt-get install qt4-dev-tools qt4-qtconfig libqt4-dev libqwt5-qt4 \ 62 | libqwt5-qt4-dev pkg-config 63 | * Incluir no comando de compilação a opção --enable-bat 64 | 65 | 66 | +-----------------------------------------------------------------------------------+ 67 | | >>> Pacotes necessários para utilizar o banco de dados MySQL <<< | 68 | +-----------------------------------------------------------------------------------+ 69 | Por padrão o CentOS 7 não instala mais o MySQL, mas sim o MariaDB. 70 | Então, caso queira habilitar o MySQL siga os passos abaixo: 71 | 72 | *Acessar o repositório oficial em https://dev.mysql.com/downloads/repo/yum/ e instalar 73 | o pacote mais atual: 74 | - Verifique se o link não foi alterado: 75 | rpm -ivh https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm 76 | 77 | * Instalar o MySQL 78 | yum install mysql-community-server mysql-community-devel 79 | 80 | * Habilitar o MySQL 81 | systemctl enable mysqld 82 | 83 | * Iniciar o MySQL 84 | systemctl start mysqld 85 | 86 | * O MySQL gera uma senha temporária, então para acessar utilize o comando abaixo: 87 | mysql -u root -p`grep 'temporary password' /var/log/mysqld.log | sed 's/.*:\s//g'` 88 | 89 | * O MySQL vem com um plugin de validação de senha, para remover ele é precisao executar 90 | os comandos abaixo no console do MySQL: 91 | 92 | * Alterar a senha para uma senha com uma certa segurança: 93 | SET PASSWORD FOR 'root'@'localhost' = PASSWORD('B@cula2018'); 94 | 95 | * Desinstalar o plugin de validação de senha: 96 | uninstall plugin validate_password; 97 | 98 | * Alterar a senha novamente para uma senha de sua preferência: 99 | SET PASSWORD FOR 'root'@'localhost' = PASSWORD(''); 100 | 101 | 102 | +-----------------------------------------------------------------------------------+ 103 | | >>> Pacotes necessários para utilizar o banco de dados MariaDB <<< | 104 | +-----------------------------------------------------------------------------------+ 105 | * Cuidado com senhas com caractes especiais, pois podem apresentar problemas na 106 | criação dos scripts. Se for uma instalação fresca, prefira deixar a senha em branco. 107 | 108 | *Lembrando que o MariaDB não é homolagago pelo Bacula, porém funciona. 109 | yum install mariadb-server mariadb-devel mariadb-libs 110 | 111 | * Habilitar o MariaDB 112 | systemctl enable mariadb.service 113 | 114 | * Iniciar o MariaDB 115 | systemctl start mariadb.service 116 | 117 | 118 | +-----------------------------------------------------------------------------------+ 119 | | >>> Pacotes para utilizar o banco de dados PostgreSQL <<< | 120 | +-----------------------------------------------------------------------------------+ 121 | yum install postgresql postgresql-server postgresql-contrib postgresql-devel 122 | 123 | 124 | +-----------------------------------------------------------------------------------+ 125 | | >>> Baixando e Compilando o Fonte <<< | 126 | +-----------------------------------------------------------------------------------+ 127 | cd /usr/src 128 | *Utilizando wget 129 | wget --no-check-certificate https://sourceforge.net/projects/bacula/files/bacula/9.0.6/bacula-9.0.6.tar.gz 130 | tar xvzf bacula-9.0.6.tar.gz 131 | cd bacula-9.0.6 132 | 133 | *Utilizando git (sempre pega a versão mais recente, porém as vezes pode conter alguns bugs) 134 | git clone -b Branch-9.0 http://git.bacula.org/bacula.git bacula 135 | 136 | cd /usr/src/bacula/bacula 137 | 138 | 139 | ******************************************************************************************************** 140 | * * 141 | * Nessa parte abaixo é preciso definir o banco de dados que será utilizado MySQL/MariaDB ou PostgreSQL * 142 | * Utilize os comandos de acordo com o banco escolhido. * 143 | * * 144 | ******************************************************************************************************** 145 | 146 | * Comando de pré-compilação para MySQL/MariaDB 147 | ./configure \ 148 | --enable-smartalloc \ 149 | --with-mysql \ 150 | --with-db-user=bacula \ 151 | --with-db-password=bacula \ 152 | --with-db-port=3306 \ 153 | --with-openssl \ 154 | --with-readline=/usr/include/readline \ 155 | --sysconfdir=/etc/bacula \ 156 | --bindir=/usr/bin \ 157 | --sbindir=/usr/sbin \ 158 | --with-scriptdir=/etc/bacula/scripts \ 159 | --with-plugindir=/etc/bacula/plugins \ 160 | --with-pid-dir=/var/run \ 161 | --with-subsys-dir=/etc/bacula/working \ 162 | --with-working-dir=/etc/bacula/working \ 163 | --with-bsrdir=/etc/bacula/bootstrap \ 164 | --with-systemd \ 165 | --disable-conio \ 166 | --disable-nls \ 167 | --with-logdir=/var/log/bacula \ 168 | --with-dump-email=email@dominio.com.br \ 169 | --with-job-email=email@dominio.com.br 170 | 171 | * Comando de pré-compilação para PostgreSQL 172 | ./configure \ 173 | --enable-smartalloc \ 174 | --with-postgresql \ 175 | --with-db-user=bacula \ 176 | --with-db-password=bacula \ 177 | --with-db-port=5432 \ 178 | --with-openssl \ 179 | --with-readline=/usr/include/readline \ 180 | --sysconfdir=/etc/bacula \ 181 | --bindir=/usr/bin \ 182 | --sbindir=/usr/sbin \ 183 | --with-scriptdir=/etc/bacula/scripts \ 184 | --with-plugindir=/etc/bacula/plugins \ 185 | --with-pid-dir=/var/run \ 186 | --with-subsys-dir=/etc/bacula/working \ 187 | --with-working-dir=/etc/bacula/working \ 188 | --with-bsrdir=/etc/bacula/bootstrap \ 189 | --with-systemd \ 190 | --disable-conio \ 191 | --disable-nls \ 192 | --with-logdir=/var/log/bacula \ 193 | --with-dump-email=email@dominio.com.br \ 194 | --with-job-email=email@dominio.com.br 195 | 196 | *Comando para efetuar a compilação e instalação 197 | make -j 8 198 | make install 199 | make install-autostart 200 | 201 | 202 | ***************************************************************************************************** 203 | * * 204 | * Passos para criação do banco de dados, usuários e permisssões MySQL/MariaDB * 205 | * * 206 | ***************************************************************************************************** 207 | 208 | +-----------------------------------------------------------------------------------+ 209 | | >>> Configurar os usuários no MySQL/MariaDB <<< | 210 | +-----------------------------------------------------------------------------------+ 211 | *Caso você não tenha definido uma senha: 212 | mysql -u root 213 | 214 | *Caso tenha definido uma senha 215 | mysql -u root -p 216 | 217 | GRANT ALL ON *.* TO 'root'@'localhost'; 218 | CREATE USER bacula; 219 | GRANT ALL ON *.* TO 'bacula'@'localhost' IDENTIFIED BY 'bacula' WITH GRANT OPTION; 220 | GRANT SELECT ON mysql.proc TO 'bacula'; 221 | FLUSH PRIVILEGES; 222 | quit 223 | systemctl restart mariadb.service 224 | 225 | 226 | +-----------------------------------------------------------------------------------+ 227 | | >>> Criar as tabelas do bacula no MySQL/MariaDB <<< | 228 | +-----------------------------------------------------------------------------------+ 229 | cd /etc/bacula/scripts 230 | * Caso não tenha definido uma senha 231 | ./create_mysql_database 232 | ./make_mysql_tables 233 | ./grant_mysql_privileges 234 | 235 | * Caso não tenha definido uma senha 236 | ./create_mysql_database -u root -p 237 | ./make_mysql_tables -u root -p 238 | ./grant_mysql_privileges -u root -p 239 | 240 | 241 | ***************************************************************************************************** 242 | * * 243 | * Passos para criação do banco de dados, usuários e permisssões PostgreSQL * 244 | * * 245 | ***************************************************************************************************** 246 | +-----------------------------------------------------------------------------------+ 247 | | >>> Iniciando e definindo a senha do usuário bacula no PostgreSQL <<< | 248 | +-----------------------------------------------------------------------------------+ 249 | * Iniciar banco de dados PostgreSQL 250 | postgresql-setup initdb 251 | systemctl start postgresql 252 | su postgres 253 | psql 254 | create user bacula; 255 | alter user bacula with password 'bacula'; 256 | \q 257 | exit 258 | 259 | 260 | +-----------------------------------------------------------------------------------+ 261 | | >>> Criar as tabelas do bacula no PostgreSQL <<< | 262 | +-----------------------------------------------------------------------------------+ 263 | chmod 775 /etc/bacula 264 | cd /etc/bacula/scripts 265 | chown postgres create_postgresql_database && chown postgres make_postgresql_tables && \ 266 | chown postgres grant_postgresql_privileges && chown postgres drop_postgresql_database && \ 267 | chown postgres update_postgresql_tables 268 | su postgres 269 | ./create_postgresql_database 270 | ./make_postgresql_tables 271 | ./grant_postgresql_privileges 272 | exit 273 | 274 | 275 | +-----------------------------------------------------------------------------------+ 276 | | >>> Configurar o acesso ao PostgreSQL pelo bacula <<< | 277 | +-----------------------------------------------------------------------------------+ 278 | Editar o arquivo /var/lib/pgsql/data/postgresql.conf e alterar a linha abaixo: 279 | de: # listen_addresses = 'localhost' 280 | para: listen_addresses = '*' 281 | 282 | Editar o arquivo /var/lib/pgsql/data/pg_hba.conf e alterar a seguinte linha: 283 | de: local all all peer 284 | para: local all all md5 285 | 286 | *Reiniciar o PostgreSQL 287 | systemctl start postgresql 288 | 289 | 290 | +-----------------------------------------------------------------------------------+ 291 | | >>> Iniciar o bacula <<< | 292 | +-----------------------------------------------------------------------------------+ 293 | bacula start 294 | Se tudo ocorrer bem, o bacula iniciará sem problemas e você pode acessar com o bconsole, 295 | e verá uma tela conforme abaixo 296 | 297 | root@bacula:/# bconsole 298 | Connecting to Director centos7:9101 299 | 1000 OK: 103 centos7-dir Version: 9.0.6 (20 November 2017) 300 | Enter a period to cancel a command. 301 | * 302 | -------------------------------------------------------------------------------- /tutorial/bacula_install_debian10.txt: -------------------------------------------------------------------------------- 1 | ##################################################################################### 2 | # Passos para Instalação do Bacula via Compilação em Debian 10 (buster) # 3 | # MySQL/MariaDB e PostgreSQL # 4 | # Autor: Wanderlei Hüttel # 5 | # Email: wanderlei.huttel at gmail.com # 6 | # Data atualização: 09/06/2021 # 7 | ##################################################################################### 8 | * Leia tudo antes de começar a instalar só depois inicie a instalação. 9 | * Se você possuir algum erro, revise todo tutorial novamente e verifique se não 10 | esqueceu nenhum passo. 11 | * Este tutorial foi testado em Debian 10 (buster) em 09/06/2020 12 | 13 | ===================================================================================== 14 | >>> Atualizar a lista dos pacotes <<< 15 | ===================================================================================== 16 | apt-get update 17 | 18 | 19 | ===================================================================================== 20 | >>> Pacotes necessários para compilação padrão <<< 21 | ===================================================================================== 22 | apt-get install vim make gcc build-essential perl unp mc mtx libreadline7 \ 23 | libreadline5-dbg libreadline-gplv2-dev zlib1g-dev lzop liblzo2-dev python-lzo sudo \ 24 | gawk gdb libacl1 libacl1-dev libssl-dev lsscsi apt-transport-https 25 | 26 | 27 | ===================================================================================== 28 | >>> Pacotes necessários para compilação dos drivers cloud S3 <<< 29 | ===================================================================================== 30 | apt-get install libxml2-dev libcurl4-openssl-dev 31 | 32 | 33 | ===================================================================================== 34 | >>> Configurações vim e bashrc <<< (OPCIONAL) 35 | ===================================================================================== 36 | Digitar o comando abaixo no terminal e selecionar a opção que contém "/usr/bin/vim.basic", 37 | digitando o respectivo número. 38 | update-alternatives --config editor 39 | 40 | 41 | # Desabilitar modo visual do VIM/Editor Colorido 42 | # Incluir as seguintes linhas no arquivo acima 43 | vim ~/.vimrc 44 | set mouse-=a 45 | syntax on 46 | :highlight comment ctermfg=lightblue 47 | 48 | 49 | # Habilitar modo colorido no bash 50 | vim /root/.bashrc 51 | export LS_OPTIONS='--color=auto' 52 | eval "`dircolors`" 53 | alias ls='ls $LS_OPTIONS' 54 | alias ll='ls $LS_OPTIONS -l' 55 | alias l='ls $LS_OPTIONS -lA' 56 | alias rm='rm -i' 57 | alias cp='cp -i' 58 | alias mv='mv -i' 59 | alias cls=clear 60 | 61 | # Recarregar o profile 62 | . ~/.profile 63 | 64 | 65 | ===================================================================================== 66 | >>> Pacotes necessários para habilitar o BAT <<< 67 | ===================================================================================== 68 | apt-get install qt4-dev-tools qt4-qtconfig libqt4-dev libqwt5-qt4 \ 69 | libqwt5-qt4-dev pkg-config 70 | * Incluir no comando de compilação a opção --enable-bat 71 | 72 | 73 | ===================================================================================== 74 | >>> Pacotes necessários para utilizar o banco de dados MySQL <<< 75 | ===================================================================================== 76 | Por padrão no Debian >= 9 não instala mais o MySQL, mas sim o MariaDB. 77 | Então, caso queira habilitar o MySQL siga os passos abaixo: 78 | 79 | *Adicionar a chave pública como confiável: 80 | wget -O /tmp/RPM-GPG-KEY-mysql https://repo.mysql.com/RPM-GPG-KEY-mysql --no-check-certificate 81 | apt-key add /tmp/RPM-GPG-KEY-mysql 82 | 83 | *Habilitar os seguintes repositórios em /etc/apt/sources.list.d 84 | echo "deb http://repo.mysql.com/apt/debian/ buster mysql-apt-config 85 | deb http://repo.mysql.com/apt/debian/ buster mysql-5.7 86 | deb http://repo.mysql.com/apt/debian/ buster mysql-tools 87 | deb http://repo.mysql.com/apt/debian/ buster mysql-tools-preview 88 | deb-src http://repo.mysql.com/apt/debian/ buster mysql-5.7" > /etc/apt/sources.list.d/mysql.list 89 | 90 | apt-get update 91 | apt-get install mysql-community-server libmysqlclient-dev 92 | 93 | 94 | ===================================================================================== 95 | >>> Pacotes necessários para utilizar o banco de dados MariaDB <<< 96 | ===================================================================================== 97 | * Cuidado com senhas com caractes especiais, pois podem apresentar problemas na 98 | criação dos scripts. Se for uma instalação fresca, prefira deixar a senha em branco. 99 | 100 | *Lembrando que o MariaDB não é homologado pelo Bacula, porém funciona. 101 | apt-get install mariadb-server libmariadbd-dev libmariadbclient-dev \ 102 | libmariadbclient-dev-compat 103 | 104 | 105 | ===================================================================================== 106 | >>> Pacotes para utilizar o banco de dados PostgreSQL <<< 107 | ===================================================================================== 108 | apt-get install postgresql-11 postgresql-contrib-11 postgresql-client-11 \ 109 | postgresql-server-dev-11 110 | 111 | 112 | ===================================================================================== 113 | >>> Baixando e Compilando o Fonte para usar os drivers Cloud S3 <<< 114 | ===================================================================================== 115 | cd /usr/src 116 | wget -c https://www.bacula.org/downloads/libs3-20200523.tar.gz 117 | tar xvzf libs3-20200523.tar.gz 118 | cd /usr/src/libs3-20200523 119 | DESTDIR=/usr/local make clean 120 | DESTDIR=/usr/local make 121 | DESTDIR=/usr/local make install 122 | 123 | # Refazer os caches das libraries 124 | rm /etc/ld.so.cache 125 | sudo ldconfig 126 | 127 | Se tudo ocorrer bem o comando "s3" vai funcionar no terminal 128 | s3 129 | 130 | ===================================================================================== 131 | >>> Baixando e Compilando o Fonte <<< 132 | ===================================================================================== 133 | cd /usr/src 134 | *Utilizando wget 135 | wget --no-check-certificate https://sourceforge.net/projects/bacula/files/bacula/11.0.5/bacula-11.0.5.tar.gz 136 | tar xvzf bacula-11.0.5.tar.gz 137 | cd bacula-11.0.5 138 | 139 | *Utilizando git (sempre busca a versão mais recente, porém as vezes pode conter alguns bugs) 140 | apt-get install git 141 | git clone -b Branch-11.0 http://git.bacula.org/bacula.git bacula 142 | cd /usr/src/bacula/bacula 143 | 144 | ######################################################################################################## 145 | # # 146 | # Nessa parte abaixo é preciso definir o banco de dados que será utilizado MySQL/MariaDB ou PostgreSQL # 147 | # Utilize os comandos de acordo com o banco escolhido. # 148 | # Caso tenha problemas durante a compilação com o OpenSSL no Debian versão 9.x, compile sem o # 149 | # OpenSSL-1.1, então não habilitamos * # 150 | # --without-openssl # 151 | # # 152 | ######################################################################################################## 153 | 154 | * Comando de pré-compilação para MySQL/MariaDB 155 | ./configure \ 156 | --enable-smartalloc \ 157 | --with-mysql \ 158 | --with-db-user=bacula \ 159 | --with-db-password=bacula \ 160 | --with-db-port=3306 \ 161 | --with-openssl \ 162 | --with-readline=/usr/include/readline \ 163 | --sysconfdir=/etc/bacula \ 164 | --bindir=/usr/bin \ 165 | --sbindir=/usr/sbin \ 166 | --with-scriptdir=/etc/bacula/scripts \ 167 | --with-plugindir=/etc/bacula/plugins \ 168 | --with-pid-dir=/var/run \ 169 | --with-subsys-dir=/etc/bacula/working \ 170 | --with-working-dir=/etc/bacula/working \ 171 | --with-bsrdir=/etc/bacula/bootstrap \ 172 | --with-s3=/usr/local \ 173 | --with-basename=bacula \ 174 | --with-hostname=XXX_IP_SERVIDOR_BACULA_XXX \ 175 | --with-systemd \ 176 | --disable-conio \ 177 | --disable-nls \ 178 | --with-logdir=/var/log/bacula \ 179 | --with-dump-email=email@dominio.com.br \ 180 | --with-job-email=email@dominio.com.br 181 | 182 | * Comando de pré-compilação para PostgreSQL 183 | ./configure \ 184 | --enable-smartalloc \ 185 | --with-postgresql \ 186 | --with-db-user=bacula \ 187 | --with-db-password=bacula \ 188 | --with-db-port=5432 \ 189 | --with-openssl \ 190 | --with-readline=/usr/include/readline \ 191 | --sysconfdir=/etc/bacula \ 192 | --bindir=/usr/bin \ 193 | --sbindir=/usr/sbin \ 194 | --with-scriptdir=/etc/bacula/scripts \ 195 | --with-plugindir=/etc/bacula/plugins \ 196 | --with-pid-dir=/var/run \ 197 | --with-subsys-dir=/etc/bacula/working \ 198 | --with-working-dir=/etc/bacula/working \ 199 | --with-bsrdir=/etc/bacula/bootstrap \ 200 | --with-s3=/usr/local \ 201 | --with-basename=bacula \ 202 | --with-hostname=XXX_IP_SERVIDOR_BACULA_XXX \ 203 | --with-systemd \ 204 | --disable-conio \ 205 | --disable-nls \ 206 | --with-logdir=/var/log/bacula \ 207 | --with-dump-email=email@dominio.com.br \ 208 | --with-job-email=email@dominio.com.br 209 | 210 | *Comando para efetuar a compilação e instalação 211 | make -j 8 212 | make install 213 | make install-autostart 214 | 215 | 216 | ######################################################################################################## 217 | # # 218 | # Passos para criação do banco de dados, usuários e permisssões MySQL/MariaDB # 219 | # # 220 | ######################################################################################################## 221 | 222 | ===================================================================================== 223 | >>> Configurar os usuários no MySQL/MariaDB <<< 224 | ===================================================================================== 225 | *Caso você não tenha definido uma senha: 226 | mysql -u root 227 | 228 | *Caso tenha definido uma senha 229 | mysql -u root -p 230 | 231 | GRANT ALL ON *.* TO 'root'@'localhost'; 232 | CREATE USER bacula; 233 | GRANT ALL ON *.* TO 'bacula'@'localhost' IDENTIFIED BY 'bacula' WITH GRANT OPTION; 234 | GRANT SELECT ON mysql.proc TO 'bacula'; 235 | FLUSH PRIVILEGES; 236 | QUIT 237 | systemctl restart mysql 238 | 239 | 240 | ===================================================================================== 241 | >>> Criar as tabelas do bacula no MySQL/MariaDB <<< 242 | ===================================================================================== 243 | chmod 775 /etc/bacula 244 | cd /etc/bacula/scripts 245 | * Caso não tenha definido uma senha 246 | /etc/bacula/scripts/create_mysql_database 247 | /etc/bacula/scripts/make_mysql_tables 248 | /etc/bacula/scripts/grant_mysql_privileges 249 | 250 | * Caso não tenha definido uma senha 251 | /etc/bacula/scripts/create_mysql_database -u root -p 252 | /etc/bacula/scripts/make_mysql_tables -u root -p 253 | /etc/bacula/scripts/grant_mysql_privileges -u root -p 254 | 255 | 256 | ######################################################################################################## 257 | # # 258 | # Passos para criação do banco de dados, usuários e permisssões PostgreSQL # 259 | # # 260 | ######################################################################################################## 261 | 262 | 263 | ===================================================================================== 264 | >>> Criar as tabelas do bacula no PostgreSQL <<< 265 | ===================================================================================== 266 | chmod 775 /etc/bacula 267 | cd /etc/bacula/scripts 268 | chown postgres create_postgresql_database && chown postgres make_postgresql_tables && \ 269 | chown postgres grant_postgresql_privileges && chown postgres drop_postgresql_database && \ 270 | chown postgres update_postgresql_tables 271 | su postgres 272 | /etc/bacula/scripts/create_postgresql_database 273 | /etc/bacula/scripts/make_postgresql_tables 274 | /etc/bacula/scripts/grant_postgresql_privileges 275 | exit 276 | 277 | 278 | ===================================================================================== 279 | >>> Definindo a senha do usuário bacula no PostgreSQL <<< 280 | ===================================================================================== 281 | su postgres 282 | psql 283 | alter user bacula with password 'bacula'; 284 | \q 285 | exit 286 | 287 | 288 | ===================================================================================== 289 | >>> Configurar o acesso ao PostgreSQL pelo bacula <<< 290 | ===================================================================================== 291 | Backup dos arquivos de configuração: 292 | \cp /etc/postgresql/11/main/postgresql.conf /etc/postgresql/11/main/postgresql.conf.default 293 | \cp /etc/postgresql/11/main/pg_hba.conf /etc/postgresql/11/main/pg_hba.conf.default 294 | 295 | Editar o arquivo /etc/postgresql/11/main/postgresql.conf e alterar a linha abaixo: 296 | de: # listen_addresses = 'localhost' 297 | para: listen_addresses = '*' 298 | 299 | Editar o arquivo /etc/postgresql/11/main/pg_hba.conf e alterar a seguinte linha: 300 | de: local all all peer 301 | para: local all all md5 302 | 303 | *Reiniciar o PostgreSQL 304 | systemctl restart postgresql 305 | 306 | 307 | ===================================================================================== 308 | >>> Iniciar o bacula <<< 309 | ===================================================================================== 310 | bacula start 311 | Se tudo ocorrer bem, o bacula iniciará sem problemas e você pode acessar com o bconsole, 312 | e verá uma tela conforme abaixo 313 | 314 | root@bacula:/# bconsole 315 | root@debian:/etc/bacula/scripts# bconsole 316 | Connecting to Director 192.168.1.1:9101 317 | 1000 OK: 103 bacula-dir Version: 11.0.5 (03 June 2021) 318 | Enter a period to cancel a command. 319 | * 320 | -------------------------------------------------------------------------------- /tutorial/bacula_install_debian9.txt: -------------------------------------------------------------------------------- 1 | ##################################################################################### 2 | # Passos para Instalação do Bacula via Compilação em Debian 9.X # 3 | # MySQL e PostgreSQL # 4 | # Autor: Wanderlei Hüttel # 5 | # Data atualização: 19/11/2018 # 6 | ##################################################################################### 7 | * Leia tudo antes de começar a instalar só depois inicie a instalação. 8 | * Se você possuir algum erro, revise todo tutorial novamente e verifique se não 9 | esqueceu nenhum passo. 10 | * Este tutorial foi testado em Debian 9.6 em 19/11/2018 11 | 12 | +-----------------------------------------------------------------------------------+ 13 | | >>> Atualizar a lista dos pacotes <<< | 14 | +-----------------------------------------------------------------------------------+ 15 | apt-get update 16 | 17 | 18 | +-----------------------------------------------------------------------------------+ 19 | | >>> Pacotes necessários para compilação padrão <<< | 20 | +-----------------------------------------------------------------------------------+ 21 | apt-get install vim make gcc build-essential perl unp mc mtx libreadline7 \ 22 | libreadline7-dbg libreadline-gplv2-dev zlib1g-dev lzop liblzo2-dev python-lzo sudo \ 23 | gawk gdb libacl1 libacl1-dev libssl-dev lsscsi apt-transport-https 24 | 25 | 26 | +-----------------------------------------------------------------------------------+ 27 | | >>> Configurações vim e bashrc <<< (OPCIONAL) | 28 | +-----------------------------------------------------------------------------------+ 29 | Digitar o comando abaixo no terminal e selecionar a opção que contém "/usr/bin/vim.basic", 30 | digitando o respectivo número. 31 | update-alternatives --config editor 32 | 33 | # Editor vim colorido 34 | vim /etc/vim/vimrc 35 | incluir as seguintes linhas no arquivo acima 36 | syntax on 37 | :highlight comment ctermfg=lightblue 38 | 39 | # Desabilitar modo visual do VIM 40 | vim ~/.vimrc 41 | set mouse-=a 42 | 43 | # Habilitar modo colorido no bash 44 | vim /root/.bashrc 45 | export LS_OPTIONS='--color=auto' 46 | eval "`dircolors`" 47 | alias ls='ls $LS_OPTIONS' 48 | alias ll='ls $LS_OPTIONS -l' 49 | alias l='ls $LS_OPTIONS -lA' 50 | alias rm='rm -i' 51 | alias cp='cp -i' 52 | alias mv='mv -i' 53 | alias cls=clear 54 | 55 | # Recarregar o profile 56 | . ~/.profile 57 | 58 | 59 | +-----------------------------------------------------------------------------------+ 60 | | >>> Pacotes necessários para habilitar o BAT <<< | 61 | +-----------------------------------------------------------------------------------+ 62 | apt-get install qt4-dev-tools qt4-qtconfig libqt4-dev libqwt5-qt4 \ 63 | libqwt5-qt4-dev pkg-config 64 | * Incluir no comando de compilação a opção --enable-bat 65 | 66 | 67 | +-----------------------------------------------------------------------------------+ 68 | | >>> Pacotes necessários para utilizar o banco de dados MySQL <<< | 69 | +-----------------------------------------------------------------------------------+ 70 | Por padrão o Debian 9 não instala mais o MySQL, mas sim o MariaDB. 71 | Então, caso queira habilitar o MySQL siga os passos abaixo: 72 | 73 | *Adicionar a chave pública como confiável: 74 | wget -O /tmp/RPM-GPG-KEY-mysql https://repo.mysql.com/RPM-GPG-KEY-mysql --no-check-certificate 75 | apt-key add /tmp/RPM-GPG-KEY-mysql 76 | 77 | *Habilitar os seguintes repositórios em /etc/apt/sources.list.d 78 | echo "deb http://repo.mysql.com/apt/debian/ stretch mysql-apt-config 79 | deb http://repo.mysql.com/apt/debian/ stretch mysql-5.7 80 | deb http://repo.mysql.com/apt/debian/ stretch mysql-tools 81 | deb http://repo.mysql.com/apt/debian/ stretch mysql-tools-preview 82 | deb-src http://repo.mysql.com/apt/debian/ stretch mysql-5.7" > /etc/apt/sources.list.d/mysql.list 83 | 84 | apt-get update 85 | apt-get install mysql-community-server libmysqlclient-dev 86 | 87 | 88 | +-----------------------------------------------------------------------------------+ 89 | | >>> Pacotes necessários para utilizar o banco de dados MariaDB <<< | 90 | +-----------------------------------------------------------------------------------+ 91 | * Cuidado com senhas com caractes especiais, pois podem apresentar problemas na 92 | criação dos scripts. Se for uma instalação fresca, prefira deixar a senha em branco. 93 | 94 | *Lembrando que o MariaDB não é homologado pelo Bacula, porém funciona. 95 | apt-get install mariadb-server libmariadbd-dev libmariadbclient-dev \ 96 | libmariadbclient-dev-compat 97 | 98 | 99 | +-----------------------------------------------------------------------------------+ 100 | | >>> Pacotes para utilizar o banco de dados PostgreSQL <<< | 101 | +-----------------------------------------------------------------------------------+ 102 | apt-get install postgresql-9.6 postgresql-contrib-9.6 postgresql-client-9.6 \ 103 | postgresql-server-dev-9.6 104 | 105 | 106 | +-----------------------------------------------------------------------------------+ 107 | | >>> Baixando e Compilando o Fonte <<< | 108 | +-----------------------------------------------------------------------------------+ 109 | cd /usr/src 110 | *Utilizando wget 111 | wget --no-check-certificate https://sourceforge.net/projects/bacula/files/bacula/9.4.4/bacula-9.4.4.tar.gz 112 | tar xvzf bacula-9.4.4.tar.gz 113 | cd bacula-9.4.4 114 | 115 | *Utilizando git (sempre pega a versão mais recente, porém as vezes pode conter alguns bugs) 116 | git clone -b Branch-9.4 http://git.bacula.org/bacula.git bacula 117 | 118 | cd /usr/src/bacula/bacula 119 | 120 | 121 | ******************************************************************************************************** 122 | * * 123 | * Nessa parte abaixo é preciso definir o banco de dados que será utilizado MySQL/MariaDB ou PostgreSQL * 124 | * Utilize os comandos de acordo com o banco escolhido. * 125 | * Caso tenha problemas durante a compilação com o OpenSSL no Debian versão 9.x, compile sem o 126 | * OpenSSL-1.1, então não habilitamos * 127 | * --without-openssl * 128 | * * 129 | ******************************************************************************************************** 130 | 131 | * Comando de pré-compilação para MySQL/MariaDB 132 | ./configure \ 133 | --enable-smartalloc \ 134 | --with-mysql \ 135 | --with-db-user=bacula \ 136 | --with-db-password=bacula \ 137 | --with-db-port=3306 \ 138 | --with-openssl \ 139 | --with-readline=/usr/include/readline \ 140 | --sysconfdir=/etc/bacula \ 141 | --bindir=/usr/bin \ 142 | --sbindir=/usr/sbin \ 143 | --with-scriptdir=/etc/bacula/scripts \ 144 | --with-plugindir=/etc/bacula/plugins \ 145 | --with-pid-dir=/var/run \ 146 | --with-subsys-dir=/etc/bacula/working \ 147 | --with-working-dir=/etc/bacula/working \ 148 | --with-bsrdir=/etc/bacula/bootstrap \ 149 | --with-basename=bacula \ 150 | --with-hostname=XXX_IP_SERVIDOR_BACULA_XXX \ 151 | --with-systemd \ 152 | --disable-conio \ 153 | --disable-nls \ 154 | --with-logdir=/var/log/bacula \ 155 | --with-dump-email=email@dominio.com.br \ 156 | --with-job-email=email@dominio.com.br 157 | 158 | * Comando de pré-compilação para PostgreSQL 159 | ./configure \ 160 | --enable-smartalloc \ 161 | --with-postgresql \ 162 | --with-db-user=bacula \ 163 | --with-db-password=bacula \ 164 | --with-db-port=5432 \ 165 | --with-openssl \ 166 | --with-readline=/usr/include/readline \ 167 | --sysconfdir=/etc/bacula \ 168 | --bindir=/usr/bin \ 169 | --sbindir=/usr/sbin \ 170 | --with-scriptdir=/etc/bacula/scripts \ 171 | --with-plugindir=/etc/bacula/plugins \ 172 | --with-pid-dir=/var/run \ 173 | --with-subsys-dir=/etc/bacula/working \ 174 | --with-working-dir=/etc/bacula/working \ 175 | --with-bsrdir=/etc/bacula/bootstrap \ 176 | --with-basename=bacula \ 177 | --with-hostname=XXX_IP_SERVIDOR_BACULA_XXX \ 178 | --with-systemd \ 179 | --disable-conio \ 180 | --disable-nls \ 181 | --with-logdir=/var/log/bacula \ 182 | --with-dump-email=email@dominio.com.br \ 183 | --with-job-email=email@dominio.com.br 184 | 185 | *Comando para efetuar a compilação e instalação 186 | make -j 8 187 | make install 188 | make install-autostart 189 | 190 | 191 | ***************************************************************************************************** 192 | * * 193 | * Passos para criação do banco de dados, usuários e permisssões MySQL/MariaDB * 194 | * * 195 | ***************************************************************************************************** 196 | 197 | +-----------------------------------------------------------------------------------+ 198 | | >>> Configurar os usuários no MySQL/MariaDB <<< | 199 | +-----------------------------------------------------------------------------------+ 200 | *Caso você não tenha definido uma senha: 201 | mysql -u root 202 | 203 | *Caso tenha definido uma senha 204 | mysql -u root -p 205 | 206 | GRANT ALL ON *.* TO 'root'@'localhost'; 207 | CREATE USER bacula; 208 | GRANT ALL ON *.* TO 'bacula'@'localhost' IDENTIFIED BY 'bacula' WITH GRANT OPTION; 209 | GRANT SELECT ON mysql.proc TO 'bacula'; 210 | FLUSH PRIVILEGES; 211 | quit 212 | /etc/init.d/mysql restart 213 | 214 | 215 | +-----------------------------------------------------------------------------------+ 216 | | >>> Criar as tabelas do bacula no MySQL/MariaDB <<< | 217 | +-----------------------------------------------------------------------------------+ 218 | cd /etc/bacula/scripts 219 | * Caso não tenha definido uma senha 220 | ./create_mysql_database 221 | ./make_mysql_tables 222 | ./grant_mysql_privileges 223 | 224 | * Caso não tenha definido uma senha 225 | ./create_mysql_database -u root -p 226 | ./make_mysql_tables -u root -p 227 | ./grant_mysql_privileges -u root -p 228 | 229 | 230 | ***************************************************************************************************** 231 | * * 232 | * Passos para criação do banco de dados, usuários e permisssões PostgreSQL * 233 | * * 234 | ***************************************************************************************************** 235 | 236 | +-----------------------------------------------------------------------------------+ 237 | | >>> Definindo a senha do usuário bacula no PostgreSQL <<< | 238 | +-----------------------------------------------------------------------------------+ 239 | su postgres 240 | psql 241 | alter user bacula with password 'bacula'; 242 | \q 243 | exit 244 | 245 | 246 | +-----------------------------------------------------------------------------------+ 247 | | >>> Criar as tabelas do bacula no PostgreSQL <<< | 248 | +-----------------------------------------------------------------------------------+ 249 | chmod 775 /etc/bacula 250 | cd /etc/bacula/scripts 251 | chown postgres create_postgresql_database && chown postgres make_postgresql_tables && \ 252 | chown postgres grant_postgresql_privileges && chown postgres drop_postgresql_database && \ 253 | chown postgres update_postgresql_tables 254 | su postgres 255 | ./create_postgresql_database 256 | ./make_postgresql_tables 257 | ./grant_postgresql_privileges 258 | exit 259 | 260 | 261 | +-----------------------------------------------------------------------------------+ 262 | | >>> Configurar o acesso ao PostgreSQL pelo bacula <<< | 263 | +-----------------------------------------------------------------------------------+ 264 | Editar o arquivo /etc/postgresql/9.6/main/postgresql.conf e alterar a linha abaixo: 265 | de: # listen_addresses = 'localhost' 266 | para: listen_addresses = '*' 267 | 268 | Editar o arquivo /etc/postgresql/9.6/main/pg_hba.conf e alterar a seguinte linha: 269 | de: local all all peer 270 | para: local all all md5 271 | 272 | *Reiniciar o PostgreSQL 273 | /etc/init.d/postgresql restart 274 | 275 | 276 | +-----------------------------------------------------------------------------------+ 277 | | >>> Iniciar o bacula <<< | 278 | +-----------------------------------------------------------------------------------+ 279 | bacula start 280 | Se tudo ocorrer bem, o bacula iniciará sem problemas e você pode acessar com o bconsole, 281 | e verá uma tela conforme abaixo 282 | 283 | root@bacula:/# bconsole 284 | Connecting to Director 192.168.1.1:9101 285 | 1000 OK: 103 bacula-dir Version: 9.4.4 (28 May 2019) 286 | Enter a period to cancel a command. 287 | * 288 | -------------------------------------------------------------------------------- /tutorial/bacula_install_ubuntu_22.0.4.txt: -------------------------------------------------------------------------------- 1 | ##################################################################################### 2 | # Passos para Instalação do Bacula via Compilação em Ubuntu 22.0.4 (jammy) # 3 | # PostgreSQL 14 # 4 | # Autor: Wanderlei Hüttel # 5 | # Email: wanderlei.huttel at gmail.com # 6 | # Data atualização: 04/07/2022 # 7 | ##################################################################################### 8 | * Leia tudo antes de começar a instalar só depois inicie a instalação. 9 | * Se você possuir algum erro, revise todo tutorial novamente e verifique se não 10 | esqueceu nenhum passo. 11 | * Este tutorial foi testado em Ubuntu 22.0.4 (jammy) em 04/07/2022 12 | 13 | ===================================================================================== 14 | >>> Atualizar a lista dos pacotes <<< 15 | ===================================================================================== 16 | apt-get update 17 | 18 | 19 | ===================================================================================== 20 | >>> Pacotes necessários para compilação padrão <<< 21 | ===================================================================================== 22 | apt-get install vim make gcc build-essential perl unp mc mtx libreadline8 \ 23 | libreadline-dev zlib1g-dev lzop liblzo2-dev python3-lzo sudo gawk gdb libacl1 \ 24 | libacl1-dev libssl-dev lsscsi apt-transport-https 25 | 26 | 27 | ===================================================================================== 28 | >>> Pacotes necessários para compilação dos drivers cloud S3 <<< 29 | ===================================================================================== 30 | apt-get install libxml2-dev libcurl4-openssl-dev 31 | 32 | 33 | ===================================================================================== 34 | >>> Configurações vim e bashrc <<< (OPCIONAL) 35 | ===================================================================================== 36 | Digitar o comando abaixo no terminal e selecionar a opção que contém "/usr/bin/vim.basic", 37 | digitando o respectivo número. 38 | update-alternatives --config editor 39 | 40 | # Desabilitar modo visual do VIM/Editor Colorido 41 | # Incluir as seguintes linhas no arquivo acima 42 | vim ~/.vimrc 43 | set mouse-=a 44 | syntax on 45 | :highlight comment ctermfg=lightblue 46 | 47 | 48 | ===================================================================================== 49 | >>> Pacotes para utilizar o banco de dados PostgreSQL <<< 50 | ===================================================================================== 51 | apt-get install postgresql-14 postgresql-14 postgresql-client-14 postgresql-server-dev-14 52 | 53 | 54 | ===================================================================================== 55 | >>> Baixando e Compilando o Fonte para usar os drivers Cloud S3 <<< 56 | ===================================================================================== 57 | cd /usr/src 58 | wget -c https://www.bacula.org/downloads/libs3-20200523.tar.gz 59 | tar xvzf libs3-20200523.tar.gz 60 | cd /usr/src/libs3-20200523 61 | 62 | # Editar o arquivo GNUmakefile 63 | # Procurar a linha com o comando CFLAGS 64 | # grep -e "^CFLAGS" GNUmakefile e remover o parâmetro "-Werror" e salvar 65 | # Antes: CFLAGS += -Wall -Werror -Wshadow -Wextra -Wno-format-truncation -Wno-stringop-overflow 66 | # Depois: CFLAGS += -Wall -Wshadow -Wextra -Wno-format-truncation -Wno-stringop-overflow 67 | DESTDIR=/usr/local make clean 68 | DESTDIR=/usr/local make 69 | DESTDIR=/usr/local make install 70 | 71 | # Refazer os caches das libraries 72 | sudo ldconfig 73 | 74 | Se tudo ocorrer bem o comando "s3" vai funcionar no terminal 75 | s3 76 | 77 | ===================================================================================== 78 | >>> Baixando e Compilando o Fonte <<< 79 | ===================================================================================== 80 | cd /usr/src 81 | *Utilizando wget 82 | wget --no-check-certificate https://sourceforge.net/projects/bacula/files/bacula/13.0.0/bacula-13.0.0.tar.gz 83 | 84 | tar xvzf bacula-13.0.0.tar.gz 85 | cd bacula-13.0.0.tar.gz 86 | 87 | *Utilizando git (sempre busca a versão mais recente, porém as vezes pode conter alguns bugs) 88 | apt-get install git 89 | git clone -b Branch-11.3 http://git.bacula.org/bacula.git bacula 90 | cd /usr/src/bacula/bacula 91 | 92 | 93 | * Comando de pré-compilação para PostgreSQL 94 | Recomendado criar um script "_bacula_postgresql.sh" para sempre usar as mesmas configurações quando atualizar. 95 | 96 | #!/usr/bin/env bash 97 | ./configure \ 98 | --enable-smartalloc \ 99 | --with-postgresql \ 100 | --with-db-user=bacula \ 101 | --with-db-password=bacula \ 102 | --with-db-port=5432 \ 103 | --with-openssl \ 104 | --with-readline=/usr/include/readline \ 105 | --sysconfdir=/etc/bacula \ 106 | --bindir=/usr/bin \ 107 | --sbindir=/usr/sbin \ 108 | --with-scriptdir=/etc/bacula/scripts \ 109 | --with-plugindir=/etc/bacula/plugins \ 110 | --with-pid-dir=/var/run \ 111 | --with-subsys-dir=/etc/bacula/working \ 112 | --with-working-dir=/etc/bacula/working \ 113 | --with-bsrdir=/etc/bacula/bootstrap \ 114 | --with-s3=/usr/local \ 115 | --with-basename=bacula \ 116 | --with-hostname=XXX_IP_SERVIDOR_BACULA_XXX \ 117 | --with-systemd 118 | --disable-conio \ 119 | --disable-nls \ 120 | --with-logdir=/var/log/bacula \ 121 | --with-dump-email=email@dominio.com.br \ 122 | --with-job-email=email@dominio.com.br 123 | 124 | *Comando para efetuar a compilação e instalação 125 | make -j 8 126 | make install 127 | make install-autostart 128 | 129 | *Comandos para configurar serviços do bacula no systemd 130 | systemctl enable bacula-{fd,dir,sd}.service 131 | systemctl start bacula-{fd,dir,sd}.service 132 | 133 | 134 | 135 | ######################################################################################################## 136 | # # 137 | # Passos para criação do banco de dados, usuários e permisssões PostgreSQL # 138 | # # 139 | ######################################################################################################## 140 | 141 | 142 | ===================================================================================== 143 | >>> Criar as tabelas do bacula no PostgreSQL <<< 144 | ===================================================================================== 145 | chmod 775 /etc/bacula 146 | cd /etc/bacula/scripts 147 | chown postgres create_postgresql_database && chown postgres make_postgresql_tables && \ 148 | chown postgres grant_postgresql_privileges && chown postgres drop_postgresql_database && \ 149 | chown postgres update_postgresql_tables 150 | su postgres 151 | /etc/bacula/scripts/create_postgresql_database 152 | /etc/bacula/scripts/make_postgresql_tables 153 | /etc/bacula/scripts/grant_postgresql_privileges 154 | 155 | 156 | ===================================================================================== 157 | >>> Definindo a senha do usuário bacula no PostgreSQL <<< 158 | ===================================================================================== 159 | psql 160 | alter user bacula with password 'bacula'; 161 | \q 162 | exit 163 | 164 | 165 | ===================================================================================== 166 | >>> Configurar o acesso ao PostgreSQL pelo bacula <<< 167 | ===================================================================================== 168 | Backup dos arquivos de configuração: 169 | \cp /etc/postgresql/14/main/postgresql.conf{,.default} 170 | \cp /etc/postgresql/14/main/pg_hba.conf{,.default} 171 | 172 | Editar o arquivo /etc/postgresql/14/main/postgresql.conf e alterar a linha abaixo: 173 | de: # listen_addresses = 'localhost' 174 | para: listen_addresses = '*' 175 | 176 | Editar o arquivo /etc/postgresql/14/main/pg_hba.conf e altere a seguinte linha: 177 | # Abaixo da linha seguinte: 178 | de: local all all peer 179 | para: local all bacula md5 180 | 181 | 182 | *Reiniciar o PostgreSQL 183 | systemctl restart postgresql 184 | 185 | 186 | ===================================================================================== 187 | >>> Iniciar o bacula <<< 188 | ===================================================================================== 189 | bacula start 190 | Se tudo ocorrer bem, o bacula iniciará sem problemas e você pode acessar com o bconsole, 191 | e verá uma tela conforme abaixo 192 | 193 | root@bacula:/# bconsole 194 | Connecting to Director 192.168.1.1:9101 195 | 1000 OK: 10002 bacula-dir Version: 13.0.0 (04 July 2022) 196 | Enter a period to cancel a command. 197 | * 198 | -------------------------------------------------------------------------------- /tutorial/baculum_install_centos7.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ################################################# 3 | # Automatic Baculum Install on Centos 7 # 4 | # Author: Wanderlei Hüttel # 5 | # Email: wanderlei.huttel@gmail.com # 6 | # Version: 1.4 - 13/02/2019 # 7 | ################################################# 8 | 9 | # Based on script https://github.com/carlosedulucas/baculum/blob/master/instalação do baculum.txt 10 | 11 | echo ">>> Baculum install Centos ..." 12 | 13 | echo ">>> Disabling any Baculum site ..." 14 | a2dissite baculum* 15 | 16 | echo ">>> Download the last version of Baculum ..." 17 | wget -P /usr/src https://sourceforge.net/projects/bacula/files/bacula/9.4.4/bacula-gui-9.4.4.tar.gz 18 | tar -xzvf /usr/src/bacula-gui-9.4.4.tar.gz -C /usr/src/ 19 | 20 | echo ">>> Copying Baculum files to /var/www/baculum ..." 21 | cp -R /usr/src/bacula-gui-9.4.4/baculum/ /var/www 22 | 23 | echo ">>> Create Baculum users (default user: admin | default password: admin ..." 24 | htpasswd -cb /var/www/baculum/protected/Web/baculum.users admin admin 25 | \cp -f /var/www/baculum/protected/Web/baculum.users /var/www/baculum/protected/Web/Config 26 | \cp -f /var/www/baculum/protected/Web/baculum.users /var/www/baculum/protected/API/Config 27 | 28 | echo ">>> Grant permission to folder /var/www/baculum ..." 29 | chown -R apache2.apache2 /var/www/baculum 30 | 31 | echo ">>> Enabling site in apache ..." 32 | \cp -f /var/www/baculum/examples/deb/baculum-web-apache.conf /etc/apache2/sites-available/baculum-web.conf 33 | sed -i 's/\/usr\/share\/baculum\/htdocs/\/var\/www\/baculum/g' /etc/apache2/sites-available/baculum-web.conf 34 | \cp -f /var/www/baculum/examples/deb/baculum-api-apache.conf /etc/apache2/sites-available/baculum-api.conf 35 | sed -i 's/\/usr\/share\/baculum\/htdocs/\/var\/www\/baculum/g' /etc/apache2/sites-available/baculum-api.conf 36 | a2ensite baculum-web.conf 37 | a2ensite baculum-api.conf 38 | 39 | echo ">>> Grant permissions in sudoers ..." 40 | echo -e "apache2 ALL=NOPASSWD: /usr/sbin/bconsole\n\ 41 | apache2 ALL=NOPASSWD: /etc/bacula/\n\ 42 | apache2 ALL=NOPASSWD: /usr/sbin/bdirjson\n\ 43 | apache2 ALL=NOPASSWD: /usr/sbin/bbconsjson\n\ 44 | apache2 ALL=NOPASSWD: /usr/sbin/bfdjson\n\ 45 | apache2 ALL=NOPASSWD: /usr/sbin/bsdjson\n\ 46 | apache2 ALL=(root) NOPASSWD: /bin/systemctl start bacula-dir\n\ 47 | apache2 ALL=(root) NOPASSWD: /bin/systemctl stop bacula-dir\n\ 48 | apache2 ALL=(root) NOPASSWD: /bin/systemctl restart bacula-dir\n\ 49 | apache2 ALL=(root) NOPASSWD: /bin/systemctl start bacula-sd\n\ 50 | apache2 ALL=(root) NOPASSWD: /bin/systemctl stop bacula-sd\n\ 51 | apache2 ALL=(root) NOPASSWD: /bin/systemctl restart bacula-sd\n\ 52 | apache2 ALL=(root) NOPASSWD: /bin/systemctl start bacula-fd\n\ 53 | apache2 ALL=(root) NOPASSWD: /bin/systemctl stop bacula-fd\n\ 54 | apache2 ALL=(root) NOPASSWD: /bin/systemctl restart bacula-fd" > /etc/sudoers.d/baculum 55 | 56 | echo ">>> Enable apache rewrite mode ..." 57 | a2enmod rewrite 58 | 59 | echo ">>> Restarting apache ..." 60 | systemctl restart httpd 61 | 62 | echo ">>> Done" 63 | -------------------------------------------------------------------------------- /tutorial/baculum_install_debian9.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ################################################# 3 | # Automatic Baculum Install on Debian 9 # 4 | # Author: Wanderlei Hüttel # 5 | # Email: wanderlei.huttel@gmail.com # 6 | # Version: 1.4 - 13/02/2019 # 7 | ################################################# 8 | 9 | # Based on script https://github.com/carlosedulucas/baculum/blob/master/instalação do baculum.txt 10 | 11 | echo ">>> Baculum install Debian ..." 12 | 13 | echo ">>> Disabling any Baculum site ..." 14 | a2dissite baculum* 15 | 16 | echo ">>> Download the last version of Baculum ..." 17 | wget -P /usr/src https://sourceforge.net/projects/bacula/files/bacula/9.4.2/bacula-gui-9.4.2.tar.gz 18 | tar -xzvf /usr/src/bacula-gui-9.4.2.tar.gz -C /usr/src/ 19 | 20 | echo ">>> Copying Baculum files to /var/www/baculum ..." 21 | cp -R /usr/src/bacula-gui-9.4.2/baculum/ /var/www 22 | 23 | echo ">>> Create Baculum users (default user: admin | default password: admin ..." 24 | htpasswd -cb /var/www/baculum/protected/Web/baculum.users admin admin 25 | \cp -f /var/www/baculum/protected/Web/baculum.users /var/www/baculum/protected/Web/Config 26 | \cp -f /var/www/baculum/protected/Web/baculum.users /var/www/baculum/protected/API/Config 27 | 28 | echo ">>> Grant permission to folder /var/www/baculum ..." 29 | chown -R www-data.www-data /var/www/baculum 30 | 31 | echo ">>> Enabling site in apache ..." 32 | \cp -f /var/www/baculum/examples/deb/baculum-web-apache.conf /etc/apache2/sites-available/baculum-web.conf 33 | sed -i 's/\/usr\/share\/baculum\/htdocs/\/var\/www\/baculum/g' /etc/apache2/sites-available/baculum-web.conf 34 | \cp -f /var/www/baculum/examples/deb/baculum-api-apache.conf /etc/apache2/sites-available/baculum-api.conf 35 | sed -i 's/\/usr\/share\/baculum\/htdocs/\/var\/www\/baculum/g' /etc/apache2/sites-available/baculum-api.conf 36 | a2ensite baculum-web.conf 37 | a2ensite baculum-api.conf 38 | 39 | echo ">>> Grant permissions in sudoers ..." 40 | echo -e "www-data ALL=NOPASSWD: /usr/sbin/bconsole\n\ 41 | www-data ALL=NOPASSWD: /etc/bacula/confapi\n\ 42 | www-data ALL=NOPASSWD: /usr/sbin/bdirjson\n\ 43 | www-data ALL=NOPASSWD: /usr/sbin/bbconsjson\n\ 44 | www-data ALL=NOPASSWD: /usr/sbin/bfdjson\n\ 45 | www-data ALL=NOPASSWD: /usr/sbin/bsdjson" > /etc/sudoers.d/baculum 46 | 47 | echo ">>> Enable apache rewrite mode ..." 48 | a2enmod rewrite 49 | 50 | echo ">>> Restarting apache ..." 51 | systemctl restart apache2 52 | 53 | echo ">>> Done" 54 | -------------------------------------------------------------------------------- /tutorial/upgrade_bacula.md: -------------------------------------------------------------------------------- 1 | ## Dicas de como efetuar o upgrade do Bacula 2 | 1. Pare todos os daemons do Bacula (tenha certeza que nenhum backup esteja sendo executado no momento), caso algum daemon estiver pendurado, force a parada com (pkill -9 bacula) 3 | 4 | 2. Efetuar um backup do banco de dados do Bacula (executar o script padrão de backup do Bacula, geralmente 5 | "/etc/bacula/scripts/make_catalog_backup.pl MyCatalog". Copiar em um local seguro o arquivo gerado pelo script. 6 | 7 | 3. Faça um backup da pasta de configuração do Bacula, geralmente /etc/bacula 8 | 9 | 4. Se o seu bacula foi instalado via pacotes, é interessante remover todos os pacotes referentes ao Bacula. 10 | Utilizar o comando: **"apt-get remove nomepacote"** 11 | 12 | 5. Se o bacula foi instalado via compilação, é interessante utilizar as mesmas opções utilizadas no **"./configure"** 13 | 14 | 6. Efetuar o download do código fonte, e proseguir como se fosse uma instalação nova 15 | 16 | 7. Copiar os arquivos de configuração (*.conf) do backup do para o /etc/bacula 17 | 18 | 8. Verificar se os caminhos que foram informados na compilação são iguais aos da configuração anterior, senão, precisa editar os arquivos, e alterar estes caminhos. 19 | 20 | 9. Rodar o script para atualizar o banco de dados do Bacula (geralmente **update_bacula_tables** ou **update_mysql_tables** ou **update_postgresql_tables** 21 | 22 | 10. Executar os comandos de testes dos daemons e certificar-se que não possuem erros de configuração. **bacula-dir -t**, **bacula-sd -t** e **bacula-fd-t** 23 | 24 | 11. Iniciar o bacula e executar o bconsole 25 | 26 | 11. Seja Feliz 27 | 28 | 29 | Em caso de erros é preciso executar o Bacula em modo debug e verificar possíveis erros. As vezes é interessante rodar um **pkill -9** para parar todos os daemons do bacula, e iniciar cada daemon separado, com a opção de debug (-d 500). 30 | **bacula-dir -d 500**, **bacula-sd -d 500**, **bacula-fd -d 500** 31 | -------------------------------------------------------------------------------- /tutorial/webacula_install_centos7.txt: -------------------------------------------------------------------------------- 1 | ##################################################################################### 2 | >>>>> Passos para instalação do Webacula no CentOS-7 <<<<< 3 | ##################################################################################### 4 | * Leia tudo antes de começar a instalar só depois inicie a instalação. 5 | * Se você possuir algum erro, revise todo tutorial novamente e verifique se não 6 | esqueceu nenhum passo. 7 | * Este tutorial foi testado em um máquina com CentOS-7-Minimal-x86_64 em 05/12/2018 8 | O webacula com o PHP-7.X (PHP <=7.3) tem alguns warnings que precisam ser corrigidos, a principio 9 | nada grave. 10 | * Nesta versão 7.5.3, foi removido o arquivo db.conf do diretório install, que era 11 | utilizado para configurar as senhas do banco de dados para criação das tabelas. Agora 12 | a criação das tabelas do webacula é igual a criação das tabelas do próprio bacula, onde 13 | executa-se o script passando o usuário e senha após o nome do arquivo. 14 | * o usuário padrão é 'root' e a senha é 'bacula' e pode ser alterada após o primeiro login 15 | * Na versão 7.5.4 foi ajustado alguns arquivos do ZendFramework1 para funcionar com o PHP <= 7.3 16 | 17 | Considerando que você já possuí o Bacula instalado 18 | 19 | +-----------------------------------------------------------------------------------+ 20 | | >>> Atualizar a lista dos pacotes <<< | 21 | +-----------------------------------------------------------------------------------+ 22 | yum update 23 | 24 | 25 | +-----------------------------------------------------------------------------------+ 26 | | >>> Instalar dependências PHP <<< | 27 | +-----------------------------------------------------------------------------------+ 28 | yum install apache2 libapache2-mod-php php php-gd php-dev php-mcrypt php-curl 29 | 30 | 31 | +-----------------------------------------------------------------------------------+ 32 | | >>> Instalar dependências do MySQL/MariaDB <<< | 33 | +-----------------------------------------------------------------------------------+ 34 | yum install php-mysqlnd 35 | 36 | 37 | +-----------------------------------------------------------------------------------+ 38 | | >>> Instalar dependências do PostgreSQL <<< | 39 | +-----------------------------------------------------------------------------------+ 40 | yum install php-pgsql 41 | 42 | 43 | +-----------------------------------------------------------------------------------+ 44 | | >>> Configurar o PHP <<< | 45 | +-----------------------------------------------------------------------------------+ 46 | Editar o arquivo /etc/php.ini and alterar a opção 'date.timezone' e 'max_execution_time' 47 | vim /etc/php.ini 48 | date.timezone = America/Sao_Paulo 49 | max_execution_time = 3600 50 | 51 | 52 | +-----------------------------------------------------------------------------------+ 53 | | >>> Efetuar o download da última versão do Webacula <<< | 54 | +-----------------------------------------------------------------------------------+ 55 | Verificar qual é a última versão do Webacula em: https://github.com/wanderleihuttel/webacula/releases 56 | * A última versão na instalação do tutorial é a 7.5.4 57 | cd /usr/src/ 58 | wget --no-check-certificate -c https://github.com/wanderleihuttel/webacula/archive/7.5.4.tar.gz 59 | tar xvzf 7.5.4.tar.gz 60 | mv webacula-7.5.4 webacula 61 | 62 | 63 | +-----------------------------------------------------------------------------------+ 64 | | >>> Criar as tabelas do Webacula no MySQL/MariaDB <<< | 65 | +-----------------------------------------------------------------------------------+ 66 | cd /usr/src/webacula/install/MySql 67 | 68 | * Caso não tenha definido uma senha 69 | ./10_make_tables.sh 70 | ./20_acl_make_tables.sh 71 | /etc/bacula/scripts/grant_mysql_privileges 72 | 73 | * Caso tenha definido uma senha 74 | ./10_make_tables.sh -p 75 | ./20_acl_make_tables.sh -p 76 | /etc/bacula/scripts/grant_mysql_privileges -p 77 | 78 | 79 | +-----------------------------------------------------------------------------------+ 80 | | >>> Criar as tabelas do Webacula no PostgreSQL <<< | 81 | +-----------------------------------------------------------------------------------+ 82 | cd /usr/src/webacula/install/PostgreSql 83 | chown postgres 10_make_tables.sh && chown postgres 20_acl_make_tables.sh && \ 84 | chown postgres 30_grant_postgresql_privileges.sh && chown postgres 40_delete_postgresql_tables.sh 85 | su postgres 86 | ./10_make_tables.sh 87 | ./20_acl_make_tables.sh 88 | ./30_grant_postgresql_privileges.sh 89 | exit 90 | 91 | 92 | +-----------------------------------------------------------------------------------+ 93 | | >>> Incluir os scripts para gerar o número de bytes copiados (>= 7.5.3 ) <<< | 94 | +-----------------------------------------------------------------------------------+ 95 | * Como o Bacula salva as informações dos arquivos em um campo "criptografado", 96 | não é possível obter diretamente do banco essas informações, é preciso descriptografar primeiro. 97 | Esses scripts fazem isso, buscam as informações de cada arquivo, descriptografa, e salva 98 | em uma tabela do Webacula (webacula_job_size). Como ele busca dados pelo bconsole, não é preciso 99 | se importar se o banco de dados é MySQL/MariaDB ou PostgreSQL. 100 | 101 | Copiar os scripts da pasta "webacula/install/scripts/" para a pasta de script do servidor, 102 | e dar permissão a+x. 103 | 104 | Executar o script "_webacula_update_filesize_once.sh" para buscar o tamanho dos arquivos 105 | dos backups antigos. 106 | 107 | Incluir no JobDefs a diretiva "RunScript" para executar o script de que busca o tamanho original 108 | do Backup após o término do mesmo, e reiniciar o Bacula. 109 | 110 | JobDefs { 111 | ... 112 | RunScript { 113 | Command = "/etc/bacula/scripts/_webacula_update_filesize.sh %i %t %e" 114 | RunsWhen = After 115 | RunsOnClient = no 116 | RunsOnFailure = yes 117 | RunsOnSuccess = yes 118 | } 119 | ... 120 | } 121 | 122 | 123 | +-----------------------------------------------------------------------------------+ 124 | | >>> Editar o arquivo /usr/src/webacula/application/config.ini <<< | 125 | +-----------------------------------------------------------------------------------+ 126 | Preencher os campos com do usuário bacula do MySQL/MariaDB ou do PostgreSQL 127 | MySQL/MariaDB = PDO_MYSQL 128 | PostgreSQL = PDO_PGSQL 129 | 130 | vim /usr/src/webacula/application/config.ini 131 | 132 | db.adapter = PDO_PGSQL 133 | db.config.host = localhost 134 | db.config.username = bacula 135 | db.config.password = bacula 136 | db.config.dbname = bacula 137 | def.timezone = "America/Sao_Paulo" 138 | # Caminho dos binários do bacula e sudo. Caso esteja com problemas, deixe em branco a configuração do sudo 139 | bacula.sudo = "/usr/bin/sudo" 140 | bacula.bconsole = "/sbin/bconsole" 141 | bacula.bconsolecmd = "-n -c /etc/bacula/bconsole.conf" 142 | 143 | 144 | +-----------------------------------------------------------------------------------+ 145 | | >>> Conceder permissão correta aos diretórios e arquivos <<< | 146 | +-----------------------------------------------------------------------------------+ 147 | cd /usr/src 148 | chown -R apache.apache /usr/src/webacula 149 | chmod 775 /etc/bacula 150 | chmod 777 /usr/src/webacula/data/cache 151 | 152 | 153 | +-----------------------------------------------------------------------------------+ 154 | | >>> Configurar o Apache <<< | 155 | +-----------------------------------------------------------------------------------+ 156 | Copiar o arquivo /usr/src/webacula/install/apache/webacula.conf para /etc/httpd/conf.d 157 | cp /usr/src/webacula/install/apache/webacula.conf /etc/httpd/conf.d/webacula.conf 158 | 159 | Editar o arquivo /etc/httpd/conf.d/webacula.conf e verificar se está liberado 160 | para a sua faixa de rede. Por padrão é "Allow from 192.168.1." 161 | 162 | 163 | +-----------------------------------------------------------------------------------+ 164 | | >>> Conceder permissão para o usuário www-data executar o bconsole <<< | 165 | +-----------------------------------------------------------------------------------+ 166 | echo "apache ALL=NOPASSWD:/usr/sbin/bconsole" > /etc/sudoers.d/webacula 167 | apachectl restart 168 | 169 | 170 | +-----------------------------------------------------------------------------------+ 171 | | >>> Mover o diretório /usr/src/webacula para o diretório root do Apache <<< | 172 | +-----------------------------------------------------------------------------------+ 173 | mv /usr/src/webacula /var/www 174 | 175 | 176 | +-----------------------------------------------------------------------------------+ 177 | | >>> Liberar o acesso ao Webacula no Firewall <<< | 178 | +-----------------------------------------------------------------------------------+ 179 | firewall-cmd --permanent --zone=public --add-service=http 180 | firewall-cmd --permanent --zone=public --add-service=https 181 | systemctl restart firewalld 182 | 183 | 184 | +-----------------------------------------------------------------------------------+ 185 | | >>> Acessar o Webacula <<< | 186 | +-----------------------------------------------------------------------------------+ 187 | Acessar o webacula pelo endereço ip: http://192.168.1.x/webacula 188 | Usuário padrão: root 189 | Senha padrão: bacula 190 | -------------------------------------------------------------------------------- /tutorial/webacula_install_debian9.txt: -------------------------------------------------------------------------------- 1 | ##################################################################################### 2 | >>>>> Passos para instalação do Webacula no Debian (testado em Debian >= 8.0 ) <<<<< 3 | ##################################################################################### 4 | * Leia tudo antes de começar a instalar só depois inicie a instalação. 5 | * Se você possuir algum erro, revise todo tutorial novamente e verifique se não 6 | esqueceu nenhum passo. 7 | * Este tutorial foi testado em Debian 9.5 em 05/12/2018 8 | O webacula com o PHP-7.X (PHP <=7.3) tem alguns warnings que precisam ser corrigidos, a principio 9 | nada grave. 10 | * Nesta versão 7.5.3, foi removido o arquivo db.conf do diretório install, que era 11 | utilizado para configurar as senhas do banco de dados para criação das tabelas. Agora 12 | a criação das tabelas do webacula é igual a criação das tabelas do próprio bacula, onde 13 | executa-se o script passando o usuário e senha após o nome do arquivo. 14 | * o usuário padrão é 'root' e a senha é 'bacula' e pode ser alterada após o primeiro login 15 | * Na versão 7.5.4 foi ajustado alguns arquivos do ZendFramework1 para funcionar com o PHP <= 7.3 16 | 17 | Considerando que você já possuí o Bacula instalado 18 | 19 | +-----------------------------------------------------------------------------------+ 20 | | >>> Atualizar a lista dos pacotes <<< | 21 | +-----------------------------------------------------------------------------------+ 22 | apt-get update 23 | 24 | 25 | +-----------------------------------------------------------------------------------+ 26 | | >>> Instalar dependências PHP <<< | 27 | +-----------------------------------------------------------------------------------+ 28 | apt-get install apache2 libapache2-mod-php php php-gd php-dev php-mcrypt php-curl 29 | 30 | 31 | +-----------------------------------------------------------------------------------+ 32 | | >>> Instalar dependências do MySQL/MariaDB <<< | 33 | +-----------------------------------------------------------------------------------+ 34 | apt-get install php-mysqlnd 35 | 36 | 37 | +-----------------------------------------------------------------------------------+ 38 | | >>> Instalar dependências do PostgreSQL <<< | 39 | +-----------------------------------------------------------------------------------+ 40 | apt-get install php-pgsql 41 | 42 | 43 | +-----------------------------------------------------------------------------------+ 44 | | >>> Configurar o PHP <<< | 45 | +-----------------------------------------------------------------------------------+ 46 | Editar o arquivo /etc/php/7.0/apache2/php.ini and alterar a opção 'date.timezone' e 'max_execution_time' 47 | vim /etc/php/7.0/apache2/php.ini 48 | date.timezone = America/Sao_Paulo 49 | max_execution_time = 3600 50 | 51 | 52 | +-----------------------------------------------------------------------------------+ 53 | | >>> Efetuar o download da última versão do Webacula <<< | 54 | +-----------------------------------------------------------------------------------+ 55 | Verificar qual é a última versão do Webacula em: https://github.com/wanderleihuttel/webacula/releases 56 | * A última versão na instalação do tutorial é a 7.5.4 57 | cd /usr/src/ 58 | wget --no-check-certificate -c https://github.com/wanderleihuttel/webacula/archive/7.5.4.tar.gz 59 | tar xvzf 7.5.4.tar.gz 60 | mv webacula-7.5.4 webacula 61 | 62 | 63 | +-----------------------------------------------------------------------------------+ 64 | | >>> Criar as tabelas do Webacula no MySQL/MariaDB <<< | 65 | +-----------------------------------------------------------------------------------+ 66 | cd /usr/src/webacula/install/MySql 67 | 68 | * Caso não tenha definido uma senha 69 | ./10_make_tables.sh 70 | ./20_acl_make_tables.sh 71 | /etc/bacula/scripts/grant_mysql_privileges 72 | 73 | * Caso tenha definido uma senha 74 | ./10_make_tables.sh -p 75 | ./20_acl_make_tables.sh -p 76 | /etc/bacula/scripts/grant_mysql_privileges -p 77 | 78 | 79 | +-----------------------------------------------------------------------------------+ 80 | | >>> Criar as tabelas do Webacula no PostgreSQL <<< | 81 | +-----------------------------------------------------------------------------------+ 82 | cd /usr/src/webacula/install/PostgreSql 83 | chown postgres 10_make_tables.sh && chown postgres 20_acl_make_tables.sh && \ 84 | chown postgres 30_grant_postgresql_privileges.sh && chown postgres 40_delete_postgresql_tables.sh 85 | su postgres 86 | ./10_make_tables.sh 87 | ./20_acl_make_tables.sh 88 | ./30_grant_postgresql_privileges.sh 89 | exit 90 | 91 | 92 | +-----------------------------------------------------------------------------------+ 93 | | >>> Incluir os scripts para gerar o número de bytes copiados (>= 7.5.3 ) <<< | 94 | +-----------------------------------------------------------------------------------+ 95 | * Como o Bacula salva as informações dos arquivos em um campo "criptografado", 96 | não é possível obter diretamente do banco essas informações, é preciso descriptografar primeiro. 97 | Esses scripts fazem isso, buscam as informações de cada arquivo, descriptografa, e salva 98 | em uma tabela do Webacula (webacula_job_size). Como ele busca dados pelo bconsole, não é preciso 99 | se importar se o banco de dados é MySQL/MariaDB ou PostgreSQL. 100 | 101 | Copiar os scripts da pasta "webacula/install/scripts/" para a pasta de script do servidor, 102 | e dar permissão a+x. 103 | 104 | Executar o script "_webacula_update_filesize_once.sh" para buscar o tamanho dos arquivos 105 | dos backups antigos. 106 | 107 | Incluir no JobDefs a diretiva "RunScript" para executar o script de que busca o tamanho original 108 | do Backup após o término do mesmo, e reiniciar o Bacula. 109 | 110 | JobDefs { 111 | ... 112 | RunScript { 113 | Command = "/etc/bacula/scripts/_webacula_update_filesize.sh %i %t %e" 114 | RunsWhen = After 115 | RunsOnClient = no 116 | RunsOnFailure = yes 117 | RunsOnSuccess = yes 118 | } 119 | ... 120 | } 121 | 122 | 123 | +-----------------------------------------------------------------------------------+ 124 | | >>> Editar o arquivo /usr/src/webacula/application/config.ini <<< | 125 | +-----------------------------------------------------------------------------------+ 126 | Preencher os campos com do usuário bacula do MySQL/MariaDB ou do PostgreSQL 127 | MySQL/MariaDB = PDO_MYSQL 128 | PostgreSQL = PDO_PGSQL 129 | 130 | vim /usr/src/webacula/application/config.ini 131 | 132 | db.adapter = PDO_PGSQL 133 | db.config.host = localhost 134 | db.config.username = bacula 135 | db.config.password = bacula 136 | db.config.dbname = bacula 137 | def.timezone = "America/Sao_Paulo" 138 | # Caminho dos binários do bacula e sudo. Caso esteja com problemas, deixe em branco a configuração do sudo 139 | bacula.sudo = "/usr/bin/sudo" 140 | bacula.bconsole = "/sbin/bconsole" 141 | bacula.bconsolecmd = "-n -c /etc/bacula/bconsole.conf" 142 | 143 | 144 | +-----------------------------------------------------------------------------------+ 145 | | >>> Conceder permissão correta aos diretórios e arquivos <<< | 146 | +-----------------------------------------------------------------------------------+ 147 | cd /usr/src 148 | chown -R www-data.www-data /usr/src/webacula 149 | chmod 775 /etc/bacula 150 | chmod 777 /usr/src/webacula/data/cache 151 | 152 | 153 | +-----------------------------------------------------------------------------------+ 154 | | >>> Configurar o Apache <<< | 155 | +-----------------------------------------------------------------------------------+ 156 | Copiar o arquivo /usr/src/webacula/install/apache/webacula.conf para /etc/apache2/sites-available/ 157 | cp /usr/src/webacula/install/apache/webacula.conf /etc/apache2/sites-available/webacula.conf 158 | 159 | Editar o arquivo /etc/apache2/sites-available/webacula.conf e verificar se está liberado 160 | para a sua faixa de rede. Por padrão é "Allow from 192.168.1." 161 | 162 | * Habilitar o modo rewrite do Apache 163 | a2enmod rewrite 164 | 165 | * Habilitar o Webacula no Apache 166 | cd /etc/apache2/sites-available/ 167 | a2ensite webacula.conf 168 | 169 | 170 | +-----------------------------------------------------------------------------------+ 171 | | >>> Conceder permissão para o usuário www-data executar o bconsole <<< | 172 | +-----------------------------------------------------------------------------------+ 173 | echo "www-data ALL=NOPASSWD:/usr/sbin/bconsole" > /etc/sudoers.d/webacula 174 | service apache2 restart 175 | 176 | +-----------------------------------------------------------------------------------+ 177 | | >>> Mover o diretório /usr/src/webacula para o diretório root do Apache <<< | 178 | +-----------------------------------------------------------------------------------+ 179 | mv /usr/src/webacula /var/www 180 | 181 | 182 | +-----------------------------------------------------------------------------------+ 183 | | >>> Acessar o Webacula <<< | 184 | +-----------------------------------------------------------------------------------+ 185 | Acessar o webacula pelo endereço ip: http://192.168.1.x/webacula 186 | Usuário padrão: root 187 | Senha padrão: bacula 188 | 189 | --------------------------------------------------------------------------------