cursor_pro_keep_alive.py 12 KB

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