#!/bin/bash CONFIG_DIR="backup.ini" LOG_FILE="backup_log_$(date +"%Y-%m-%d_%H-%M-%S").txt" # Инициализация логирования exec &> >(tee -a "$LOG_FILE") # Проверка на выполнение скрипта с правами суперпользователя if [ "$EUID" -ne 0 ]; then echo "Error: the script must be run with superuser rights (sudo)." exit 1 fi # Проверка наличия необходимых утилит for cmd in tar ftp lftp curl; do if ! command -v "$cmd" &> /dev/null; then echo "Error: $cmd is not installed." exit 1 fi done get_ini_value() { local ini_file="$CONFIG_DIR" local section="$1" local key="$2" # Найти секцию local section_found=0 while IFS= read -r line; do # Проверка на начало секции if [[ "$line" == "[$section]" ]]; then section_found=1 continue fi # Если секция найдена, ищем ключ if [[ $section_found -eq 1 ]]; then # Проверка на конец секции if [[ "$line" =~ ^[.*]$ ]]; then break fi # Проверка на наличие ключа if [[ "$line" == "$key="* ]]; then echo "${line#*=}" return fi fi done < "$ini_file" echo "Error: Key '$key' not found in section '$section'." exit 1 } get_sent_message() { # Настройки для Telegram TELEGRAM_TOKEN=$(get_ini_value "SENT" "TELEGRAM_TOKEN") CHAT_ID=$(get_ini_value "SENT" "CHAT_ID") # Настройки для Gotify GOTIFY_URL="$(get_ini_value "SENT" "GOTIFY_URL")/message" GOTIFY_APP_TOKEN=$(get_ini_value "SENT" "GOTIFY_APP_TOKEN") # Сообщение для отправки local message="$1" local title="$(hostname)" local escaped_message=$(printf '%s\n' "$message" | jq -R .) if [[ "$ENABLE_SENT" == "true" ]]; then if [[ "$ENABLE_SENT_GOTIFY" == "true" ]]; then response=$(curl -s -o /dev/null -w "%{http_code}" -X POST "$GOTIFY_URL" -H "X-Gotify-Key: $GOTIFY_APP_TOKEN" -H "Content-Type: application/json" -d "{"title":$title,"message":$escaped_message,"priority":5}") if [[ "$response" -ne 200 ]]; then echo "Gotify error: $response" fi fi if [[ "$ENABLE_SENT_TELEGRAM" == "true" ]]; then response=$(curl -s -o /dev/null -w "%{http_code}" -X POST "https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage" -d "chat_id=$CHAT_ID&text=$title: $message") if [[ "$response" -ne 200 ]]; then echo "Telegram error: $response" fi fi fi } # Указываем директории и файлы для копирования DIRECTORIES=$(get_ini_value "Backup" "DIRS") FILES=$(get_ini_value "Backup" "FILES") ENABLE_DIRS=$(get_ini_value "Backup" "ENABLE_DIRS") ENABLE_FILES=$(get_ini_value "Backup" "ENABLE_FILES") TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S") TEMP_DIR="/tmp/backup_$TIMESTAMP" TAR_NAME="BACKUP_$(hostname)_$TIMESTAMP.tar.gz" FTP_SERVER="$(get_ini_value "FTP" "FTP_SERVER")" FTP_USER="$(get_ini_value "FTP" "FTP_USER")" FTP_PASS="$(get_ini_value "FTP" "FTP_PASS")" # Создаем временную директорию mkdir -p "$TEMP_DIR" echo "Create temp directory: $TEMP_DIR" # Проверка, включено ли резервное копирование директорий echo "Enable backup of directories: $ENABLE_DIRS" if [[ "$ENABLE_DIRS" == "true" ]]; then IFS=',' read -r -a DIR_ARRAY <<< "$DIRECTORIES" for DIR in "${DIR_ARRAY[@]}"; do if [ -d "$DIR" ]; then cp -r "$DIR" "$TEMP_DIR/" && echo "Copy directory $DIR completed." || echo "Error while copying directory $DIR." else echo "Directory $DIR not found, skipping." fi done else echo "Backup of directories is disabled." fi # Проверка, включено ли резервное копирование файлов echo "Enable backup of files: $ENABLE_FILES" if [[ "$ENABLE_FILES" == "true" ]]; then IFS=',' read -r -a FILE_ARRAY <<< "$FILES" for FILE in "${FILE_ARRAY[@]}"; do if [ -f "$FILE" ]; then cp "$FILE" "$TEMP_DIR/" && echo "Copy file $FILE completed." || echo "Error while copying file $FILE." else echo "File $FILE not found, skipping." fi done else echo "Backup of files is disabled." fi # Упаковываем временную директорию в tar.gz архив tar -czf "$TAR_NAME" -C "$TEMP_DIR" . && echo "Created tar.gz archive: $(pwd)/$TAR_NAME" || { echo "Error while creating tar.gz archive."; rm -rf "$TEMP_DIR"; exit 1; } # Проверяем наличие файлов if [[ ! -f "$TAR_NAME" ]]; then echo "Fайл $TAR_NAME не найден." exit 1 fi if [[ ! -f "$LOG_FILE" ]]; then echo "Fайл $LOG_FILE не найден." exit 1 fi # Загружаем файлы на FTP-сервер echo "Sending files ..." lftp -u "$FTP_USER","$FTP_PASS" "$FTP_SERVER" < ftp_log.txt 2>&1 set ssl:verify-certificate no set net:timeout 10 set net:max-retries 3 set net:reconnect-interval-base 5 set net:reconnect-interval-multiplier 2 put "/$TAR_NAME" put "/$LOG_FILE" bye EOF # Проверка статуса выполнения FTP команды if [ $? -ne 0 ]; then echo "Error while sending files." rm "$TAR_NAME" exit 1 fi # Удаление временной директории и архива после завершения работы скрипта rm -rf "$TEMP_DIR" || { echo "Error while deleting temp directory."} echo "Temp directory deleted." rm "$TAR_NAME" || { echo "Error while deleting tar.gz archive."} echo "Tar.gz archive deleted." rm "$LOG_FILE" || { echo "Error while deleting log file."} echo "Log file deleted." echo "Sending message..." get_sent_message "$(get_ini_value "SENT" "TEXT_FINISH_MESSAGE")" || echo "Error while sending message." echo "Backup completed."