Linux系统下每日自动推送GIT更新
1、添加SSH凭证
1.1 创建无密码的 SSH 密钥对
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
将"your_email@example.com"替换为您的GitHub邮箱。
1.2 将新的公钥添加到 GitHub
vi ~/.ssh/id_rsa.pub
将此密钥复制到GitHub的SSH管理设置中。
1.3 配置 Git 使用 SSH
如果您已有一个仓库,您需要确保 Git 使用 SSH 而非 HTTPS 连接到 GitHub。检查当前的远程仓库设置:
git remote -v
git remote set-url origin git@github.com:username/repository.git
确保将 username 和 repository 替换为您的 GitHub 用户名和仓库名。
1.4 测试连接
执行以下命令来测试 SSH 连接:
ssh -T git@github.com
如果是第一次连接到 GitHub,可能会看到一个关于主机身份的警告。输入 "yes" 继续。如果一切设置正确,您将看到一条欢迎消息。.
2、编写脚本
根据自己需求更改脚本操作。
import subprocess
import datetime
import os
# 指定文件路径,这里使用相对路径,基于仓库的根目录
file_path = 'path/to/your/file.txt'
# 指定 Git 仓库的绝对目录路径
repo_path = '/absolute/path/to/your/git/repo'
# 指定分支名称
branch_name = 'main'
# 切换到仓库目录
os.chdir(repo_path)
# 写入当前日期到指定文件
current_date = datetime.datetime.now().strftime('%Y-%m-%d')
with open(file_path, 'a+') as file: # 'a' 模式为追加模式
file.write(f'{current_date}\n')
# Git 添加文件更改
subprocess.run(['git', 'add', file_path], check=True)
# Git 提交更改
commit_message = f'Update file with current date {current_date}'
subprocess.run(['git', 'commit', '-m', commit_message], check=True)
# Git 推送到远程仓库的特定分支
subprocess.run(['git', 'push', 'origin', branch_name], check=True)
3、创建CRON脚本
为了自动化这个脚本每天执行,您可以将它添加到 cron 作业中。在 Linux 系统中,您可以通过运行 crontab -e 命令并添加如下行来实现:
0 0 * * * /usr/bin/python3 /path/to/your/script.py
按自己需求更改时间。