python备份数据库之接收端代码详情
本着公开的原则,源代码如下,如果大家有更好更便捷的方式,不妨分享出来,目前是第28版
具体使用方法请看:python备份数据库之 备份程序使用手册(windows版)
# _*_ utf-8 _*_
from socket import *
import datetime
import os
import time
import configparser
#接收数据类
class rev_data:
HOST = ''
PORT = ''
data_save_name = ''
def __init__(self, HOST, PORT, data_save_name):
self.HOST = HOST
self.PORT = PORT
self.data_save_name = data_save_name
def rev(self):
def log_print(log_txt, print_txt):
file = open(current_log_path, 'a', encoding='utf-8') # w 的含义为可进行读写
file.write(log_txt + "\n")
print(print_txt)
file.close()
# aaa
# 这里写 服务端 socket nat映射出来的IP地址和端口
ADDR = (self.HOST, self.PORT)
# 接收文件路径和名称
FILE = self.data_save_name
# 启动一个socket连接 去连接刚才开通的服务端
client = socket(AF_INET, SOCK_STREAM)
client.connect(ADDR)
rev_data1 = time2+' 成功与'+self.HOST+'建立连接'
print_data1 = time2+' 成功与'+self.HOST+'建立连接'
log_print(rev_data1,print_data1)
# 打开一个空的文件
with open(FILE, "ab") as f:
rev_data2 = time2 + ' 正在接收文件>>>>>>>>>>'
print_data2 = time2 + ' 正在接收文件>>>>>>>>>>'
log_print(rev_data2, print_data2)
while True:
# 以二进制方式接收文件
data = client.recv(1024000)
# 当没有内容是结束接收
if not data:
break;
# 将刚接收到的消息写入文件
f.write(data)
# 写入完毕关闭文件
f.close()
rev_data3 = time2 + ' 接收文件完毕>>>>>>>>>>'
print_data3 = time2 + ' 接收文件完毕>>>>>>>>>>'
log_print(rev_data3, print_data3)
# 关闭客户端连接
client.close()
rev_data4 = time2 + ' 断开与' + self.HOST + '的连接'
print_data4 = time2 + ' 断开与' + self.HOST + '的连接'
time.sleep(5)
log_print(rev_data4, print_data4)
#清理前三天文件类
class ls_pwd():
file_name = ''
date = ''
def __init__(self,file_name,date):
self.file_name = file_name
self.date = date
def rm_backup(self):
# 获取当前时间
# print(self.file_name)
today = datetime.datetime.now()
# 计算偏移量,前3天
riqi = self.date
offset = datetime.timedelta(days=-self.date)
# 获取想要的日期的时间,即前3天时间
re_date = (today + offset)
# 前3天时间转换为时间戳
re_date_unix = time.mktime(re_date.timetuple())
# print("当前日期",today.strftime('%Y-%m-%d')) # 当前日期
# print("前3天日期",re_date.strftime('%Y-%m-%d')) # 前3天日期
file_name_rm = current_database_backup_path +'\\'+self.file_name
file_time = os.path.getmtime(file_name_rm) # 文件修改时间
timeArray = time.localtime(file_time) # 时间戳->结构化时间
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) #格式化时间
# print("文件修改时间",otherStyleTime)
if file_time <= re_date_unix:
# print(time2,' 文件名为:',self.file_name,' 已经超过3天,需要删除')
log_data7 = time2 + ' 文件名为:'+self.file_name+' 已经超过3天,需要删除'
print_data7 = time2 + ' 文件名为:'+self.file_name+' 已经超过3天,需要删除'
log_print(log_data7, print_data7)
#进行删除文件,未测试,等待测试,如需要删除,请取消下面的注释
os.remove(self.file_name)
else:
# print(time2,' 文件名为:',self.file_name," 未超过3天,无需处理!")
log_data8 = time2 + ' 文件名为:' + self.file_name + ' 未超过3天,无需处理!'
print_data8 = time2 + ' 文件名为:' + self.file_name + ' 未超过3天,无需处理!'
log_print(log_data8, print_data8)
#清理文件函数。里面调用了清理文件类
def rm_path_ls():
# path = os.getcwd()
path_ls = os.listdir(current_database_backup_path)
# print(path_ls)
for i in path_ls:
rm_file = ls_pwd(i,3)
rm_file.rm_backup()
else:
log_data6 = time2 + ' 此次备份已正常结束>>>>>>'
print_data6 = time2 + ' 此次备份已正常结束>>>>>>'
time.sleep(5)
log_print(log_data6, print_data6)
#日志文件判断
def path_txt_judge(txt):
if os.path.exists(txt):
print(time2, ' '+txt+'已存在,不需要创建')
file = open(current_log_path, 'a', encoding='utf-8')
# file.write('hello\nword')
a = str(time2 + " "+txt+"文件存在")
# print(a)
file.write(a + "\n")
file.close()
else:
file = open(txt, 'a', encoding='utf-8') # w 的含义为可进行读写
# file.write('hello\nword')
a1 = str(time2 + ' 创建'+txt+'文件' + current_log_path + '成功')
file.write(a1 + "\n")
file.close()
#判断配置文件
def path_ini_judge(ini):
if os.path.exists(ini):
print(time2, ' '+ini+'已存在,不需要创建')
file = open(current_log_path, 'a', encoding='utf-8')
# file.write('hello\nword')
a = str(time2 + " "+ini+"文件存在")
# print(a)
file.write(a + "\n")
file.close()
else:
file = open(current_config_path, 'w', encoding='utf-8') # w 的含义为可进行读写
# file.write('hello\nword')
b1 = str(time2 + ' 新建配置文件' + current_config_path + '成功,程序即将退出,请完善配置文件后再次运行该程序')
file.write('[rev_data]\nhost=\nport=\n')
file.close()
file = open(current_log_path, 'a', encoding='utf-8') # w 的含义为可进行读写
# file.write('hello\nword')
file.write(b1 + "\n")
file.close()
print(b1)
time.sleep(5)
exit(0)
#判断备份目录
def path_dir_judge(dir):
if os.path.exists(dir):
print(time2, ' 文件目录存在,不需要创建')
file = open(current_log_path, 'a', encoding='utf-8')
# file.write('hello\nword')
d = str(time2 + ' 备份目录' + current_database_backup_path + '存在')
file.write(d + "\n")
file.close()
else:
os.makedirs(dir)
file = open(current_log_path, 'a', encoding='utf-8') # w 的含义为可进行读写
# file.write('hello\nword')
d1 = str(time2 + ' 备份目录' + current_database_backup_path + '创建成功')
file.write(d1 + "\n")
file.close()
#日志和屏幕的打印
def log_print(log_txt,print_txt):
file = open(current_log_path, 'a', encoding='utf-8') # w 的含义为可进行读写
file.write(log_txt + "\n")
print(print_txt)
file.close()
#单纯的日志写入
def log_write(log):
file = open(current_log_path, 'a', encoding='utf-8') # w 的含义为可进行读写
file.write(log + "\n")
file.close()
#开始程序函数
def error_for_restart():
try:
rev = rev_data(database_host,database_port_plan,data_save_name)
rev.rev()
rm_path_ls()
except:
error_for_restart()
# 程序入口
##获取系统当前时间
time2 = (str(datetime.datetime.now())).split('.')[0]
##常用变量
current_path = os.getcwd()
current_config_path = current_path + '\\' + 'rev_config.ini'
current_log_path = current_path + '\\' + 'rev_log.txt'
current_database_backup_path = current_path + '\\' + 'database_save_backup'
#调用日志、配置文件以及备份目录函数
path_txt_judge(current_log_path)
path_ini_judge(current_config_path)
path_dir_judge(current_database_backup_path)
##提取配置文件里面的所填写的参数
cf= configparser.ConfigParser()
cf.read(current_config_path)
database_host = cf.get('rev_data','host')
database_port = cf.get('rev_data','port')
rev_time = cf.get('rev_data','rev_time')
database_port_plan = int(database_port)
##利用两个循环,进行定时任务的开启
while 2>1:
time1 = str(datetime.datetime.now())
time11 = time1.split('.')[0]
time3 = time11.split(' ')[0]
tim4 = time.strftime("%H:%M")
if tim4 == rev_time:
lock = 0
file = open(current_log_path, 'w', encoding='utf-8') #w,为重定向,即覆盖之前全部内容,确保日志文件不会太大
a1 = str(time2 + " 已清空"+time2+"之前所有日志")
file.write(a1 + "\n")
file.close()
while 2>1:
lock += 1
tim5 = time.strftime("%H:%M")
if lock == 1:
print(time2, ' 当前时间为备份时间,开始进行备份>>>>>>>')
data_save_name = current_database_backup_path + '\\' + time3 + '_' + database_host + '.bak'
error_for_restart()
elif tim5 != rev_time:
break
else:
print(time2, ' 当前时间为:', tim4, '开始备份时间为:', rev_time, '不是备份时间')
time.sleep(55)