由于你使用的是 Debian 且有 root 权限,按照以下步骤操作:
1. 安装 Python 环境和库
pip3 install qbittorrent-api --break-system-packages
# 更新并安装 python3 和 pip
apt update && apt install -y python3-pip
# 安装 qBittorrent 官方 API 库
pip3 install qbittorrent-api
2. 创建并编辑脚本
我们对之前的脚本做一点增强优化,增加对 stalledDL(停滞下载)的判定:
mkdir /home/scripts && vim /home/scripts/qbt_cleaner.py
粘贴以下内容(请根据你的 qbt 修改账号密码):
import time
from qbittorrentapi import Client
# --- 配置区域 ---
QBT_HOST = '127.0.0.1'
QBT_PORT = 8080 # 你的 qbt 端口
QBT_USER = 'admin'
QBT_PASS = '123456'
# --- 规则定义 ---
CLEAN_TAG = '已整理' # MP 整理完成后打上的标签名称
BAD_EXTENSIONS = ('.iso', '.vob', '.ifo', '.bup', '.m2ts') # 修正了 m2ts 的小数点
# ----------------
def clean_qbt():
qbt_client = Client(host=QBT_HOST, port=QBT_PORT, username=QBT_USER, password=QBT_PASS)
try:
qbt_client.auth_log_in()
torrents = qbt_client.torrents_info()
for torrent in torrents:
# ========================================================
# 【优先逻辑】识别 MP 已整理标签,直接物理抹除(斩断重叠空间)
# ========================================================
# qBt 的 tags 字段返回的是逗号分隔的字符串,需切片精准比对
torrent_tags = [t.strip() for t in torrent.tags.split(',')] if torrent.tags else []
if CLEAN_TAG in torrent_tags:
print(f"[🔥 空间释放] 任务已整理,正在物理切除种源及文件: {torrent.name}")
qbt_client.torrents_delete(delete_files=True, torrent_hashes=torrent.hash)
continue # 功成身退,直接跳入下一个种子
# ========================================================
# 【常规巡检】以下逻辑保持不变,继续服务死种与格式剔除
# ========================================================
# 1. 逻辑:Tracker 报错清理 (针对死种)
trackers = qbt_client.torrents_trackers(torrent.hash)
all_failed = all(t.status == 4 for t in trackers if t.url.startswith(('http', 'udp')))
if all_failed and len(trackers) > 0:
print(f"[清理] Tracker 故障: {torrent.name}")
qbt_client.torrents_delete(delete_files=True, torrent_hashes=torrent.hash)
continue
# 2. 逻辑:识别原盘或 ISO 格式
files = qbt_client.torrents_files(torrent.hash)
is_bad_format = any(f.name.lower().endswith(BAD_EXTENSIONS) for f in files)
if is_bad_format:
print(f"[清理] 发现原盘/ISO 格式,正在剔除: {torrent.name}")
qbt_client.torrents_delete(delete_files=True, torrent_hashes=torrent.hash)
continue
# 3. 逻辑:0 速度停滞清理 (stalledDL)
if torrent.state == 'stalledDL' and torrent.dlspeed == 0:
print(f"[清理] 停滞无速度: {torrent.name}")
qbt_client.torrents_delete(delete_files=True, torrent_hashes=torrent.hash)
except Exception as e:
print(f"发生错误: {e}")
if __name__ == "__main__":
clean_qbt()
3. 测试运行
ython3 /home/scripts/qbt_cleaner.py
查看输出,看它是否能识别并删除你 qbt 里那些卡住的任务。
4. 设置定时任务(每 10 分钟自动清理一次)
crontab -e
添加一行:
*/10 * * * * /usr/bin/python3 /home/scripts/qbt_cleaner.py >> /var/log/qbt_clean.log 2>&1
