Site icon Learning & Doing

Membuat File backup dan sending to email dengan Bash di linux

1. install dahulu crontab dan mailx

 ubuntu /debian :
apt-get install cron
apt-get install heirloom-mailx (harus versi 12.5)

#jika di debian 9 harus ikutin petunjuk berikut :
masukan repo debian jessie :
nano /etc/apt/source.list
deb http://ftp.de.debian.org/debian jessie main
lalu update : apt-get update -y
apt-get install heirloom-mailx
cek versi : dpkg -l |grep mail
heirloom-mailx 12.5-4 amd64 feature-rich BSD mail(1)

 Centos :
yum install cronie -y
yum -y install mailx

2. pastikan service nya running
3. contoh saya akan melakukan backup config DNS
4. buat script bash di /home/backup/backup.sh
5. lalu chmod a+x backup.sh
masukan scrip berikut :

#!/bin/bash
####################################
#
# Backup script.
#
####################################

# What to backup.
backup_files1=\"/var/cache/bind/*\"
backup_files2=\"/etc/bind/*\"

# Where to backup to.
dest=\"/home/backup\"

# Create archive filename.
day=$(date +\"%m-%d-%y\")
hostname=$(hostname -s)
archive_file=\"$hostname-$day.tar.gz\"

# Print start status message.
echo \"Backing up $backup_files1 to $dest/$archive_file\"
echo \"Backing up $backup_files2 to $dest/$archive_file\"
date
echo

# Backup the files using tar.
tar czf $dest/$archive_file $backup_files1 $backup_files2

# Print end status message.
echo
echo \"Backup finished\"
date

# Long listing of files in $dest to check file sizes.
# ls -lh $dest
sleep 1m

# delete  file setelah 1 hari
find /home/backup/ns1-* -mtime +1 -exec rm {} \\;
sleep 5

# email

mail -r dns1@xxx.com -s \"DNS Backup\" -a $dest/$archive_file -S smtp=smtp.xxx.net  hendro@xxx.com  <<< \"isi Backup DNS\"

# log 
[ $? -ne 0 ] && echo -e \'backup \\e[91mfailed\\e[0m\' >> /var/log/backup/backup.log || echo -e \'backup \\e[32msuccess\\e[0m\' >>  /var/log/backup/backup.log

5. setting crontab

0 4 * * * /home/backup/backup.sh

misal : tiap jam 4 pagi .
Exit mobile version