Chuyển tới nội dung chính

Backup & File Management Scripts

Các scripts trong phần này giúp bạn tự động hóa việc sao lưu dữ liệu, quản lý file và dọn dẹp hệ thống một cách hiệu quả.

🔄 1. Script Backup Tự Động

Backup Thư Mục với Nén

#!/bin/bash
# backup_directory.sh - Sao lưu thư mục với nén và timestamp

# Cấu hình
SOURCE_DIR="/home/user/documents"
BACKUP_DIR="/backup"
DATE=$(date +"%Y%m%d_%H%M%S")
BACKUP_NAME="backup_${DATE}.tar.gz"
LOG_FILE="/var/log/backup.log"
MAX_BACKUPS=7 # Giữ lại 7 bản backup gần nhất

# Hàm ghi log
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Kiểm tra thư mục nguồn
if [ ! -d "$SOURCE_DIR" ]; then
log_message "ERROR: Thư mục nguồn $SOURCE_DIR không tồn tại"
exit 1
fi

# Tạo thư mục backup nếu chưa có
mkdir -p "$BACKUP_DIR"

# Bắt đầu backup
log_message "Bắt đầu backup $SOURCE_DIR"

# Tạo file backup với nén
if tar -czf "$BACKUP_DIR/$BACKUP_NAME" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"; then
BACKUP_SIZE=$(du -h "$BACKUP_DIR/$BACKUP_NAME" | cut -f1)
log_message "SUCCESS: Backup hoàn thành - $BACKUP_NAME ($BACKUP_SIZE)"
else
log_message "ERROR: Backup thất bại"
exit 1
fi

# Dọn dẹp backup cũ
log_message "Dọn dẹp backup cũ (giữ lại $MAX_BACKUPS bản gần nhất)"
cd "$BACKUP_DIR" || exit 1
ls -t backup_*.tar.gz | tail -n +$((MAX_BACKUPS + 1)) | xargs -r rm -f

# Hiển thị danh sách backup hiện có
log_message "Danh sách backup hiện có:"
ls -lh backup_*.tar.gz | tee -a "$LOG_FILE"

log_message "Backup script hoàn thành"

Cách sử dụng

  1. Cấp quyền thực thi:
chmod +x backup_directory.sh
  1. Chạy thủ công:
./backup_directory.sh
  1. Tự động hóa với cron (chạy hàng ngày lúc 2:00 AM):
crontab -e
# Thêm dòng:
0 2 * * * /path/to/backup_directory.sh

🧹 2. Script Dọn Dẹp Disk

Dọn Dẹp Tự Động

#!/bin/bash
# disk_cleanup.sh - Dọn dẹp disk tự động

# Cấu hình
LOG_FILE="/var/log/disk_cleanup.log"
MIN_FREE_SPACE=10 # Phần trăm dung lượng trống tối thiểu
TEMP_DIRS=("/tmp" "/var/tmp" "/var/cache")
LOG_DIRS=("/var/log")
MAX_LOG_AGE=30 # Xóa log cũ hơn 30 ngày
MAX_TEMP_AGE=7 # Xóa file temp cũ hơn 7 ngày

# Hàm ghi log
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Hàm kiểm tra dung lượng disk
check_disk_space() {
local partition=$1
local usage=$(df "$partition" | awk 'NR==2 {print $5}' | sed 's/%//')
local free_space=$((100 - usage))

log_message "Partition $partition: ${usage}% used, ${free_space}% free"

if [ "$free_space" -lt "$MIN_FREE_SPACE" ]; then
log_message "WARNING: Partition $partition có ít dung lượng trống ($free_space%)"
return 1
fi
return 0
}

# Hàm dọn dẹp thư mục temp
cleanup_temp_dirs() {
log_message "Dọn dẹp thư mục tạm thời"

for dir in "${TEMP_DIRS[@]}"; do
if [ -d "$dir" ]; then
log_message "Dọn dẹp $dir (files older than $MAX_TEMP_AGE days)"

# Đếm số file trước khi xóa
before_count=$(find "$dir" -type f -mtime +$MAX_TEMP_AGE 2>/dev/null | wc -l)

# Xóa files cũ
find "$dir" -type f -mtime +$MAX_TEMP_AGE -delete 2>/dev/null

# Xóa thư mục rỗng
find "$dir" -type d -empty -delete 2>/dev/null

after_count=$(find "$dir" -type f 2>/dev/null | wc -l)
deleted_count=$((before_count - after_count))

log_message "Đã xóa $deleted_count files từ $dir"
fi
done
}

# Hàm dọn dẹp log files
cleanup_log_files() {
log_message "Dọn dẹp log files"

for dir in "${LOG_DIRS[@]}"; do
if [ -d "$dir" ]; then
log_message "Dọn dẹp logs trong $dir (older than $MAX_LOG_AGE days)"

# Xóa log files cũ (trừ file log hiện tại)
find "$dir" -name "*.log" -type f -mtime +$MAX_LOG_AGE ! -name "$(basename "$LOG_FILE")" -delete 2>/dev/null
find "$dir" -name "*.log.*" -type f -mtime +$MAX_LOG_AGE -delete 2>/dev/null

# Nén log files lớn
find "$dir" -name "*.log" -type f -size +100M ! -name "$(basename "$LOG_FILE")" -exec gzip {} \; 2>/dev/null
fi
done
}

# Hàm dọn dẹp package cache
cleanup_package_cache() {
log_message "Dọn dẹp package cache"

# APT cache (Ubuntu/Debian)
if command -v apt-get >/dev/null 2>&1; then
apt-get clean
apt-get autoclean
apt-get autoremove -y
log_message "Đã dọn dẹp APT cache"
fi

# YUM cache (CentOS/RHEL)
if command -v yum >/dev/null 2>&1; then
yum clean all
log_message "Đã dọn dẹp YUM cache"
fi

# DNF cache (Fedora)
if command -v dnf >/dev/null 2>&1; then
dnf clean all
log_message "Đã dọn dẹp DNF cache"
fi
}

# Hàm hiển thị thống kê
show_disk_stats() {
log_message "=== THỐNG KÊ DISK SPACE ==="
df -h | tee -a "$LOG_FILE"
log_message "=== TOP 10 THỦ MỤC LỚN NHẤT ==="
du -h / 2>/dev/null | sort -hr | head -10 | tee -a "$LOG_FILE"
}

# Main execution
log_message "Bắt đầu disk cleanup script"

# Hiển thị thống kê trước khi dọn dẹp
show_disk_stats

# Kiểm tra dung lượng các partition chính
check_disk_space "/"
check_disk_space "/var" 2>/dev/null || true
check_disk_space "/tmp" 2>/dev/null || true

# Thực hiện dọn dẹp
cleanup_temp_dirs
cleanup_log_files
cleanup_package_cache

# Hiển thị thống kê sau khi dọn dẹp
log_message "=== THỐNG KÊ SAU KHI DỌN DẸP ==="
show_disk_stats

log_message "Disk cleanup script hoàn thành"

⚙️ 3. Cấu Hình và Lưu Ý

Cấu Hình Cron Jobs

# Mở crontab editor
crontab -e

# Thêm các dòng sau:
# Backup thư mục hàng ngày lúc 2:00 AM
0 2 * * * /path/to/backup_directory.sh

# Dọn dẹp disk hàng tuần vào Chủ nhật lúc 1:00 AM
0 1 * * 0 /path/to/disk_cleanup.sh

Quyền và Bảo Mật

# Cấp quyền thực thi cho scripts
chmod +x *.sh

# Đặt quyền sở hữu cho user backup
chown backup:backup *.sh

# Bảo vệ file chứa mật khẩu
chmod 600 /path/to/config/db_credentials

# Tạo user riêng cho backup
useradd -r -s /bin/bash backup

Monitoring và Alerting

#!/bin/bash
# monitor_backups.sh - Kiểm tra trạng thái backup

BACKUP_DIRS=("/backup")
ALERT_EMAIL="[email protected]"
MAX_AGE=2 # Cảnh báo nếu backup cũ hơn 2 ngày

for dir in "${BACKUP_DIRS[@]}"; do
if [ -d "$dir" ]; then
latest_backup=$(find "$dir" -type f -name "*.tar.gz" | sort | tail -1)

if [ -n "$latest_backup" ]; then
age=$(find "$latest_backup" -mtime +$MAX_AGE)
if [ -n "$age" ]; then
echo "WARNING: Backup trong $dir cũ hơn $MAX_AGE ngày" | mail -s "Backup Alert" "$ALERT_EMAIL"
fi
else
echo "ERROR: Không tìm thấy backup trong $dir" | mail -s "Backup Alert" "$ALERT_EMAIL"
fi
fi
done

Troubleshooting

Lỗi thường gặp:

  1. Permission denied:

    sudo chown -R backup:backup /backup
    sudo chmod -R 755 /backup
  2. Disk space full:

    # Kiểm tra dung lượng
    df -h
    # Dọn dẹp khẩn cấp
    find /backup -name "*.tar.gz" -mtime +30 -delete
  3. Cron job không chạy:

    # Kiểm tra cron service
    systemctl status cron
    # Xem log cron
    tail -f /var/log/cron

Lưu ý quan trọng:

  • Luôn test scripts trước khi đưa vào production

  • Backup cấu hình trước khi thay đổi

  • Kiểm tra log files thường xuyên

  • Đảm bảo có đủ dung lượng cho backup

  • Thiết lập monitoring và alerting