Typecho博客代码、数据库数据备份

  • 需求:将typecho目录下的所有代码、文件夹进行每周备份
  • 思路:使用git工具,每周进行推送至git。

全局配置

配置git name、email
  594  root 2025/04/01 14:45:43 git config --global user.name "何忻宇"
  595  root 2025/04/01 14:45:43 git config --global user.email "17600160229@163.com"

推送博客网址代码至gitee

root@instance-nsstydow:~/python# cat  push-typecho-gitee.py
import os
import subprocess


def push_to_gitee(repo_url, directory):
    try:
        # 初始化 Git 仓库
        if not os.path.exists(os.path.join(directory, '.git')):
            subprocess.run(['git', 'init'], cwd=directory, check=True)

        # 添加所有文件
        subprocess.run(['git', 'add', '.'], cwd=directory, check=True)

        # 提交更改
        subprocess.run(['git', 'commit', '-m', 'Add all files'], cwd=directory, check=True)

        # 设置远程仓库
        remote_list = subprocess.run(['git', 'remote'], cwd=directory, capture_output=True, text=True).stdout.strip().split('\n')
        if 'origin' not in remote_list:
            subprocess.run(['git', 'remote', 'add', 'origin', repo_url], cwd=directory, check=True)
        else:
            subprocess.run(['git', 'remote', 'set-url', 'origin', repo_url], cwd=directory, check=True)

        # 强制推送至远程仓库,覆盖之前内容
        subprocess.run(['git', 'push', '-u', '--force', 'origin', 'master'], cwd=directory, check=True)

        print("文件成功推送至 Gitee 仓库!")
    except subprocess.CalledProcessError as e:
        print(f"执行 Git 命令时出错: {e}")
    except Exception as e:
        print(f"发生未知错误: {e}")


if __name__ == "__main__":
    repo_url = "https://gitee.com/*.git"
    directory = '/typecho_www/www/html/typecho/'  # 当前目录
    push_to_gitee(repo_url, directory)
  
root@instance-nsstydow:~/python#

定时job每周一次

root@instance-nsstydow:~/python# crontab -l |egrep -v "#|^&"
00 00 */7 * * python3 /root/python/push-typecho-gitee.py

image.png

正文到此结束
最后修改:2025 年 04 月 04 日
如果觉得我的文章对你有用,请随意赞赏