cursor_pro_keep_alive.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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("Invalid email or password"):
  122. print("Invalid email or password")
  123. return False
  124. if tab.ele("Account Settings"):
  125. break
  126. if tab.ele("@data-index=0"):
  127. code = email_handler.get_verification_code(account)
  128. if code:
  129. print("获取验证码成功:", code)
  130. else:
  131. print("获取验证码失败,程序退出")
  132. return False
  133. i = 0
  134. for digit in code:
  135. tab.ele(f"@data-index={i}").input(digit)
  136. time.sleep(random.uniform(0.1, 0.3))
  137. i += 1
  138. break
  139. except Exception as e:
  140. print(e)
  141. handle_turnstile(tab)
  142. time.sleep(random.uniform(1, 3))
  143. # tab.get_screenshot('sign-in_success.png')
  144. # print("登录账户截图")
  145. tab.get(settings_url)
  146. print("进入设置页面")
  147. try:
  148. if tab.ele("@class=mt-1"):
  149. tab.ele("@class=mt-1").click()
  150. print("点击Adavance")
  151. time.sleep(random.uniform(1, 2))
  152. except Exception as e:
  153. print(f"点击Adavance失败: {str(e)}")
  154. try:
  155. if tab.ele("Delete Account"):
  156. tab.ele("Delete Account").click()
  157. print("点击Delete Account")
  158. time.sleep(random.uniform(1, 2))
  159. except Exception as e:
  160. print(f"点击Delete Account失败: {str(e)}")
  161. try:
  162. if tab.ele("tag:input"):
  163. tab.actions.click("tag:input").type("delete")
  164. print("输入delete")
  165. time.sleep(random.uniform(1, 2))
  166. except Exception as e:
  167. print(f"输入delete失败: {str(e)}")
  168. delete_button = tab.ele(
  169. "xpath:/html/body/main/div/div/div/div/div/div[1]/div[2]/div[3]/div[2]/div/div/div[2]/button[2]"
  170. )
  171. try:
  172. if delete_button:
  173. print("点击Delete")
  174. delete_button.click()
  175. time.sleep(5)
  176. # tab.get_screenshot('delete_account.png')
  177. # print("删除账户截图")
  178. return True
  179. except Exception as e:
  180. print(f"点击Delete失败: {str(e)}")
  181. return False
  182. def get_cursor_session_token(tab):
  183. """获取cursor session token"""
  184. cookies = tab.cookies()
  185. cursor_session_token = None
  186. time.sleep(3)
  187. for cookie in cookies:
  188. if cookie["name"] == "WorkosCursorSessionToken":
  189. cursor_session_token = cookie["value"].split("%3A%3A")[1]
  190. break
  191. if not cursor_session_token:
  192. print("未能获取到CursorSessionToken")
  193. return cursor_session_token
  194. def update_cursor_auth(email=None, access_token=None, refresh_token=None):
  195. """
  196. 更新Cursor的认证信息的便捷函数
  197. """
  198. auth_manager = CursorAuthManager()
  199. return auth_manager.update_auth(email, access_token, refresh_token)
  200. def sign_up_account(browser, tab):
  201. """注册账户流程"""
  202. print("\n开始注册新账户...")
  203. tab.get(sign_up_url)
  204. try:
  205. if tab.ele("@name=first_name"):
  206. print("已打开注册页面")
  207. tab.actions.click("@name=first_name").input(first_name)
  208. time.sleep(random.uniform(1, 3))
  209. tab.actions.click("@name=last_name").input(last_name)
  210. time.sleep(random.uniform(1, 3))
  211. tab.actions.click("@name=email").input(account)
  212. print("输入邮箱")
  213. time.sleep(random.uniform(1, 3))
  214. tab.actions.click("@type=submit")
  215. print("点击注册按钮")
  216. except Exception as e:
  217. print("打开注册页面失败")
  218. return False
  219. handle_turnstile(tab)
  220. try:
  221. if tab.ele("@name=password"):
  222. tab.ele("@name=password").input(password)
  223. print("输入密码")
  224. time.sleep(random.uniform(1, 3))
  225. tab.ele("@type=submit").click()
  226. print("点击Continue按钮")
  227. except Exception as e:
  228. print("输入密码失败")
  229. return False
  230. time.sleep(random.uniform(1, 3))
  231. if tab.ele("This email is not available."):
  232. print("This email is not available.")
  233. return False
  234. handle_turnstile(tab)
  235. while True:
  236. try:
  237. if tab.ele("Account Settings"):
  238. break
  239. if tab.ele("@data-index=0"):
  240. code = email_handler.get_verification_code(account)
  241. if code:
  242. print("获取验证码成功:", code)
  243. else:
  244. print("获取验证码失败,程序退出")
  245. return False
  246. i = 0
  247. for digit in code:
  248. tab.ele(f"@data-index={i}").input(digit)
  249. time.sleep(random.uniform(0.1, 0.3))
  250. i += 1
  251. break
  252. except Exception as e:
  253. print(e)
  254. handle_turnstile(tab)
  255. time.sleep(random.uniform(1, 3))
  256. print("进入设置页面")
  257. tab.get(settings_url)
  258. try:
  259. usage_ele = tab.ele(
  260. "xpath:/html/body/main/div/div/div/div/div/div[2]/div/div/div/div[1]/div[1]/span[2]"
  261. )
  262. if usage_ele:
  263. usage_info = usage_ele.text
  264. total_usage = usage_info.split("/")[-1].strip()
  265. print("可用上限: " + total_usage)
  266. except Exception as e:
  267. print("获取可用上限失败")
  268. # tab.get_screenshot("sign_up_success.png")
  269. # print("注册账户截图")
  270. print("注册完成")
  271. print("Cursor 账号: " + account)
  272. print(" 密码: " + password)
  273. return True
  274. def cleanup_temp_files():
  275. """清理临时文件和缓存"""
  276. try:
  277. temp_dirs = [
  278. os.path.join(os.getcwd(), "__pycache__"),
  279. os.path.join(os.getcwd(), "build"),
  280. ]
  281. for dir_path in temp_dirs:
  282. if os.path.exists(dir_path):
  283. import shutil
  284. shutil.rmtree(dir_path)
  285. except Exception as e:
  286. logging.warning(f"清理临时文件失败: {str(e)}")
  287. if __name__ == "__main__":
  288. browser_manager = None
  289. try:
  290. # 加载配置
  291. config = load_config()
  292. # 初始化浏览器
  293. browser_manager = BrowserManager()
  294. browser = browser_manager.init_browser()
  295. # 初始化��箱验证处理器
  296. email_handler = EmailVerificationHandler(browser)
  297. # 固定的 URL 配置
  298. login_url = "https://authenticator.cursor.sh"
  299. sign_up_url = "https://authenticator.cursor.sh/sign-up"
  300. settings_url = "https://www.cursor.com/settings"
  301. mail_url = "https://tempmail.plus"
  302. # 账号信息
  303. account = config["account"]
  304. password = config["password"]
  305. first_name = config["first_name"]
  306. last_name = config["last_name"]
  307. auto_update_cursor_auth = True
  308. tab = browser.latest_tab
  309. tab.run_js("try { turnstile.reset() } catch(e) { }")
  310. print("开始执行删除和注册流程")
  311. print("***请确认已经用https://tempmail.plus/zh邮箱成功申请过cursor账号!***")
  312. tab.get(login_url)
  313. # 执行删除和注册流程
  314. if delete_account(browser, tab):
  315. print("账户删除成功")
  316. time.sleep(3)
  317. if sign_up_account(browser, tab):
  318. token = get_cursor_session_token(tab)
  319. if token:
  320. # print(f"CursorSessionToken: {token}")
  321. print("账户注册成功")
  322. if auto_update_cursor_auth:
  323. update_cursor_auth(
  324. email=account, access_token=token, refresh_token=token
  325. )
  326. else:
  327. print("未能获取到CursorSessionToken")
  328. else:
  329. print("账户注册失败")
  330. else:
  331. print("账户删除失败")
  332. # if sign_up_account(browser, tab):
  333. # token = get_cursor_session_token(tab)
  334. # print(f"CursorSessionToken: {token}")
  335. # print("账户注册成功")
  336. # if auto_update_cursor_auth:
  337. # update_cursor_auth(
  338. # email=account, access_token=token, refresh_token=token
  339. # )
  340. # else:
  341. # print("账户注册失败")
  342. print("脚本执行完毕")
  343. except Exception as e:
  344. logging.error(f"程序执行出错: {str(e)}")
  345. import traceback
  346. logging.error(traceback.format_exc())
  347. finally:
  348. if browser_manager:
  349. browser_manager.quit()
  350. input("\n按回车键退出...")