Files
nosqlicursorv8/reset_machine_enhanced.py
2025-02-09 22:02:44 +08:00

176 lines
7.1 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import sys
import json
import uuid
import hashlib
import subprocess
import winreg
from datetime import datetime
from colorama import Fore, Style, init
# 初始化colorama
init()
EMOJI = {
"FILE": "📄",
"BACKUP": "💾",
"SUCCESS": "",
"ERROR": "",
"INFO": "",
"RESET": "🔄",
}
class EnhancedMachineIDResetter:
def __init__(self):
if sys.platform != "win32":
raise NotImplementedError("此版本仅支持Windows系统")
self.appdata = os.getenv("APPDATA")
self.localappdata = os.getenv("LOCALAPPDATA")
if not self.appdata or not self.localappdata:
raise EnvironmentError("环境变量未设置")
self.cursor_storage = os.path.join(
self.appdata, "Cursor", "User", "globalStorage", "storage.json"
)
self.backup_dir = os.path.join(
self.appdata, "Cursor", "User", "globalStorage", "backups"
)
def backup_registry(self):
"""备份注册表MachineGuid"""
try:
# 创建备份目录
os.makedirs(self.backup_dir, exist_ok=True)
# 读取当前MachineGuid
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\\Microsoft\\Cryptography", 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as key:
machine_guid = winreg.QueryValueEx(key, "MachineGuid")[0]
# 保存备份
backup_time = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = os.path.join(self.backup_dir, f"MachineGuid.backup_{backup_time}")
with open(backup_file, "w") as f:
f.write(machine_guid)
print(f"{Fore.GREEN}{EMOJI['BACKUP']} 注册表备份成功: {backup_file}{Style.RESET_ALL}")
return True
except Exception as e:
print(f"{Fore.RED}{EMOJI['ERROR']} 注册表备份失败: {str(e)}{Style.RESET_ALL}")
return False
def modify_registry(self):
"""修改注册表MachineGuid"""
try:
new_guid = str(uuid.uuid4())
# 使用管理员权限修改注册表
cmd = f'reg add "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid /t REG_SZ /d "{new_guid}" /f'
subprocess.run(["powershell", "Start-Process", "cmd", "/c", cmd, "-Verb", "RunAs", "-WindowStyle", "Hidden"])
print(f"{Fore.GREEN}{EMOJI['SUCCESS']} 注册表MachineGuid已更新: {new_guid}{Style.RESET_ALL}")
return True
except Exception as e:
print(f"{Fore.RED}{EMOJI['ERROR']} 注册表修改失败: {str(e)}{Style.RESET_ALL}")
return False
def generate_new_ids(self):
"""生成新的机器标识"""
return {
"telemetry.devDeviceId": str(uuid.uuid4()),
"telemetry.macMachineId": hashlib.sha512(os.urandom(64)).hexdigest(),
"telemetry.machineId": hashlib.sha256(os.urandom(32)).hexdigest(),
"telemetry.sqmId": "{" + str(uuid.uuid4()).upper() + "}",
}
def backup_cursor_config(self):
"""备份Cursor配置文件"""
try:
if os.path.exists(self.cursor_storage):
backup_time = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = os.path.join(self.backup_dir, f"storage.json.backup_{backup_time}")
os.makedirs(self.backup_dir, exist_ok=True)
with open(self.cursor_storage, "r", encoding="utf-8") as src, \
open(backup_file, "w", encoding="utf-8") as dst:
dst.write(src.read())
print(f"{Fore.GREEN}{EMOJI['BACKUP']} Cursor配置备份成功: {backup_file}{Style.RESET_ALL}")
return True
except Exception as e:
print(f"{Fore.RED}{EMOJI['ERROR']} Cursor配置备份失败: {str(e)}{Style.RESET_ALL}")
return False
def modify_cursor_config(self):
"""修改Cursor配置文件"""
try:
if not os.path.exists(self.cursor_storage):
print(f"{Fore.RED}{EMOJI['ERROR']} Cursor配置文件不存在{Style.RESET_ALL}")
return False
# 读取现有配置
with open(self.cursor_storage, "r", encoding="utf-8") as f:
config = json.load(f)
# 更新配置
new_ids = self.generate_new_ids()
config.update(new_ids)
# 保存新配置
with open(self.cursor_storage, "w", encoding="utf-8") as f:
json.dump(config, f, indent=4)
print(f"{Fore.GREEN}{EMOJI['SUCCESS']} Cursor配置已更新{Style.RESET_ALL}")
for key, value in new_ids.items():
print(f"{EMOJI['INFO']} {key}: {value}")
return True
except Exception as e:
print(f"{Fore.RED}{EMOJI['ERROR']} Cursor配置修改失败: {str(e)}{Style.RESET_ALL}")
return False
def kill_cursor_process(self):
"""结束Cursor进程"""
try:
subprocess.run(["taskkill", "/F", "/IM", "Cursor.exe"], capture_output=True)
print(f"{Fore.GREEN}{EMOJI['SUCCESS']} Cursor进程已终止{Style.RESET_ALL}")
return True
except Exception as e:
print(f"{Fore.RED}{EMOJI['ERROR']} 终止Cursor进程失败: {str(e)}{Style.RESET_ALL}")
return False
def reset_all(self):
"""执行完整的重置流程"""
print(f"\n{Fore.CYAN}{'='*50}{Style.RESET_ALL}")
print(f"{Fore.CYAN}{EMOJI['RESET']} Cursor 增强版机器码重置工具{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'='*50}{Style.RESET_ALL}\n")
# 1. 结束Cursor进程
print(f"{Fore.CYAN}[1/5] 正在结束Cursor进程...{Style.RESET_ALL}")
self.kill_cursor_process()
# 2. 备份注册表
print(f"\n{Fore.CYAN}[2/5] 正在备份注册表...{Style.RESET_ALL}")
self.backup_registry()
# 3. 备份Cursor配置
print(f"\n{Fore.CYAN}[3/5] 正在备份Cursor配置...{Style.RESET_ALL}")
self.backup_cursor_config()
# 4. 修改注册表
print(f"\n{Fore.CYAN}[4/5] 正在修改注册表...{Style.RESET_ALL}")
self.modify_registry()
# 5. 修改Cursor配置
print(f"\n{Fore.CYAN}[5/5] 正在修改Cursor配置...{Style.RESET_ALL}")
self.modify_cursor_config()
print(f"\n{Fore.GREEN}{EMOJI['SUCCESS']} 重置完成!{Style.RESET_ALL}")
print(f"{Fore.YELLOW}{EMOJI['INFO']} 请重启电脑以使更改生效{Style.RESET_ALL}")
if __name__ == "__main__":
try:
resetter = EnhancedMachineIDResetter()
resetter.reset_all()
except Exception as e:
print(f"{Fore.RED}{EMOJI['ERROR']} 发生错误: {str(e)}{Style.RESET_ALL}")
finally:
print(f"\n{Fore.CYAN}{'='*50}{Style.RESET_ALL}")
input(f"{EMOJI['INFO']} 按回车键退出...")