一、业务运用场景
很多时候,我们需要定期备份一些我们服务器上的文件并将文件上传到对应的云端,例如mysql数据备份文件,我们需要设置报自动备份后,再将文件同步到云端。
实现上面的业务场景有很多种方法,例如给mysql自动备份服务写上后置处理脚本,或者是使用同步软件检测我们的数据备份目录,虽然这些方式都能实现,但这里我将介绍一种通过python监控目录文件再使用git上传到git仓库的方法。
二、运用技术栈
- python3
- git
- git仓库(github或gitee)
- windows bat 自启动或者# Centos 自启动或nohup后台运行命令
三、安装python依赖包
主要依赖插件有watchdog
文件检测插件,gitpython
git操作插件
首先使用pip安装上面的两个依赖包,运行下列命令
pip3 install watchdoy
pip3 install gitpython
创建auto_up.py
文件,主要的python代码如下:
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\\"
# 需要检测的文件目录
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()
配置好需要检测的目录然后运行上面的auto_up.py文件,就可以进行文件夹监控了,当有文件增加删除或者修改的时候就会触发更新到指定的git仓库。
四、注意事项
- 上面的方法前提需要有一个git仓库,可以注册一个github或者gitee的仓库来使用。
- 建立好仓库后,建议使用ssh验证方式配置好需要使用git的服务器的秘钥方式。
- 当上述文件测试成功后,就需要使用方法将脚本常驻在后台,开机自启动等位置,达到重启服务器后会自动运行,windows上我这边主要使用的是开机自启动文件夹+bat文件操作,centos上主要使用的后端运行脚本命令,命令如下:。
nohup python3 -u auto_up.py > test.log 2>&1 &
总结
以上就是通过python
监控文件目录修改后自动提交到git仓库的方法,通过该方法我们可以备份很多不能丢失的文件到云端。