1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
| from hashlib import sha1 import hmac import time from matplotlib.lines import Line2D import requests import json import urllib from dotenv import load_dotenv import os import sys import matplotlib
matplotlib.use('TkAgg') import json import matplotlib.pyplot as plt import numpy as np from datetime import datetime, timedelta import matplotlib.dates as mdates import tkinter as tk from tkinter import ttk plt.rcParams['font.sans-serif'] = ['SimHei'] animation_chars = ["/", "|", "\\", "-"]
load_dotenv() def dogecloud_api(api_path, data={}, json_mode=False): access_key = os.getenv("ACCESS_KEY") secret_key = os.getenv("SECRET_KEY") body = '' mime = '' if json_mode: body = json.dumps(data) mime = 'application/json' else: body = urllib.parse.urlencode(data) mime = 'application/x-www-form-urlencoded' sign_str = api_path + "\n" + body signed_data = hmac.new(secret_key.encode('utf-8'), sign_str.encode('utf-8'), sha1) sign = signed_data.digest().hex() authorization = 'TOKEN ' + access_key + ':' + sign response = requests.post('https://api.dogecloud.com' + api_path, data=body, headers = { 'Authorization': authorization, 'Content-Type': mime }) return response.json()
def get_js_list(): api = dogecloud_api('/cdn/domain/list.json') if api['code'] == 200: for domain in api['data']['domains']: print(domain) return api['data']['domains'] else: print("api failed: " + api['msg'])
def stop_js(domain): api = dogecloud_api('/cdn/domain/offline.json', { 'domain': domain }) return api['code']
def enable_js(domain): api = dogecloud_api('/cdn/domain/online.json', { 'domain': domain }) return api['code']
def get_ssl(): api = dogecloud_api('/cdn/cert/list.json') if api['code'] == 200: return api['data']['certs'] else: print("api failed: " + api['msg'])
def updata_ssl(note,cert,private,domain=os.getenv("DOMAIN")): cert_path=f"pem/{cert}" with open(cert_path,mode='r') as f: cert=f.read() private_path=f"pem/{private}" with open(private_path,mode='r') as f: private=f.read() api = dogecloud_api('/cdn/cert/upload.json', { "note": note, "cert": cert, "private": private }) if api['code'] == 200: print("---上传成功") if domain is not None: bind_ssl(domain,api['data']['id']) print("---绑定成功") else: print("为检测到.env文件内的DOMAIN") else: print("api failed: " + api['msg'])
def bind_ssl(id,domain=os.getenv("DOMAIN")): api = dogecloud_api(f'/cdn/domain/config.json?domain={domain}', { 'cert_id': id }, True) if api['code']== 200: print("绑定成功") else: print(api['msg'])
def refresh_pre(path): animation_index=0 url_list=[path] api = dogecloud_api('/cdn/refresh/add.json', { 'rtype': 'prefetch', 'urls': json.dumps(url_list) }) if api['code'] == 200: id=api['data']['task_id'] print("预热id",id) print("现在开始预热") while True: code = get_pre(id)["percent"] time.sleep(1) print(f"\r正在加载... {animation_chars[animation_index]}{code}%", end="", flush=True) animation_index = (animation_index + 1) % len(animation_chars) if code == 100: print("\r刷新完成!") break print("预热完成") else: print("api failed: " + api['msg'])
def refresh_url(path): animation_index = 0 url_list=[path] api = dogecloud_api('/cdn/refresh/add.json', { 'rtype': 'url', 'urls': json.dumps(url_list) }) if api['code'] == 200: print("URL刷新ID:",api['data']['task_id']) id=api['data']['task_id'] print("\n开始URL刷新") while True: print(f"\r正在加载... {animation_chars[animation_index]}{code}%", end="", flush=True) animation_index = (animation_index + 1) % len(animation_chars) time.sleep(1) code = get_pre(id)["percent"]
if code == 100: print("\r刷新完成!") break print("刷新完成,现在开始预热") refresh_pre(path) else: print("api failed: " + api['msg'])
def refresh_menu(*custom_urls): if not custom_urls: default_domain = os.getenv("DOMAIN") if not default_domain: raise ValueError("环境变量 DOMAIN 未设置,且未传入自定义URL") url_list = [f"https://{default_domain}"] else: url_list = custom_urls api = dogecloud_api('/cdn/refresh/add.json', { 'rtype': 'path', 'urls': json.dumps(url_list) }) animation_index=0 if api['code'] == 200: print(f"刷新任务提交成功,任务ID: {api['data']['task_id']}") id=api['data']['task_id'] print("\n开始目录刷新") a=0 while True: code = get_pre(id)["percent"] time.sleep(5) print(f"\r正在加载... {animation_chars[animation_index]}{code}%", end="", flush=True) animation_index = (animation_index + 1) % len(animation_chars) if code == 100: a+=1 if a==2: print("\r刷新完成!") break
else: print(f"API调用失败: {api['msg']}")
def get_pre(id): api = dogecloud_api(f'/cdn/refresh/query.json?id={id}') if api['code'] == 200: return api['data']['tasks'][0] else: print("api failed: " + api['msg'])
def get_traffic_data(start=datetime.now().date()- timedelta(days=1), end=datetime.now().date(), domain=os.getenv("DOMAIN")): api = dogecloud_api(f'/cdn/stat/traffic.json?start_date={start}&end_date={end}&granularity=hour&area=china&domains={domain}') if api['code'] == 200: print(api['data']['result'][0]) plt.rcParams['axes.unicode_minus'] = False
def plot_traffic_bar(api_data): """绘制流量柱状图(全屏居中版本)""" start_timestamp = api_data['start'] traffic_data = api_data['data'] base_time = datetime.fromtimestamp(start_timestamp) hours = [base_time + timedelta(hours=i) for i in range(len(traffic_data))]
max_traffic = max(traffic_data) unit = 'B' divisor = 1 if max_traffic > 1024**3: unit = 'GB' divisor = 1024**3 elif max_traffic > 1024**2: unit = 'MB' divisor = 1024**2 elif max_traffic > 1024: unit = 'KB' divisor = 1024
root = tk.Tk() root.title("流量统计图表") screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() window_width = int(screen_width * 0.9) window_height = int(screen_height * 0.8) x = (screen_width - window_width) // 2 y = (screen_height - window_height) // 2 root.geometry(f"{window_width}x{window_height}+{x}+{y}") root.attributes('-topmost', True) fig = plt.figure(figsize=(16, 8), dpi=100) canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(fig, master=root) canvas.draw() toolbar = ttk.Frame(root) toolbar_nav = ttk.Frame(toolbar) ttk.Button(toolbar_nav, text="保存", command=lambda: fig.savefig('traffic_fullscreen.png')).pack(side=tk.LEFT, padx=2) ttk.Button(toolbar_nav, text="关闭", command=root.destroy).pack(side=tk.LEFT, padx=2) toolbar_nav.pack(side=tk.TOP, fill=tk.X) canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) toolbar.pack(side=tk.BOTTOM, fill=tk.X)
plt.clf() converted_traffic = [x / divisor for x in traffic_data] plt.clf() bars = plt.bar( hours, converted_traffic, color='steelblue', edgecolor='white', width=0.03 ) plt.ylabel(f'流量 ({unit})', fontsize=12) for bar in bars: height = bar.get_height() plt.text( bar.get_x() + bar.get_width()/2, height + 0.1 if height < 350 else height*1.01, f'{height:.1f} {unit}', ha='center', va='bottom', fontsize=10 )
plt.title(f'{api_data["date"]} 域名流量分布', fontsize=16, pad=30) plt.xlabel('时间', fontsize=14) plt.grid(axis='y', linestyle='--', alpha=0.7) plt.gcf().autofmt_xdate() plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.gca().xaxis.set_major_locator(mdates.HourLocator(interval=2)) plt.tight_layout(pad=2.0)
canvas.draw() def on_close(): root.destroy() sys.exit(0) root.protocol("WM_DELETE_WINDOW", on_close) root.mainloop() plot_traffic_bar(api['data']['result'][0]) else: print("api failed: " + api['msg'])
def get_request(start=datetime.now().date()- timedelta(days=1), end=datetime.now().date(), domain=os.getenv("DOMAIN")): api = dogecloud_api(f'/cdn/stat/request.json?start_date={start}&end_date={end}&granularity=hour&area=china&domains={domain}') if api['code'] == 200: print(api['data']['result']) def plot_cdn_requests(api_response): if api_response.get("code") != 200: print("API Failed:", api_response.get("msg", "Unknown error")) return results = api_response["data"]["result"] if not results: print("No data available.") return plt.figure(figsize=(12, 6)) colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] markers = ['o', 's', '^', 'v', '<', '>', 'x'] for idx, day_data in enumerate(results): date = day_data["date"] requests = day_data["data"] hours = range(len(requests)) color = colors[idx % len(colors)] marker = markers[idx % len(markers)] plt.plot(hours, requests, marker=marker, linestyle='-', color=color, label=date) for h, req in zip(hours, requests): offset = 5 if idx == 0 else -5 plt.text(h, req + offset, str(req), ha='center', va='bottom', fontsize=8, color=color) plt.title('请求数变化趋势(每小时)') plt.xlabel('小时(0-23)') plt.ylabel('请求数') plt.xticks(range(24), [f"{h:02d}:00" for h in range(24)], rotation=45) legend_elements = [ Line2D([0], [0], marker=markers[i], color=colors[i], label=day["date"]) for i, day in enumerate(results) ] plt.legend(handles=legend_elements) plt.grid(True, linestyle='--', alpha=0.5) plt.tight_layout() plt.show() plot_cdn_requests(api) else: print("api failed: " + api['msg'])
def get_domain_id(domain=None): result=get_js_list() if domain is None: id=list(filter(lambda item:item.get("name")==os.getenv("DOMAIN"),result))[0].get("id") else: id=list(filter(lambda item:item.get("name")==domain,result))[0].get("id") return id
def down_log(id=None,date=None): if id is None or date is None: id=get_domain_id() date=datetime.now().date() api = dogecloud_api(f'/cdn/log/list.json?id={id}&date={date}') if api['code'] == 200: path=f"log/{date}.json" os.makedirs(os.path.dirname(path), exist_ok=True) with open(path,mode='w',encoding='utf-8') as f: json.dump(api['data']['log_list'], f, indent=4, ensure_ascii=False) print("下载完成,路径为",path) else: print("api failed: " + api['msg'])
def cg(id): default_domain = os.getenv("DOMAIN") default_articles=os.getenv("ARTICLES_PATH") if not default_domain or not default_articles: raise ValueError("环境变量 DOMAIN 未设置,未传入自定义URL") else: url = f"https://{default_domain}{default_articles}{id}.html" refresh_url(url)
"重新绑定多吉云的证书" def bind_djy(): ssls=get_ssl() current_time = int(time.time()) valid_certs = [cert for cert in ssls if cert['expire'] > current_time] if not valid_certs: raise ValueError("没有未过期的证书!") longest_valid_cert = max(valid_certs, key=lambda x: x['expire']) id=longest_valid_cert.get("id") print("未过期的证书列表:", valid_certs) print("剩余有效期最长的证书ID:", id) bind_ssl(id) def show_help(): commands = [ ("get_js_list", "获取加速域名列表"), ("stop_js <域名>", "停用加速域名"), ("enable_js <域名>", "启用加速域名"), ("get_ssl", "获取证书列表"), ("updata_ssl <证书名> <cert文件名> <private文件名> <域名(可选)>", "上传证书(传入域名自动绑定)"), ("bind_ssl <域名> <证书ID>", "绑定证书到域名"), ("djy bind", "一键绑定时间最长的证书"), ("refresh_pre <URL>", "URL预热"), ("refresh_url <URL>", "URL刷新"), ("refresh_menu", "目录刷新"), ("cg abblink", "文章刷新"), ("get_pre <任务ID>", "查询预热任务"), ("get_traffic_data <开始> <结束> <域名>", "获取流量数据"), ("get_request <开始> <结束> <域名>", "查询请求数"), ("down_log <域名id> <日期>", "下载离线日志"), ] max_cmd_len = max(len(cmd[0]) for cmd in commands) print("多吉云 CDN 管理工具命令列表:\n") print("-" * 60) for cmd, desc in commands: print(f"{cmd.ljust(max_cmd_len + 2)} {desc}") print("-" * 60) if __name__ == "__main__": if len(sys.argv) < 2: show_help() sys.exit(1) func_name = sys.argv[1] args = sys.argv[2:] try: if func_name == "get_js_list": get_js_list() elif func_name == "stop_js": if len(args) < 1: raise ValueError("缺少域名参数") stop_js(args[0]) elif func_name == "enable_js": if len(args) < 1: raise ValueError("缺少域名参数") enable_js(args[0]) elif func_name == "get_ssl": get_ssl() elif func_name == "updata_ssl": if len(args) < 3: raise ValueError("缺少必要参数:需要至少 3 个参数(cert_name, cert_path, private_key_path)") elif len(args) == 3: updata_ssl(args[0], args[1], args[2]) else: updata_ssl(args[0], args[1], args[2],args[3]) elif func_name == "bind_ssl": if len(args) < 2: raise ValueError("缺少域名或证书ID参数") bind_ssl(args[0], args[1]) elif func_name == "refresh_pre": if len(args) < 1: raise ValueError("缺少URL列表参数") refresh_pre(*args) elif func_name == "refresh_url": if len(args) < 1: raise ValueError("缺少URL列表参数") refresh_url(*args) elif func_name == "refresh_menu": refresh_menu(*args) elif func_name == "get_pre": if len(args) < 1: raise ValueError("缺少任务ID参数") get_pre(args[0]) elif func_name == "get_traffic_data": if len(args) < 3: get_traffic_data()
get_traffic_data(args[0], args[1], args[2]) elif func_name == "get_request": if len(args) < 3: get_request() else: get_request(args[0], args[1], args[2]) elif func_name == "down_log": down_log(*args) elif func_name == "bind_djy": bind_djy() elif func_name =="cg": if len(args) < 1: raise ValueError("缺少文章abbrlink") else: cg(args[0]) else: print(f"未知命令:{func_name}") show_help() except Exception as e: print(f"执行出错:{str(e)}") sys.exit(1)
|