cursor_pro_keep_alive.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import os
  2. from exit_cursor import ExitCursor
  3. os.environ["PYTHONVERBOSE"] = "0"
  4. os.environ["PYINSTALLER_VERBOSE"] = "0"
  5. import time
  6. import random
  7. from cursor_auth_manager import CursorAuthManager
  8. import os
  9. from logger import logging
  10. from browser_utils import BrowserManager
  11. from get_email_code import EmailVerificationHandler
  12. from logo import print_logo
  13. import psutil
  14. def handle_turnstile(tab):
  15. print("开始突破难关")
  16. try:
  17. while True:
  18. try:
  19. challengeCheck = (
  20. tab.ele("@id=cf-turnstile", timeout=2)
  21. .child()
  22. .shadow_root.ele("tag:iframe")
  23. .ele("tag:body")
  24. .sr("tag:input")
  25. )
  26. if challengeCheck:
  27. print("开始突破")
  28. time.sleep(random.uniform(1, 3))
  29. challengeCheck.click()
  30. time.sleep(2)
  31. print("突破成功")
  32. return True
  33. except:
  34. pass
  35. if tab.ele("@name=password"):
  36. print("突破成功")
  37. break
  38. if tab.ele("@data-index=0"):
  39. print("突破成功")
  40. break
  41. if tab.ele("Account Settings"):
  42. print("突破成功")
  43. break
  44. time.sleep(random.uniform(1, 2))
  45. except Exception as e:
  46. print(e)
  47. print("突破失败")
  48. return False
  49. def get_cursor_session_token(tab, max_attempts=3, retry_interval=2):
  50. """
  51. 获取Cursor会话token,带有重试机制
  52. :param tab: 浏览器标签页
  53. :param max_attempts: 最大尝试次数
  54. :param retry_interval: 重试间隔(秒)
  55. :return: session token 或 None
  56. """
  57. print("开始获取cookie")
  58. attempts = 0
  59. while attempts < max_attempts:
  60. try:
  61. cookies = tab.cookies()
  62. for cookie in cookies:
  63. if cookie.get("name") == "WorkosCursorSessionToken":
  64. return cookie["value"].split("%3A%3A")[1]
  65. attempts += 1
  66. if attempts < max_attempts:
  67. print(
  68. f"第 {attempts} 次尝试未获取到CursorSessionToken,{retry_interval}秒后重试..."
  69. )
  70. time.sleep(retry_interval)
  71. else:
  72. print(f"已达到最大尝试次数({max_attempts}),获取CursorSessionToken失败")
  73. except Exception as e:
  74. print(f"获取cookie失败: {str(e)}")
  75. attempts += 1
  76. if attempts < max_attempts:
  77. print(f"将在 {retry_interval} 秒后重试...")
  78. time.sleep(retry_interval)
  79. return None
  80. def update_cursor_auth(email=None, access_token=None, refresh_token=None):
  81. """
  82. 更新Cursor的认证信息的便捷函数
  83. """
  84. auth_manager = CursorAuthManager()
  85. return auth_manager.update_auth(email, access_token, refresh_token)
  86. def sign_up_account(browser, tab):
  87. print("开始执行...")
  88. tab.get(sign_up_url)
  89. try:
  90. if tab.ele("@name=first_name"):
  91. tab.actions.click("@name=first_name").input(first_name)
  92. time.sleep(random.uniform(1, 3))
  93. tab.actions.click("@name=last_name").input(last_name)
  94. time.sleep(random.uniform(1, 3))
  95. tab.actions.click("@name=email").input(account)
  96. time.sleep(random.uniform(1, 3))
  97. tab.actions.click("@type=submit")
  98. except Exception as e:
  99. print("打开注册页面失败")
  100. return False
  101. handle_turnstile(tab)
  102. try:
  103. if tab.ele("@name=password"):
  104. tab.ele("@name=password").input(password)
  105. time.sleep(random.uniform(1, 3))
  106. tab.ele("@type=submit").click()
  107. print("请稍等...")
  108. except Exception as e:
  109. print("执行失败")
  110. return False
  111. time.sleep(random.uniform(1, 3))
  112. if tab.ele("This email is not available."):
  113. print("执行失败")
  114. return False
  115. handle_turnstile(tab)
  116. while True:
  117. try:
  118. if tab.ele("Account Settings"):
  119. break
  120. if tab.ele("@data-index=0"):
  121. code = email_handler.get_verification_code(account)
  122. if not code:
  123. return False
  124. i = 0
  125. for digit in code:
  126. tab.ele(f"@data-index={i}").input(digit)
  127. time.sleep(random.uniform(0.1, 0.3))
  128. i += 1
  129. break
  130. except Exception as e:
  131. print(e)
  132. handle_turnstile(tab)
  133. wait_time = random.randint(3, 6)
  134. for i in range(wait_time):
  135. print(f"等待中... {wait_time-i}秒")
  136. time.sleep(1)
  137. tab.get(settings_url)
  138. try:
  139. usage_selector = (
  140. "css:div.col-span-2 > div > div > div > div > "
  141. "div:nth-child(1) > div.flex.items-center.justify-between.gap-2 > "
  142. "span.font-mono.text-sm\\/\\[0\\.875rem\\]"
  143. )
  144. usage_ele = tab.ele(usage_selector)
  145. if usage_ele:
  146. usage_info = usage_ele.text
  147. total_usage = usage_info.split("/")[-1].strip()
  148. print("可用上限: " + total_usage)
  149. except Exception as e:
  150. print("获取可用上限失败")
  151. print("注册完成")
  152. account_info = f"\nCursor 账号: {account} 密码: {password}"
  153. logging.info(account_info)
  154. time.sleep(5)
  155. return True
  156. class EmailGenerator:
  157. def __init__(
  158. self,
  159. domain="mailto.plus",
  160. password="".join(
  161. random.choices(
  162. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",
  163. k=12,
  164. )
  165. ),
  166. first_name="yuyan",
  167. last_name="peng",
  168. ):
  169. self.domain = domain
  170. self.default_password = password
  171. self.default_first_name = first_name
  172. self.default_last_name = last_name
  173. def generate_email(self, length=8):
  174. """生成随机邮箱地址"""
  175. random_str = "".join(random.choices("abcdefghijklmnopqrstuvwxyz", k=length))
  176. timestamp = str(int(time.time()))[-6:] # 使用时间戳后6位
  177. return f"{random_str}{timestamp}@{self.domain}"
  178. def get_account_info(self):
  179. """获取完整的账号信息"""
  180. return {
  181. "email": self.generate_email(),
  182. "password": self.default_password,
  183. "first_name": self.default_first_name,
  184. "last_name": self.default_last_name,
  185. }
  186. if __name__ == "__main__":
  187. print_logo()
  188. browser_manager = None
  189. try:
  190. ExitCursor()
  191. # 初始化浏览器
  192. browser_manager = BrowserManager()
  193. browser = browser_manager.init_browser()
  194. # 初始化邮箱验证处理器
  195. email_handler = EmailVerificationHandler(browser)
  196. # 固定的 URL 配置
  197. login_url = "https://authenticator.cursor.sh"
  198. sign_up_url = "https://authenticator.cursor.sh/sign-up"
  199. settings_url = "https://www.cursor.com/settings"
  200. mail_url = "https://tempmail.plus"
  201. # 生成随机邮箱
  202. email_generator = EmailGenerator()
  203. account = email_generator.generate_email()
  204. password = email_generator.default_password
  205. first_name = email_generator.default_first_name
  206. last_name = email_generator.default_last_name
  207. auto_update_cursor_auth = True
  208. tab = browser.latest_tab
  209. tab.run_js("try { turnstile.reset() } catch(e) { }")
  210. tab.get(login_url)
  211. if sign_up_account(browser, tab):
  212. token = get_cursor_session_token(tab)
  213. if token:
  214. update_cursor_auth(
  215. email=account, access_token=token, refresh_token=token
  216. )
  217. else:
  218. print("账户注册失败")
  219. print("执行完毕")
  220. except Exception as e:
  221. logging.error(f"程序执行出错: {str(e)}")
  222. import traceback
  223. logging.error(traceback.format_exc())
  224. finally:
  225. if browser_manager:
  226. browser_manager.quit()
  227. input("\n按回车键退出...")