使用clash-api自动切换节点

你知唔知我系靓仔

使用clash-api自动切换节点

最近在做自动化测试的时候经常因为ip被拦截,但是某些代理服务在国内的大环境下作用有限,所以使用clash来做ip管理。

以下程序修改自这位老哥 https://github.com/allen746/auto_change_clash_proxy

访问changeip路由即可更换ip

import requests
import random
from flask import Flask, jsonify

app = Flask(__name__)

# Define your configuration variables here
clash_api_port = 'YOUR_CLASH_API_PORT'
clash_api_secret = 'YOUR_CLASH_API_SECRET'
clash_api_selector = 'YOUR_CLASH_API_SELECTOR'

headers_secret = {
    'Authorization': 'Bearer {}'.format(clash_api_secret)
}

url_all_proxies_info = 'http://localhost:{}/proxies'.format(clash_api_port)
url_all_proxies_info = requests.get(url_all_proxies_info, headers=headers_secret).json()
url_all_proxies = 'http://localhost:{}/proxies/{}'.format(clash_api_port, clash_api_selector)

def change_proxy():
    res_proxies = requests.get(url_all_proxies, headers=headers_secret).json()
    now_proxy = res_proxies['now']
    proxy_name_list = res_proxies['all'][3:-3]

    if now_proxy not in ['DIRECT', 'REJECT']:
        proxy_name_list.remove(now_proxy)

    while True:
        random_proxy = random.choice(proxy_name_list)
        delay = url_all_proxies_info['proxies'][random_proxy]['history'][-1]['delay']
        if delay != 0:
            break

    data = {
        "name": random_proxy
    }
    headers = {
        "content-type": "application/json",
        'Authorization': 'Bearer {}'.format(clash_api_secret)
    }

    res = requests.put(url=url_all_proxies, json=data, headers=headers)
    return random_proxy, res.status_code

@app.route('/changeip', methods=['GET'])
def change_ip():
    random_proxy, status_code = change_proxy()
    if status_code == 204:
        response = {
            'status': 'success',
            'message': 'Proxy changed successfully',
            'new_proxy': random_proxy
        }
        return jsonify(response), 200
    else:
        response = {
            'status': 'error',
            'message': 'Failed to change proxy'
        }
        return jsonify(response), 500

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)