cursor_pro_keep_alive.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import os
  2. from license_manager import LicenseManager
  3. os.environ["PYTHONVERBOSE"] = "0"
  4. os.environ["PYINSTALLER_VERBOSE"] = "0"
  5. from DrissionPage import ChromiumOptions, Chromium
  6. from DrissionPage.common import Keys
  7. import re
  8. import time
  9. import random
  10. from cursor_auth_manager import CursorAuthManager
  11. from configparser import ConfigParser
  12. import os
  13. import sys
  14. import logging
  15. from browser_utils import BrowserManager
  16. from get_veri_code import EmailVerificationHandler
  17. # 在文件开头设置日志
  18. logging.basicConfig(
  19. level=logging.WARNING,
  20. format="%(asctime)s - %(levelname)s - %(message)s",
  21. handlers=[
  22. logging.StreamHandler(),
  23. logging.FileHandler("cursor_keep_alive.log", encoding="utf-8"),
  24. ],
  25. )
  26. def load_config():
  27. """加载配置文件"""
  28. config = ConfigParser()
  29. # 获取程序运行的实际目录
  30. if getattr(sys, "frozen", False):
  31. # 打包后的情况:使用可执行文件所在目录
  32. root_dir = os.path.dirname(sys.executable)
  33. else:
  34. # 开发环境:使用当前工作目录
  35. root_dir = os.getcwd()
  36. config_path = os.path.join(root_dir, "config.ini")
  37. if os.path.exists(config_path):
  38. config.read(config_path, encoding="utf-8")
  39. print(f"已加载配置文件: {config_path}")
  40. print(config["Account"]["email"])
  41. return {
  42. "account": config["Account"]["email"],
  43. "password": config["Account"]["password"],
  44. "first_name": config["Account"]["first_name"],
  45. "last_name": config["Account"]["last_name"],
  46. }
  47. raise FileNotFoundError(f"配置文件不存在: {config_path}")
  48. def handle_turnstile(tab):
  49. """处理 Turnstile 验证"""
  50. print("准备处理验证")
  51. try:
  52. while True:
  53. try:
  54. challengeCheck = (
  55. tab.ele("@id=cf-turnstile", timeout=2)
  56. .child()
  57. .shadow_root.ele("tag:iframe")
  58. .ele("tag:body")
  59. .sr("tag:input")
  60. )
  61. if challengeCheck:
  62. print("验证框加载完成")
  63. time.sleep(random.uniform(1, 3))
  64. challengeCheck.click()
  65. print("验证按钮已点击,等待验证完成...")
  66. time.sleep(2)
  67. return True
  68. except:
  69. pass
  70. if tab.ele("@name=password"):
  71. print("无需验证")
  72. break
  73. if tab.ele("@data-index=0"):
  74. print("无需验证")
  75. break
  76. if tab.ele("Account Settings"):
  77. print("无需验证")
  78. break
  79. time.sleep(random.uniform(1, 2))
  80. except Exception as e:
  81. print(e)
  82. print("跳过验证")
  83. return False
  84. def delete_account(browser, tab):
  85. """删除账户流程"""
  86. print("\n开始删除账户...")
  87. try:
  88. if tab.ele("@name=email"):
  89. tab.ele("@name=email").input(account)
  90. print("输入账号")
  91. time.sleep(random.uniform(1, 3))
  92. except Exception as e:
  93. print(f"输入账号失败: {str(e)}")
  94. try:
  95. if tab.ele("Continue"):
  96. tab.ele("Continue").click()
  97. print("点击Continue")
  98. except Exception as e:
  99. print(f"点击Continue失败: {str(e)}")
  100. handle_turnstile(tab)
  101. time.sleep(5)
  102. try:
  103. if tab.ele("@name=password"):
  104. tab.ele("@name=password").input(password)
  105. print("输入密码")
  106. time.sleep(random.uniform(1, 3))
  107. except Exception as e:
  108. print("输入密码失败")
  109. sign_in_button = tab.ele(
  110. "xpath:/html/body/div[1]/div/div/div[2]/div/form/div/button"
  111. )
  112. try:
  113. if sign_in_button:
  114. sign_in_button.click(by_js=True)
  115. print("点击Sign in")
  116. except Exception as e:
  117. print(f"点击Sign in失败: {str(e)}")
  118. handle_turnstile(tab)
  119. # 处理验证码
  120. while True:
  121. try:
  122. if tab.ele("Invalid email or password"):
  123. print("Invalid email or password")
  124. return False
  125. if tab.ele("Account Settings"):
  126. break
  127. if tab.ele("@data-index=0"):
  128. code = email_handler.get_verification_code(account)
  129. if code:
  130. print("获取验证码成功:", code)
  131. else:
  132. print("获取验证码失败,程序退出")
  133. return False
  134. i = 0
  135. for digit in code:
  136. tab.ele(f"@data-index={i}").input(digit)
  137. time.sleep(random.uniform(0.1, 0.3))
  138. i += 1
  139. break
  140. except Exception as e:
  141. print(e)
  142. handle_turnstile(tab)
  143. time.sleep(random.uniform(1, 3))
  144. # tab.get_screenshot('sign-in_success.png')
  145. # print("登录账户截图")
  146. tab.get(settings_url)
  147. print("进入设置页面")
  148. try:
  149. if tab.ele("@class=mt-1"):
  150. tab.ele("@class=mt-1").click()
  151. print("点击Adavance")
  152. time.sleep(random.uniform(1, 2))
  153. except Exception as e:
  154. print(f"点击Adavance失败: {str(e)}")
  155. try:
  156. if tab.ele("Delete Account"):
  157. tab.ele("Delete Account").click()
  158. print("点击Delete Account")
  159. time.sleep(random.uniform(1, 2))
  160. except Exception as e:
  161. print(f"点击Delete Account失败: {str(e)}")
  162. try:
  163. if tab.ele("tag:input"):
  164. tab.actions.click("tag:input").type("delete")
  165. print("输入delete")
  166. time.sleep(random.uniform(1, 2))
  167. except Exception as e:
  168. print(f"输入delete失败: {str(e)}")
  169. delete_button = tab.ele(
  170. "xpath:/html/body/main/div/div/div/div/div/div[1]/div[2]/div[3]/div[2]/div/div/div[2]/button[2]"
  171. )
  172. try:
  173. if delete_button:
  174. print("点击Delete")
  175. delete_button.click()
  176. time.sleep(5)
  177. # tab.get_screenshot('delete_account.png')
  178. # print("删除账户截图")
  179. return True
  180. except Exception as e:
  181. print(f"点击Delete失败: {str(e)}")
  182. return False
  183. def get_cursor_session_token(tab):
  184. """获取cursor session token"""
  185. cookies = tab.cookies()
  186. cursor_session_token = None
  187. time.sleep(3)
  188. for cookie in cookies:
  189. if cookie["name"] == "WorkosCursorSessionToken":
  190. cursor_session_token = cookie["value"].split("%3A%3A")[1]
  191. break
  192. if not cursor_session_token:
  193. print("未能获取到CursorSessionToken")
  194. return cursor_session_token
  195. def update_cursor_auth(email=None, access_token=None, refresh_token=None):
  196. """
  197. 更新Cursor的认证信息的便捷函数
  198. """
  199. auth_manager = CursorAuthManager()
  200. return auth_manager.update_auth(email, access_token, refresh_token)
  201. def sign_up_account(browser, tab):
  202. """注册账户流程"""
  203. print("\n开始注册新账户...")
  204. tab.get(sign_up_url)
  205. try:
  206. if tab.ele("@name=first_name"):
  207. print("已打开注册页面")
  208. tab.actions.click("@name=first_name").input(first_name)
  209. time.sleep(random.uniform(1, 3))
  210. tab.actions.click("@name=last_name").input(last_name)
  211. time.sleep(random.uniform(1, 3))
  212. tab.actions.click("@name=email").input(account)
  213. print("输入邮箱")
  214. time.sleep(random.uniform(1, 3))
  215. tab.actions.click("@type=submit")
  216. print("点击注册按钮")
  217. except Exception as e:
  218. print("打开注册页面失败")
  219. return False
  220. handle_turnstile(tab)
  221. try:
  222. if tab.ele("@name=password"):
  223. tab.ele("@name=password").input(password)
  224. print("输入密码")
  225. time.sleep(random.uniform(1, 3))
  226. tab.ele("@type=submit").click()
  227. print("点击Continue按钮")
  228. except Exception as e:
  229. print("输入密码失败")
  230. return False
  231. time.sleep(random.uniform(1, 3))
  232. if tab.ele("This email is not available."):
  233. print("This email is not available.")
  234. return False
  235. handle_turnstile(tab)
  236. while True:
  237. try:
  238. if tab.ele("Account Settings"):
  239. break
  240. if tab.ele("@data-index=0"):
  241. code = email_handler.get_verification_code(account)
  242. if code:
  243. print("获取验证码成功:", code)
  244. else:
  245. print("获取验证码失败,程序退出")
  246. return False
  247. i = 0
  248. for digit in code:
  249. tab.ele(f"@data-index={i}").input(digit)
  250. time.sleep(random.uniform(0.1, 0.3))
  251. i += 1
  252. break
  253. except Exception as e:
  254. print(e)
  255. handle_turnstile(tab)
  256. time.sleep(random.uniform(1, 3))
  257. print("进入设置页面")
  258. tab.get(settings_url)
  259. try:
  260. usage_ele = tab.ele(
  261. "xpath:/html/body/main/div/div/div/div/div/div[2]/div/div/div/div[1]/div[1]/span[2]"
  262. )
  263. if usage_ele:
  264. usage_info = usage_ele.text
  265. total_usage = usage_info.split("/")[-1].strip()
  266. print("可用上限: " + total_usage)
  267. except Exception as e:
  268. print("获取可用上限失败")
  269. # tab.get_screenshot("sign_up_success.png")
  270. # print("注册账户截图")
  271. print("注册完成")
  272. print("Cursor 账号: " + account)
  273. print(" 密码: " + password)
  274. return True
  275. def cleanup_temp_files():
  276. """清理临时文件和缓存"""
  277. try:
  278. temp_dirs = [
  279. os.path.join(os.getcwd(), "__pycache__"),
  280. os.path.join(os.getcwd(), "build"),
  281. ]
  282. for dir_path in temp_dirs:
  283. if os.path.exists(dir_path):
  284. import shutil
  285. shutil.rmtree(dir_path)
  286. except Exception as e:
  287. logging.warning(f"清理临时文件失败: {str(e)}")
  288. if __name__ == "__main__":
  289. browser_manager = None
  290. license_manager = None
  291. try:
  292. # 检查许可证
  293. license_manager = LicenseManager()
  294. if not license_manager.check_license():
  295. print("免费使用次数已用完")
  296. sys.exit(1)
  297. # 加载配置
  298. config = load_config()
  299. # 初始化浏览器
  300. browser_manager = BrowserManager()
  301. browser = browser_manager.init_browser()
  302. # 初始化��箱验证处理器
  303. email_handler = EmailVerificationHandler(browser)
  304. # 固定的 URL 配置
  305. login_url = "https://authenticator.cursor.sh"
  306. sign_up_url = "https://authenticator.cursor.sh/sign-up"
  307. settings_url = "https://www.cursor.com/settings"
  308. mail_url = "https://tempmail.plus"
  309. # 账号信息
  310. account = config["account"]
  311. password = config["password"]
  312. first_name = config["first_name"]
  313. last_name = config["last_name"]
  314. auto_update_cursor_auth = True
  315. tab = browser.latest_tab
  316. tab.run_js("try { turnstile.reset() } catch(e) { }")
  317. print("开始执行删除和注册流程")
  318. print("***请确认已经用https://tempmail.plus/zh邮箱成功申请过cursor账号!***")
  319. tab.get(login_url)
  320. # 执行删除和注册流程
  321. if delete_account(browser, tab):
  322. print("账户删除成功")
  323. time.sleep(3)
  324. if sign_up_account(browser, tab):
  325. token = get_cursor_session_token(tab)
  326. if token:
  327. # print(f"CursorSessionToken: {token}")
  328. print("账户注册成功")
  329. if auto_update_cursor_auth:
  330. update_cursor_auth(
  331. email=account, access_token=token, refresh_token=token
  332. )
  333. else:
  334. print("未能获取到CursorSessionToken")
  335. else:
  336. print("账户注册失败")
  337. else:
  338. print("账户删除失败")
  339. # if sign_up_account(browser, tab):
  340. # token = get_cursor_session_token(tab)
  341. # print(f"CursorSessionToken: {token}")
  342. # print("账户注册成功")
  343. # if auto_update_cursor_auth:
  344. # update_cursor_auth(
  345. # email=account, access_token=token, refresh_token=token
  346. # )
  347. # else:
  348. # print("账户注册失败")
  349. print("脚本执行完毕")
  350. except Exception as e:
  351. logging.error(f"程序执行出错: {str(e)}")
  352. import traceback
  353. logging.error(traceback.format_exc())
  354. finally:
  355. if browser_manager:
  356. browser_manager.quit()
  357. input("\n按回车键退出...")