引言:
无意间看到一个文章可以用写脚本进行自动备份,我也想搞一个
一、创建脚本
主脚本main.py内容如下:
import base64
import time
import requests
import json
from datetime import datetime
from aligo import Aligo
# 网站地址 自行修改
website = "http://localhost:8090"
# halo2备份文件夹路径 自行修改
backup_halo_path = "/opt/halo/halo2/backups"
backup_api = website + "/apis/migration.halo.run/v1alpha1/backups"
check_api = website + "/apis/migration.halo.run/v1alpha1/backups?sort=metadata.creationTimestamp%2Cdesc"
# 要备份的阿里云盘文件夹ID 自行修改
ali_folder = "########"
#halo的用户名 自行修改
user = "useruser"
#halo的密码 自行修改
password = "pwdpwd"
def get_access_token(refresh_token):
url = "https://auth.aliyundrive.com/v2/account/token"
headers = {"Content-Type": "application/json"}
data = {
"grant_type": "refresh_token",
"refresh_token": refresh_token
}
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
return response.json()["access_token"]
else:
raise Exception(f"Failed to get access token: {response.text}")
def upload_file(access_token, local_file_path, remote_parent_file_id="root"):
# 获取文件信息
url = "https://api.aliyundrive.com/adrive/v3/file/get_upload_info"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
data = {
"parent_file_id": remote_parent_file_id,
"name": local_file_path.split('/')[-1],
"check_name_mode": "refuse"
}
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
upload_info = response.json()
upload_id = upload_info["upload_id"]
upload_url = upload_info["upload_url"]
# 上传文件
with open(local_file_path, "rb") as file:
files = {"file": (local_file_path.split('/')[-1], file)}
response = requests.post(upload_url, files=files)
if response.status_code == 200:
print("File uploaded successfully.")
else:
print(f"Failed to upload file: {response.text}")
else:
print(f"Failed to get upload info: {response.text}")
ali = Aligo()
# 获取现在的时间 2023-09-24T13:14:18.650Z
now_time = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
print(now_time)
# 构建认证头部
auth_header = "Basic " + base64.b64encode((user + ":" + password).encode()).decode()
payload = json.dumps({
"apiVersion": "migration.halo.run/v1alpha1",
"kind": "Backup",
"metadata": {
"generateName": "backup-",
"name": ""
},
"spec": {
"expiresAt": now_time,
}
})
headers = {
'User-Agent': '',
'Content-Type': 'application/json',
'Authorization': "Basic " + base64.b64encode((user + ":" + password).encode()).decode(),
}
response = requests.request("POST", backup_api, headers=headers, data=payload)
print(response.text)
if response.status_code == 201:
print("备份请求成功!")
new_backup_name = ""
while True:
check_response = requests.request("GET", check_api, headers=headers)
if check_response.status_code == 200:
backup_data = json.loads(check_response.text)
items = backup_data.get("items", [])
if items[0]["status"]["phase"] == "SUCCEEDED":
print("备份完成!")
new_backup_name = items[0]["status"]["filename"]
break
if items[0]["status"]["phase"] == "RUNNING":
print("正在备份!")
time.sleep(10)
else:
print(f"查询备份请求失败!错误代码:{check_response.status_code}")
ali.upload_file(backup_halo_path + "/" + new_backup_name,
parent_file_id=ali_folder)
print("阿里云盘上传完成!")
else:
print("备份请求失败!错误代码:{response.status_code}")
先修改脚本里面的变量,都在最上面
二、安装软件
首先这个脚本是依赖python的,要检测下有没有安装,没有自行安装
安装aligo
在github中下载了最新版本release的文件 aligo-6.2.4-py3-none-any.whl
执行命令
pip3 install *.whl
三、在阿里云盘创建一个文件夹
要点是要在全部文件->备份文件 里面创建文件夹,进入文件夹后url上的id就是文件夹id
修改脚本里面的变量,程序目录、文件夹id、用户密码
四、创建定时任务
打开终端。
输入
crontab -e
命令来编辑cron表。添加一行来定义新的任务。
0 1 * * * python3 /opt/halo/main.py
保存退出
查看是否已经存在
crontab -l
五、先执行一次看看
执行主脚本main.py
如果没有权限先授权
$ sudo chmod +x /opt/halo/main.py
执行 python3 main.py
第一次运行会扫描登录
执行结果如下:
备份请求成功!
正在备份!
正在备份!
备份完成!
16:03:42.046 aligo.INFO 开始上传文件 /opt/halo/halo2/backups/20240811160316-backup-KIizo.zip
16:03:42.443 aligo.INFO POST https://api.aliyundrive.com/adrive/v2/file/createWithFolders 201 18152
100%|
79.3M/79.3M [03:07 00:00, 422kB/s]
16:06:50.669 aligo.INFO POST https://api.aliyundrive.com/v2/file/complete 200 1229
16:06:50.669 aligo.INFO 文件上传完成 /opt/halo/halo2/backups/20240811160316-backup-KIizo.zip
阿里云盘上传完成!
完美!后续就是观察定时任务是否正常执行就可以了。
第二天补充:
第二天进入阿里云盘,已经产生了一个新的备份文件,定时任务工作正常。
评论区