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<