type -a btstatus
#!/usr/bin/env python3
import urllib.request
import urllib.parse
import http.cookiejar
import json
import getpass
import sys
BASE = "http://127.0.0.1:8080"
def size(n):
n = float(n)
for unit in ["B", "KB", "MB", "GB", "TB"]:
if n < 1024 or unit == "TB":
return f"{n:.2f} {unit}"
n /= 1024
username = "admin"
password = getpass.getpass("qBittorrent 密码: ")
cookies = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(cookies)
)
def request(path, data=None):
headers = {"Referer": BASE + "/"}
body = urllib.parse.urlencode(data).encode() if data else None
req = urllib.request.Request(BASE + path, data=body, headers=headers)
return opener.open(req, timeout=10).read()
try:
result = request("/api/v2/auth/login", {
"username": username,
"password": password
}).decode()
if result.strip() != "Ok.":
print("登录失败:请检查用户名或密码。")
sys.exit(1)
torrents = json.loads(request("/api/v2/torrents/info"))
if not torrents:
print("当前没有下载任务。")
sys.exit(0)
print()
print(f"当前任务数:{len(torrents)}")
print("=" * 90)
for t in torrents:
print(f"任务:{t['name']}")
print(f"进度:{t['progress'] * 100:.2f}%")
print(f"状态:{t['state']}")
print(f"已下载:{size(t['downloaded'])} / {size(t['size'])}")
print(f"剩余:{size(t['amount_left'])}")
print(f"下载速度:{size(t['dlspeed'])}/s")
print(f"上传速度:{size(t['upspeed'])}/s")
eta = t['eta']
print("预计剩余时间:" + ("未知" if eta < 0 else f"{eta // 3600}小时{eta % 3600 // 60}分钟"))
print("-" * 90)
except Exception as e:
print(f"查询失败:{e}")
sys.exit(1)