import os
import subprocess
import sys
import time
import ctypes
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QVBoxLayout, QWidget, QLabel, QMessageBox,
QProgressBar)
from PyQt5.QtCore import Qt
class CleanupTool(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle(" Windows系统清理工具")
self.setGeometry(100, 100, 650, 550) # 调整窗口大小适应新内容
self.is_admin = self.check_admin()
self.cleaned_items = 0 # 清理项计数器
self.init_ui()
def init_ui(self):
main_widget = QWidget()
layout = QVBoxLayout()
# 标题
title = QLabel("????? Windows 系统深度清理工具 ????")
title.setStyleSheet("font-size: 22px; font-weight: bold; color: #2c3e50;")
title.setAlignment(Qt.AlignCenter)
layout.addWidget(title)
# 权限状态
admin_status = QLabel()
if self.is_admin:
admin_status.setText("? 管理员权限已获取 (可执行完整清理)")
admin_status.setStyleSheet("color: #27ae60; font-weight: bold;")
else:
admin_status.setText("?? 警告: 部分功能需要管理员权限")
admin_status.setStyleSheet("color: #e74c3c; font-weight: bold;")
admin_status.setAlignment(Qt.AlignCenter)
layout.addWidget(admin_status)
# 进度条
self.progress = QProgressBar()
self.progress.setAlignment(Qt.AlignCenter)
layout.addWidget(self.progress)
# 功能按钮
buttons = [
("???? 清理临时文件 (推荐)", self.clean_temp_files),
("????? 强制清空回收站", self.empty_recycle_bin),
("???? 清除浏览器缓存 (Chrome/Edge/Firefox)", self.clean_browser_cache),
("???? 深度清理Windows更新残留", self.clean_windows_update_cache),
("???? 删除系统旧版本备份 (Windows.old)", self.clean_windows_backup),
("???? 清除系统日志和错误报告", self.clean_log_files),
("????? 清理Defender防病毒垃圾", self.clean_defender_files),
("???? 清理IIS网站日志 (服务器专用)", self.clean_iis_logs),
("???? 删除休眠文件 (hiberfil.sys)", self.clean_hibernation_files),
("???? 重置虚拟内存 (需重启生效)", self.clean_pagefile),
("???? 一键智能全盘清理 (推荐)", self.clean_all)
]
for text, func in buttons:
btn = QPushButton(text)
btn.setStyleSheet("""
QPushButton {
font-size: 14px;
padding: 8px;
margin: 2px;
background-color: #3498db;
color: white;
border-radius: 5px;
}
QPushButton:hover {
background-color: #2980b9;
}
""")
btn.clicked.connect(func)
layout.addWidget(btn)
# 帮助按钮
help_btn = QPushButton("?? 使用说明")
help_btn.setStyleSheet("background-color: #95a5a6;")
help_btn.clicked.connect(self.show_help)
layout.addWidget(help_btn)
# 状态栏
self.status_bar = QLabel("就绪 | 点击按钮开始清理")
self.status_bar.setAlignment(Qt.AlignCenter)
self.status_bar.setStyleSheet("""
QLabel {
font-size: 13px;
color: #7f8c8d;
border-top: 1px solid #bdc3c7;
padding: 5px;
}
""")
layout.addWidget(self.status_bar)
main_widget.setLayout(layout)
self.setCentralWidget(main_widget)
def check_admin(self):
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except:
return False
def confirm_action(self, title, message):
reply = QMessageBox.question(self, title, message,
QMessageBox.Yes | QMessageBox.No)
return reply == QMessageBox.Yes
def log_operation(self, action, success=True):
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
try:
with open("cleanup_log.txt", "a", encoding="utf-8") as f:
status = "成功" if success else "失败"
f.write(f"[{timestamp}] {action} {status}\n")
except Exception as e:
print(f"日志记录失败: {str(e)}")
def run_command(self, command, description):
self.status_bar.setText(f"? 正在{description}...")
self.status_bar.setStyleSheet("color: #3498db; font-weight: bold;")
QApplication.processEvents()
try:
result = subprocess.run(command, shell=True, check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
encoding='gbk', errors='replace')
self.log_operation(description, True)
self.cleaned_items += 1
return True
except subprocess.CalledProcessError as e:
error_msg = e.stderr if e.stderr else "未知错误"
self.status_bar.setText(f"? {description}失败: {error_msg}")
self.status_bar.setStyleSheet("color: #e74c3c; font-weight: bold;")
self.log_operation(description, False)
return False
def clean_temp_files(self):
if not self.confirm_action("确认清理", "即将扫描并清理以下临时文件:\n\n• 系统临时文件\n• 用户临时文件\n• 预取缓存\n\n是否继续?"):
return
self.progress.setValue(0)
commands = [
('cleanmgr /sagerun:1', "使用系统磁盘清理工具清理临时文件", 20),
('del /f /s /q %TEMP%\\*', "清理用户临时文件夹", 40),
('del /f /s /q C:\\Windows\\Temp\\*', "清理系统临时文件夹", 60),
('del /f /s /q C:\\Windows\\Prefetch\\*', "清理预取文件", 80)
]
for cmd, desc, progress in commands:
self.run_command(cmd, desc)
self.progress.setValue(progress)
time.sleep(1)
self.progress.setValue(100)
self.status_bar.setText(f"? 临时文件清理完成!共清理 {len(commands)} 个项目")
self.status_bar.setStyleSheet("color: #27ae60; font-weight: bold;")
def empty_recycle_bin(self):
if not self.confirm_action("确认清空", "即将永久删除回收站中的所有文件!\n此操作不可恢复,是否继续?"):
return
self.progress.setValue(0)
if self.run_command('cleanmgr /sagerun:2', "使用系统工具清空回收站"):
self.progress.setValue(50)
time.sleep(1)
if not self.run_command('powershell -Command "Clear-RecycleBin -Force -ErrorAction SilentlyContinue"', "强制清空回收站"):
self.run_command('rd /s /q C:\\$Recycle.bin', "尝试直接清理回收站目录")
self.progress.setValue(100)
self.status_bar.setText("? 回收站已清空!")
self.status_bar.setStyleSheet("color: #27ae60; font-weight: bold;")
def clean_browser_cache(self):
if not self.confirm_action("确认清理", "即将清理浏览器缓存:\n\n• Chrome\n• Edge\n• Firefox\n\n请先关闭所有浏览器,是否继续?"):
return
self.progress.setValue(0)
userprofile = os.environ.get('USERPROFILE', '')
if userprofile:
try:
userprofile = userprofile.encode('gbk').decode('utf-8', errors='ignore')
except:
pass
browsers = [
('Google\\Chrome\\User Data\\Default\\Cache', "Chrome 缓存", 30),
('Microsoft\\Edge\\User Data\\Default\\Cache', "Edge 缓存", 60),
('Mozilla\\Firefox\\Profiles', "Firefox 缓存", 90)
]
cleaned = 0
for path, name, progress in browsers:
full_path = os.path.join(userprofile, 'AppData', 'Local', path)
if os.path.exists(full_path):
if self.run_command(f'del /f /s /q "{full_path}\\*"', f"清理 {name}"):
cleaned += 1
self.progress.setValue(progress)
time.sleep(1)
self.progress.setValue(100)
self.status_bar.setText(f"? 已清理 {cleaned} 款浏览器的缓存文件")
self.status_bar.setStyleSheet("color: #27ae60; font-weight: bold;")
def clean_windows_update_cache(self):
if not self.confirm_action("警告", "清理更新缓存可能导致需要重新下载Windows更新!\n是否继续?"):
return
self.progress.setValue(0)
commands = [
('net stop wuauserv', "停止Windows更新服务", 10),
('net stop bits', "停止BITS服务", 20),
('del /f /s /q %windir%\\SoftwareDistribution\\Download\\*', "清理更新下载文件", 40),
('net start wuauserv', "启动Windows更新服务", 60),
('net start bits', "启动BITS服务", 70),
('dism /online /cleanup-image /startcomponentcleanup /resetbase', "清理组件存储", 90)
]
for cmd, desc, progress in commands:
self.run_command(cmd, desc)
self.progress.setValue(progress)
time.sleep(1)
self.progress.setValue(100)
self.status_bar.setText("? Windows更新缓存已清理!建议检查系统更新")
self.status_bar.setStyleSheet("color: #27ae60; font-weight: bold;")
def clean_windows_backup(self):
if not self.confirm_action("危险操作", "删除Windows.old将无法回退到旧版本系统!\n确定继续吗?"):
return
self.progress.setValue(0)
if os.path.exists("C:\\Windows.old"):
if self.run_command('rmdir /s /q C:\\Windows.old', "清理Windows.old文件夹"):
self.progress.setValue(50)
time.sleep(2)
if self.run_command('vssadmin delete shadows /all /quiet', "清理系统还原点"):
self.progress.setValue(100)
self.status_bar.setText("? 系统备份文件已彻底删除!")
self.status_bar.setStyleSheet("color: #27ae60; font-weight: bold;")
def clean_log_files(self):
self.progress.setValue(0)
commands = [
('powershell -Command "wevtutil el | Foreach-Object {wevtutil cl $_}"', "清理事件日志", 30),
('del /f /s /q C:\\Windows\\Logs\\CBS\\*', "清理CBS日志", 60),
('del /f /s /q C:\\Windows\\System32\\LogFiles\\*', "清理系统日志", 90)
]
for cmd, desc, progress in commands:
self.run_command(cmd, desc)
self.progress.setValue(progress)
time.sleep(1)
self.progress.setValue(100)
self.status_bar.setText("? 系统日志文件已清理!")
self.status_bar.setStyleSheet("color: #27ae60; font-weight: bold;")
def clean_defender_files(self):
if self.run_command('cleanmgr /sagerun:4', "清理Windows Defender文件"):
self.status_bar.setText("? Defender防病毒垃圾已清理!")
self.status_bar.setStyleSheet("color: #27ae60; font-weight: bold;")
def clean_iis_logs(self):
if self.run_command('del /f /s /q %SystemDrive%\\inetpub\\logs\\LogFiles\\*', "清理IIS日志"):
self.status_bar.setText("? IIS网站日志已清理!")
self.status_bar.setStyleSheet("color: #27ae60; font-weight: bold;")
def clean_hibernation_files(self):
if not self.confirm_action("确认操作", "禁用休眠功能将影响快速启动和睡眠功能!\n是否继续?"):
return
if self.run_command('powercfg -h off', "禁用休眠功能并删除休眠文件"):
self.status_bar.setText("? 休眠文件已删除!如需恢复请重新启用休眠功能")
self.status_bar.setStyleSheet("color: #27ae60; font-weight: bold;")
def clean_pagefile(self):
if not self.confirm_action("危险操作",
"重置虚拟内存可能导致系统不稳定!\n建议仅在磁盘空间严重不足时使用。\n确定继续吗?"):
return
commands = [
('wmic pagefileset delete', "删除虚拟内存设置", 30),
('del /f /q C:\\pagefile.sys', "删除分页文件", 70)
]
for cmd, desc, progress in commands:
self.run_command(cmd, desc)
self.progress.setValue(progress)
time.sleep(1)
self.run_command('wmic computersystem where name="%computername%" set AutomaticManagedPagefile=True', "恢复自动管理虚拟内存")
self.progress.setValue(100)
self.status_bar.setText("?? 虚拟内存已重置!必须重启系统才能生效")
self.status_bar.setStyleSheet("color: #f39c12; font-weight: bold;")
def clean_all(self):
if not self.confirm_action("全面清理", "即将执行所有清理操作,可能需要较长时间!\n建议先关闭所有应用程序,是否继续?"):
return
self.cleaned_items = 0
operations = [
("临时文件", self.clean_temp_files),
("回收站", self.empty_recycle_bin),
("浏览器缓存", self.clean_browser_cache),
("系统更新缓存", self.clean_windows_update_cache),
("系统备份", self.clean_windows_backup),
("系统日志", self.clean_log_files),
("Defender垃圾", self.clean_defender_files),
("IIS日志", self.clean_iis_logs),
("休眠文件", self.clean_hibernation_files),
("虚拟内存", self.clean_pagefile)
]
for name, operation in operations:
self.status_bar.setText(f"? 正在执行 {name} 清理...")
QApplication.processEvents()
operation()
time.sleep(1)
self.status_bar.setText(f"???? 全盘清理完成!共执行 {self.cleaned_items} 项清理,建议重启系统")
self.status_bar.setStyleSheet("color: #27ae60; font-weight: bold;")
self.progress.setValue(100)
def show_help(self):
help_text = """
<h3>Windows系统清理工具 使用指南</h3>
<p><b>基本功能:</b></p>
<ul>
<li>【一键智能清理】:推荐普通用户使用,自动执行安全清理</li>
<li>【单独功能清理】:适合高级用户按需选择</li>
</ul>
<p><b>注意事项:</b></p>
<ol>
<li>部分功能需要管理员权限</li>
<li>清理前请保存重要文件</li>
<li>系统更新缓存清理后可能需要重新下载更新</li>
<li>执行完全清理后建议重启系统</li>
</ol>
<p><b>技术支持:创客白泽</b> 遇到问题请查看日志文件 cleanup_log.txt</p>
"""
QMessageBox.information(self, "使用说明", help_text.strip())
def closeEvent(self, event):
if self.confirm_action("退出", "确定要退出清理工具吗?"):
event.accept()
else:
event.ignore()
def main():
app = QApplication(sys.argv)
# 设置中文字体
font = app.font()
font.setFamily("Microsoft YaHei")
app.setFont(font)
# 检查管理员权限
try:
if not ctypes.windll.shell32.IsUserAnAdmin():
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setWindowTitle("权限警告")
msg.setText("<b>?? 需要管理员权限</b>")
msg.setInformativeText("此程序的部分核心功能需要管理员权限才能正常运行。\n\n请右键点击程序,选择【以管理员身份运行】获取完整功能。")
msg.exec_()
except:
pass
window = CleanupTool()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
|