How to update config yaml on docker based clash?

how to update config yaml on docker based clash

本文教你如何更新docker based clash中的config.yaml文件,主要使用python/ruamel.yaml。

TABLE OF CONTENT


SSH到服务器

首先我们需要通过ssh登录到服务器上,我是在qnap nas上安装的clash docker,具体可以参见这篇文章

找到Config.yaml的位置

这篇文章中我们讲解了如何在qnap上安装clash docker,我是将config.yaml挂载在NAS的/share/Container/clash目录下。

下载python依赖包

$ pip3 install ruamel.yaml 

编写python更新脚本

注意把:suwa_url,clash_ip,config_path替换成你正确的信息

在config.yaml所在目录下/share/Container/clash,创建update.py文件。

from ruamel import yaml
import requests
import os
import sys

suwa_url = '#你的订阅地址#'
clash_ip = '#你的clash ip#'
config_path = '#你的clash config.yaml所在目录#'
#suwa_url = 'https://*********'
#clash_ip = '192.168.1.2'
#config_path = '/share/Container/clash/'

old_conf_path = config_path + 'config.yaml'
tmp_conf_path = config_path + 'new.yaml'
new_conf_path = config_path + 'config_new.yaml'
old_conf_bakpath = config_path + 'conf/'
conf_url = 'http://' + clash_ip + ':9090/configs'

# 从订阅地址下载config.yaml
wget_cmd = 'wget ' + suwa_url + ' -e use_proxy=yes -e https_proxy='+ clash_ip +':7890 -O ' + tmp_conf_path
try:
    os.system(wget_cmd)
except Exception as err:
    print(err)
    sys.exit()

# 替换proxies
with open(tmp_conf_path) as newfile:
    newdata = yaml.load(newfile,Loader=yaml.RoundTripLoader)
with open(old_conf_path) as oldfile:
    olddata = yaml.load(oldfile,Loader=yaml.RoundTripLoader)

olddata['proxies'] = newdata['proxies']
olddata['proxy-groups'] = newdata['proxy-groups']
with open(new_conf_path, 'w') as ofile:
    yaml.dump(olddata, ofile, default_flow_style=False, encoding='utf-8', allow_unicode=True, per=yaml.RoundTripDumper)
print('replace proxy')

# 备份旧配置文件
os.system('mv ' + old_conf_path + ' ' + old_conf_bakpath)
os.system('rm -f ' + tmp_conf_path)
os.system('mv ' + new_conf_path + ' ' + old_conf_path)
print('moving files')

# curl更新
requests.put(conf_url, json={})
print('update finish')

执行更新脚本

$ python3 update.py

Post a Comment

0 Comments