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

312 lines
12 KiB
Python

import os
import ctypes
import subprocess
from colorama import Fore, Style
import sys
import logging
import codecs
import traceback
import time
import random
# 设置日志记录
try:
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')
except Exception as e:
print(f"编码设置失败: {e}")
# 确保日志目录存在
log_dir = 'logs'
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, 'full_reset_debug.log')
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file, encoding='utf-8', mode='w'),
logging.StreamHandler(sys.stdout)
]
)
def pause_exit(status=0):
"""暂停并等待用户输入后退出"""
print("\n" + "="*50)
print("按回车键退出...")
input()
sys.exit(status)
def is_admin():
try:
logging.debug("检查管理员权限")
result = ctypes.windll.shell32.IsUserAnAdmin()
logging.debug(f"管理员权限检查结果: {result}")
return result
except Exception as e:
logging.error(f"检查管理员权限时出错: {str(e)}")
logging.error(traceback.format_exc())
return False
def run_powershell_reset():
"""运行 PowerShell 重置脚本"""
try:
logging.debug("开始准备 PowerShell 重置")
# 获取并记录路径信息
storage_path = os.path.expandvars(r"%APPDATA%\Cursor\User\globalStorage\storage.json")
backup_path = os.path.expandvars(r"%APPDATA%\Cursor\User\globalStorage\backups")
logging.info(f"存储文件路径: {storage_path}")
logging.info(f"备份目录路径: {backup_path}")
# 检查文件和目录是否存在
if os.path.exists(storage_path):
logging.info("存储文件存在")
if not os.access(storage_path, os.W_OK):
logging.error("存储文件没有写入权限")
print(f"{Fore.RED}错误: 没有文件写入权限{Style.RESET_ALL}")
return False
else:
logging.error("存储文件不存在")
print(f"{Fore.RED}错误: 存储文件不存在{Style.RESET_ALL}")
return False
if not os.path.exists(backup_path):
try:
os.makedirs(backup_path)
logging.info("已创建备份目录")
except Exception as e:
logging.error(f"创建备份目录失败: {e}")
print(f"{Fore.RED}错误: 无法创建备份目录{Style.RESET_ALL}")
return False
# 准备 PowerShell 命令
cmd = f'''
# 设置输出编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
chcp 65001 | Out-Null
# 配置文件路径
$STORAGE_FILE = "{storage_path}"
$BACKUP_DIR = "{backup_path}"
Write-Host "`e[32m[信息]`e[0m 检查 Cursor 进程..."
# 检查管理员权限
function Test-Administrator {{
$user = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($user)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}}
if (-not (Test-Administrator)) {{
Write-Host "`e[31m[错误]`e[0m 请以管理员身份运行此脚本"
exit 1
}}
# 创建备份目录
if (-not (Test-Path $BACKUP_DIR)) {{
New-Item -ItemType Directory -Path $BACKUP_DIR | Out-Null
}}
# 备份现有配置
if (Test-Path $STORAGE_FILE) {{
Write-Host "`e[32m[信息]`e[0m 正在备份配置文件..."
$backupName = "storage.json.backup_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
Copy-Item $STORAGE_FILE "$BACKUP_DIR\\$backupName"
}}
# 生成新的 ID
Write-Host "`e[32m[信息]`e[0m 正在生成新的 ID..."
function New-StandardMachineId {{
$template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
$result = $template -replace '[xy]', {{
param($match)
$r = [Random]::new().Next(16)
$v = if ($match.Value -eq "x") {{ $r }} else {{ ($r -band 0x3) -bor 0x8 }}
return $v.ToString("x")
}}
return $result
}}
$MAC_MACHINE_ID = New-StandardMachineId
$UUID = [System.Guid]::NewGuid().ToString()
$prefixBytes = [System.Text.Encoding]::UTF8.GetBytes("auth0|user_")
$prefixHex = -join ($prefixBytes | ForEach-Object {{ [System.Convert]::ToString($_, 16).PadLeft(2, '0') }})
$randomPart = -join (1..32 | ForEach-Object {{ [Convert]::ToString((Get-Random -Minimum 0 -Maximum 256), 16).PadLeft(2, '0') }})
$MACHINE_ID = "$prefixHex$randomPart"
$SQM_ID = "{{$([System.Guid]::NewGuid().ToString().ToUpper())}}"
# 更新配置文件
Write-Host "`e[32m[信息]`e[0m 正在更新配置..."
try {{
if (-not (Test-Path $STORAGE_FILE)) {{
Write-Host "`e[31m[错误]`e[0m 未找到配置文件: $STORAGE_FILE"
exit 1
}}
$originalContent = Get-Content $STORAGE_FILE -Raw -Encoding UTF8
$config = $originalContent | ConvertFrom-Json
# 备份当前值
$oldValues = @{{
'machineId' = $config.'telemetry.machineId'
'macMachineId' = $config.'telemetry.macMachineId'
'devDeviceId' = $config.'telemetry.devDeviceId'
'sqmId' = $config.'telemetry.sqmId'
}}
# 更新特定的值
$config.'telemetry.machineId' = $MACHINE_ID
$config.'telemetry.macMachineId' = $MAC_MACHINE_ID
$config.'telemetry.devDeviceId' = $UUID
$config.'telemetry.sqmId' = $SQM_ID
# 将更新后的对象转换回 JSON 并保存
$updatedJson = $config | ConvertTo-Json -Depth 10
[System.IO.File]::WriteAllText(
[System.IO.Path]::GetFullPath($STORAGE_FILE),
$updatedJson,
[System.Text.Encoding]::UTF8
)
Write-Host "`e[32m[信息]`e[0m 成功更新配置文件"
# 更新系统 MachineGuid
try {{
$newMachineGuid = [System.Guid]::NewGuid().ToString()
$registryPath = "HKLM:\\SOFTWARE\\Microsoft\\Cryptography"
# 备份原始值
$originalGuid = (Get-ItemProperty -Path $registryPath -Name "MachineGuid").MachineGuid
$backupFile = "$BACKUP_DIR\\MachineGuid.backup_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
$originalGuid | Out-File $backupFile -Encoding UTF8
# 更新注册表
Set-ItemProperty -Path $registryPath -Name "MachineGuid" -Value $newMachineGuid
Write-Host "`e[32m[信息]`e[0m 已更新系统 MachineGuid: $newMachineGuid"
Write-Host "`e[32m[信息]`e[0m 原始值已备份至: $backupFile"
}}
catch {{
Write-Host "`e[31m[错误]`e[0m 更新系统 MachineGuid 失败: $_"
}}
# 显示结果
Write-Host ""
Write-Host "`e[32m[信息]`e[0m 已更新配置:"
Write-Host "`e[34m[调试]`e[0m machineId: $MACHINE_ID"
Write-Host "`e[34m[调试]`e[0m macMachineId: $MAC_MACHINE_ID"
Write-Host "`e[34m[调试]`e[0m devDeviceId: $UUID"
Write-Host "`e[34m[调试]`e[0m sqmId: $SQM_ID"
}} catch {{
Write-Host "`e[31m[错误]`e[0m 主要操作失败: $_"
Write-Host "`e[33m[尝试]`e[0m 使用备选方法..."
try {{
$tempFile = [System.IO.Path]::GetTempFileName()
$config | ConvertTo-Json | Set-Content -Path $tempFile -Encoding UTF8
Copy-Item -Path $tempFile -Destination $STORAGE_FILE -Force
Remove-Item -Path $tempFile
Write-Host "`e[32m[信息]`e[0m 使用备选方法成功写入配置"
}} catch {{
Write-Host "`e[31m[错误]`e[0m 所有尝试都失败了"
Write-Host "错误详情: $_"
Write-Host "目标文件: $STORAGE_FILE"
Write-Host "请确保您有足够的权限访问该文件"
exit 1
}}
}}
exit 0
'''
logging.info("准备执行 PowerShell 命令")
# 执行命令并捕获输出
process = subprocess.run(
["powershell", "-NoProfile", "-NonInteractive", "-Command", cmd],
capture_output=True,
text=True,
encoding='utf-8'
)
# 记录命令输出
if process.stdout:
logging.info("PowerShell 输出:")
for line in process.stdout.splitlines():
logging.info(f"PS> {line}")
if process.stderr:
logging.error("PowerShell 错误:")
for line in process.stderr.splitlines():
logging.error(f"PS Error> {line}")
if process.returncode != 0:
logging.error(f"PowerShell 命令执行失败,返回码: {process.returncode}")
return False
logging.info("PowerShell 命令执行成功")
return True
except subprocess.CalledProcessError as e:
logging.error(f"PowerShell 脚本执行失败: {e}")
logging.error(f"返回码: {e.returncode}")
if hasattr(e, 'stdout') and e.stdout:
logging.error(f"标准输出: {e.stdout}")
if hasattr(e, 'stderr') and e.stderr:
logging.error(f"标准错误: {e.stderr}")
logging.error(traceback.format_exc())
return False
except Exception as e:
logging.error(f"执行过程中出错: {str(e)}")
logging.error(traceback.format_exc())
return False
def full_system_reset():
"""执行完整的系统重置"""
try:
# 检查管理员权限
if not is_admin():
logging.error("需要管理员权限")
return False
# 运行重置
logging.info("开始执行完整重置...")
if run_powershell_reset():
logging.info("重置完成")
return True
else:
logging.error("重置失败")
return False
except Exception as e:
logging.error(f"系统重置出错: {str(e)}")
logging.error(traceback.format_exc())
return False
if __name__ == "__main__":
try:
# 检查管理员权限
if not is_admin():
print(f"{Fore.RED}[错误] 请以管理员身份运行此程序{Style.RESET_ALL}")
print(f"{Fore.YELLOW}[提示] 请右键点击程序,选择'以管理员身份运行'{Style.RESET_ALL}")
pause_exit(1)
# 运行重置
print(f"{Fore.CYAN}[信息] 开始执行完整重置...{Style.RESET_ALL}")
if full_system_reset():
print(f"{Fore.GREEN}[成功] 重置完成!{Style.RESET_ALL}")
print(f"{Fore.YELLOW}[提示] 请重启 Cursor 以应用新的配置{Style.RESET_ALL}")
else:
print(f"{Fore.RED}[错误] 重置失败{Style.RESET_ALL}")
except Exception as e:
logging.error(f"程序执行出错: {str(e)}")
logging.error(traceback.format_exc())
print(f"{Fore.RED}[错误] 程序执行出现异常: {str(e)}{Style.RESET_ALL}")
finally:
pause_exit()