分页: 1 / 1

Python脚本打包备份文件夹到腾讯云对象存储

发表于 : 周日 12月 24, 2023 14:10
DT27
来源:https://github.com/forecho/backup-to-cloud-storage
腾讯云存储:https://console.cloud.tencent.com/cos
腾讯云密钥:https://console.cloud.tencent.com/cam/capi
前提:
sudo apt-get install python3 python3-pip -y
pip3 install pyyaml
pip3 install cos-python-sdk-v5 # tencent cos
Python脚本backup.py:

代码: 全选

# !/usr/bin/python3
# -*- coding: utf-8 -*-
import datetime
import yaml
import os
import subprocess

def cfg(key):
    current_path = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(current_path, 'backup.config.yaml'), 'r') as f:
        config = yaml.safe_load(f)
    try:
        value = config[key]
    except KeyError:
        raise KeyError('Config key "{}" not found!'.format(key))
    if value is None:
        return ''
    return value

def main():

    print('Zipping...')
    backup_name = '{}-backup-{}.zip'.format(cfg('backup')['name'], datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
    backup_path = '{}/{}'.format(cfg('backup')['dir'], backup_name)
    backup_src = cfg('backup')['src']
    os.system('mkdir {}'.format(cfg('backup')['dir']))
    os.system('zip -qr {} {}'.format(backup_path, backup_src))
    print('Zipping done!')

    # upload
    print('Uploading...')

    from qcloud_cos import CosConfig
    from qcloud_cos import CosS3Client
    config = CosConfig(Region=cfg('cos')['region'], SecretId=cfg('cos')['secret_id'], SecretKey=cfg('cos')['secret_key'])
    client = CosS3Client(config)
    client.put_object_from_local_file(
        Bucket=cfg('cos')['bucket'],
        LocalFilePath=backup_path,
        Key=backup_name,
    )

    print('Cleaning...')
    subprocess.call(['rm', '-rf', cfg('backup')['dir']])

if __name__ == '__main__':
    main()
配置文件backup.config.yaml:

代码: 全选

backup:
    driver: cos
    name: domoticz-cos
    # backup multiple directory
    src: /root/domoticz
    dir: /tmp/backup

cos:
    secret_id: *******************************
    secret_key: *******************************
    region: ap-hongkong
    bucket: btbak-hk-1306214329

设置每天执行一次:
crontab -e

代码: 全选

5 2 * * * sudo python3 /root/domoticz/config/backup.py