前言背景
1、主要是突然有一个需要实时备份数据库文件,防止数据丢失的需求,思前想后,发现存在很多方式,例如备份在自己的其他服务器,备份在本地等,最终决定编写一个python脚本用来判断数据库备份文件夹文编改动后通过git提交到github或者gitee
代码
from watchdog.observers import Observer
from watchdog.events import *
import time
from git import Repo
import os
def pushgit(ccpath):
if(".git" in ccpath):
print(1);
else:
try:
dirfile = "C:\\Users\\Administrator\\Documents\\Navicat\\MySQL\\servers\\127.0.0.1\\ddh\\" # code的文件位置,我默认将其存放在根目录下
repo = Repo(dirfile)
g = repo.git
g.add("--all")
g.commit("-m auto update")
g.push()
print("Successful push!")
except :
print("error push!")
class FileEventHandler(FileSystemEventHandler):
def __init__(self):
FileSystemEventHandler.__init__(self)
def on_moved(self, event):
pushgit(event.src_path)
if event.is_directory:
print("directory moved from {0} to {1}".format(event.src_path,event.dest_path))
else:
print("file moved from {0} to {1}".format(event.src_path,event.dest_path))
def on_created(self, event):
pushgit(event.src_path)
if event.is_directory:
print("directory created:{0}".format(event.src_path))
else:
print("file created:{0}".format(event.src_path))
def on_deleted(self, event):
pushgit(event.src_path)
if event.is_directory:
print("directory deleted:{0}".format(event.src_path))
else:
print("file deleted:{0}".format(event.src_path))
def on_modified(self, event):
pushgit(event.src_path)
if event.is_directory:
print("directory modified:{0}".format(event.src_path))
else:
print("file modified:{0}".format(event.src_path))
if __name__ == "__main__":
observer = Observer()
event_handler = FileEventHandler()
observer.schedule(event_handler,"C:\\Users\\Administrator\\Documents\\Navicat\\MySQL\\servers\\127.0.0.1\\ddh\\",True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
centos7 后端运行脚本命令
nohup python3 -u auto_up.py > test.log 2>&1 &
写好脚本文件中,将脚本文件加入到开机自动运行里就可以监控更新了。
然后如果是备份数据库,则只需要创建数据库自动备份计划,就可以完成了。
评论