linux脚本练习2-文件压缩删除

目的:

1、将/data01/log/10.175.253.245/ 以原文件夹名+当天日期命名压缩至打包至/data02/log-bakcup/目录下
2、查询上一个压缩复制动作是否执行完成,如果执行完成,删除原文件夹
3、将以上操作追加至日志文件/data02/10.175.253.245-autobak.log
4、每周五下午15:30执行该操作,并将执行情况进行记录

实现:
python

1、代码:

javascript 复制代码
#!/usr/bin/python3
#-------songp--------#
#-----2024-03-09-----#
#----autobackup.py---#
#---------V1---------#

import os  
import tarfile  
import time  
from datetime import datetime  
import shutil
  
# 定义源文件夹、目标文件夹和日志文件路径  
SOURCE_DIR = "/data01/log/10.175.253.245/"  
BACKUP_DIR = "/data02/log-backup/"  
LOG_FILE = "/data02/10.175.253.245-autobak.log"  
  
# 确保日志文件存在  
if not os.path.exists(LOG_FILE):  
    with open(LOG_FILE, 'w'):  
        pass  
  
# 获取当前日期并格式化为YYYYMMDD  
current_date = datetime.now().strftime("%Y%m%d")  
  
# 定义压缩文件的名称  
backup_file = f"10.175.253.245-{current_date}.tar.gz"  
backup_path = os.path.join(BACKUP_DIR, backup_file)  
  
# 记录压缩过程开始到日志文件  
with open(LOG_FILE, 'a') as log:  
    log.write(f"{datetime.now()}: The compression process is being initiated\n")  
  
# 压缩源文件夹至目标文件夹  
try:  
    with tarfile.open(backup_path, 'w:gz') as tar:  
        tar.add(SOURCE_DIR, arcname=os.path.basename(SOURCE_DIR))  
  
    # 检查压缩文件是否确实存在  
    if os.path.exists(backup_path):  
        # 遍历原始文件夹并删除其中的文件  
        for filename in os.listdir(SOURCE_DIR):  
            file_path = os.path.join(SOURCE_DIR, filename)  
            try:  
                # 如果是文件,则删除  
                if os.path.isfile(file_path):  
                    os.remove(file_path)  
                    print(f"Removed file: {file_path}")  
                # 如果是目录,则跳过(在这个例子中,我们仅处理文件)  
            except OSError as e:  
                print(f"Error: {e.strerror} : {file_path}")  
  
        with open(LOG_FILE, 'a') as log:  
            log.write(f"{datetime.now()}: Compressed {SOURCE_DIR} to {backup_path}\n")  
            log.write(f"{datetime.now()}: Deleted files from original directory {SOURCE_DIR}.\n")  
    else:  
        with open(LOG_FILE, 'a') as log:  
            log.write(f"{datetime.now()}: The backup file {backup_path} was not created, skipping deletion of files from {SOURCE_DIR}.\n")   
except Exception as e:  
    with open(LOG_FILE, 'a') as log:  
        log.write(f"{datetime.now()}: Compression failed with error: {e}\n")  
        log.write(f"{datetime.now()}: Did not delete original directory due to previous failure.\n")  
  
# 记录文件删除完成(如果删除操作执行了)  
if not os.path.exists(SOURCE_DIR):  
    with open(LOG_FILE, 'a') as log:  
        log.write(f"{datetime.now()}: File deletion completed.\n")

定时执行

javascript 复制代码
chmod +x autobackup.py

crontab -e
	0 15 * * 5 /path/to/autobackup.py

shell

代码:

javascript 复制代码
#!/bin/bash

#-------songp--------#
#-----2024-03-09-----#
#----autobackup.sh---#
#---------V1---------#
  
# 定义源文件夹和目标文件夹  

SOURCE_DIR="/data01/log/10.175.253.245/"  
BACKUP_DIR="/data02/log-backup/"  
LOG_FILE="/data02/10.175.253.245-autobak.log"  

if [ -f "$LOG_FILE" ]; then
        echo "$(date): $LOG_FILE Already exist" >> "$LOG_FILE"
else
        touch  "$LOG_FILE" 
fi

# 获取当前日期,并格式化为YYYYMMDD  
CURRENT_DATE=$(date +"%Y%m%d")  
  
# 定义压缩文件的名称  
BACKUP_FILE="10.175.253.245-$CURRENT_DATE.tar.gz"  


echo "$(date): The compression process is being initiated" >> "$LOG_FILE"
  
#  压缩源文件夹至目标文件夹  
tar -czvf "$BACKUP_DIR$BACKUP_FILE" "$SOURCE_DIR"  
  
# 记录压缩操作到日志文件  
echo "$(date): Compressed $SOURCE_DIR to $BACKUP_DIR$BACKUP_FILE" >> "$LOG_FILE"  
  
# 检查压缩操作是否成功  
if [ $? -eq 0 ]; then  
    echo "$(date): Compression successful." >> "$LOG_FILE"  
else  
    echo "$(date): Compression failed." >> "$LOG_FILE"  
    exit 1  
fi  
# 检查压缩操作是否成功  
if [ $? -eq 0 ]; then  
    # 检查目标目录下是否确实生成了新的压缩文件  
    if [ -f "$BACKUP_FILE" ]; then  
        rm -rf "$SOURCE_DIR"/  
        echo "$(date): Deleted original directory $SOURCE_DIR." >> "$LOG_FILE"  
    else  
        echo "$(date): The backup file $BACKUP_FILE was not created, skipping deletion of $SOURCE_DIR." >> "$LOG_FILE"  
    fi  
else  
    echo "$(date): Did not delete original directory due to previous failure." >> "$LOG_FILE"  
fi  

echo "$(date): File deletion completed " >> "$LOG_FILE"

定时执行

javascript 复制代码
chmod +x autobackup.sh

crontab -e
	0 15 * * 5 /path/to/autobackup.sh
相关推荐
Jtti几秒前
Windows系统服务器怎么设置远程连接?详细步骤
运维·服务器·windows
TeYiToKu3 分钟前
笔记整理—linux驱动开发部分(9)framebuffer驱动框架
linux·c语言·arm开发·驱动开发·笔记·嵌入式硬件·arm
dsywws6 分钟前
Linux学习笔记之时间日期和查找和解压缩指令
linux·笔记·学习
yeyuningzi14 分钟前
Debian 12环境里部署nginx步骤记录
linux·运维·服务器
上辈子杀猪这辈子学IT32 分钟前
【Zookeeper集群搭建】安装zookeeper、zookeeper集群配置、zookeeper启动与关闭、zookeeper的shell命令操作
linux·hadoop·zookeeper·centos·debian
minihuabei38 分钟前
linux centos 安装redis
linux·redis·centos
进击的六角龙39 分钟前
Python中处理Excel的基本概念(如工作簿、工作表等)
开发语言·python·excel
一只爱好编程的程序猿1 小时前
Java后台生成指定路径下创建指定名称的文件
java·python·数据下载
EasyCVR1 小时前
萤石设备视频接入平台EasyCVR多品牌摄像机视频平台海康ehome平台(ISUP)接入EasyCVR不在线如何排查?
运维·服务器·网络·人工智能·ffmpeg·音视频
Aniay_ivy1 小时前
深入探索 Java 8 Stream 流:高效操作与应用场景
java·开发语言·python