Linux下文件夹的自动同步

Linux下文件夹的自动同步

问题:服务器a每天21:00给服务器B发送日志文件,服务器B接受到日志文件后,如果磁盘大小小于10G则选择创建时间最早的文件删除,保证磁盘剩余空间大于等于10G。

安装的python库

#coding=utf-8
import time
import os
import threading
import socket
import schedule
import hashlib
import shutil
from functools import cmp_to_key

#coding=utf-8在Linux系统中用来指定编码方式,否则程序中有中文会报错!
path_str = ‘./home1’ ##工作目录
ip = ‘127.0.0.1’
port = 6969
指定工作目录,目标IP,端口号等信息。

对文件夹下文件进行排序,按照时间排序

def compare(x,y): ##文件夹排序函数--sort()
    stat_x = os.stat(path_str + '/' + x)
    stat_y = os.stat(path_str + '/' + y)
    if stat_x.st_ctime < stat_y.st_ctime:
        return -1
    elif stat_x.st_ctime > stat_y.st_ctime: ##由操作系统的ctime统一
        return 1
    else:
        return 0

定义多线程函数

def run_threaded(job_func): ##多线程并发执行
    job_thread = threading.Thread(target=job_func)
    job_thread.start()

监听,每天定时执行,A和B错开一分钟确保不会掉线

#服务器B
    schedule.every().day.at("21:01").do(run_threaded,start)
    while True:
        schedule.run_pending()
        time.sleep(1)
#服务器A
    if not os.path.exists(path_str):
        os.mkdir(path_str)
    schedule.every().day.at("21:00").do(run_threaded,Serber_start)
    schedule.every().day.at("21:00").do(run_threaded,storage_space)
    while True:
        schedule.run_pending()
        time.sleep(1)

创建收发信息的日志文件

def journal(record):
    if os.path.exists('./abc.log'):
        with open('./abc.log','a') as f:
            f.write(record)
    else:
        with open('./abc.log','w+') as f:
            f.write(record)

监视磁盘空间,小于指定值则删除最早创建的文件

def storage_space(): ##监视磁盘空间,当磁盘空间少于10时,删除最先创建的文件夹
    global path_str
    disk = os.statvfs(path_str)
    disk_size = disk.f_bsize * disk.f_blocks / (1024 ** 3)  # 1G = 1024M  1M = 1024KB 1KB = 1024bytes<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万家灯火@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值