声明:本文转载自:https://www.jiewen.run
首先,我们想要把备份上传到阿里云盘,就要用到一个可玩性很高的python库:aligo,这也是我们这个脚本的核心。
下面通过备份Halo博客
作为示例,直接看代码
import base64
import time
import requests
import json
from datetime import datetime
from aligo import Aligo
# 网站地址
website = "https://halo.wyong.fun"
# halo2备份文件夹路径
backup_halo_path = "/root/.halo/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 = "650fcd6345b746c5d582467ab8a6ba34ec2c5a7a"
user = "admin"
password = "P@88w0rd"
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(f"备份请求失败!错误代码:{response.status_code}")
代码很简单,就是请求Halo
备份的api
然后利用aligo
把备份的压缩包上传到阿里云盘。
这里提一下几个,要修改的参数
website
你的网站地址,不要带结尾反斜杠backup_halo_path
你Halo备份的目录ali_folder
你要备份到的阿里云网盘目录ID(网页进入目录后有)user
你Halo的账号password
你Halo的密码
到这里正文也就结束了,剩下的就是部署到你的服务器
安装好python环境,这里不多说。注意的是aligo需要3.7及以上版本
。
然后pip 安装依赖,requests
和aligo
,我这里安装的时候说找不到,就直接去github下载whl
包然后运行pip3 install *.whl安装。
然后执行测试下python3 main.py
,首次执行需要扫码登入,登录成功就会开始执行备份。
评论区