cursor_pro_keep_alive.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import os
  2. from exit_cursor import ExitCursor
  3. from reset_machine import MachineIDResetter
  4. os.environ["PYTHONVERBOSE"] = "0"
  5. os.environ["PYINSTALLER_VERBOSE"] = "0"
  6. import time
  7. import random
  8. from cursor_auth_manager import CursorAuthManager
  9. import os
  10. from logger import logging
  11. from browser_utils import BrowserManager
  12. from get_email_code import EmailVerificationHandler
  13. from logo import print_logo
  14. from config import Config
  15. def handle_turnstile(tab):
  16. print("开始突破难关")
  17. try:
  18. while True:
  19. try:
  20. challengeCheck = (
  21. tab.ele("@id=cf-turnstile", timeout=2)
  22. .child()
  23. .shadow_root.ele("tag:iframe")
  24. .ele("tag:body")
  25. .sr("tag:input")
  26. )
  27. if challengeCheck:
  28. print("开始突破")
  29. time.sleep(random.uniform(1, 3))
  30. challengeCheck.click()
  31. time.sleep(2)
  32. print("突破成功")
  33. return True
  34. except:
  35. pass
  36. if tab.ele("@name=password"):
  37. print("突破成功")
  38. break
  39. if tab.ele("@data-index=0"):
  40. print("突破成功")
  41. break
  42. if tab.ele("Account Settings"):
  43. print("突破成功")
  44. break
  45. time.sleep(random.uniform(1, 2))
  46. except Exception as e:
  47. print(e)
  48. print("突破失败")
  49. return False
  50. def get_cursor_session_token(tab, max_attempts=3, retry_interval=2):
  51. """
  52. 获取Cursor会话token,带有重试机制
  53. :param tab: 浏览器标签页
  54. :param max_attempts: 最大尝试次数
  55. :param retry_interval: 重试间隔(秒)
  56. :return: session token 或 None
  57. """
  58. print("开始获取cookie")
  59. attempts = 0
  60. while attempts < max_attempts:
  61. try:
  62. cookies = tab.cookies()
  63. for cookie in cookies:
  64. if cookie.get("name") == "WorkosCursorSessionToken":
  65. return cookie["value"].split("%3A%3A")[1]
  66. attempts += 1
  67. if attempts < max_attempts:
  68. print(
  69. f"第 {attempts} 次尝试未获取到CursorSessionToken,{retry_interval}秒后重试..."
  70. )
  71. time.sleep(retry_interval)
  72. else:
  73. print(f"已达到最大尝试次数({max_attempts}),获取CursorSessionToken失败")
  74. except Exception as e:
  75. print(f"获取cookie失败: {str(e)}")
  76. attempts += 1
  77. if attempts < max_attempts:
  78. print(f"将在 {retry_interval} 秒后重试...")
  79. time.sleep(retry_interval)
  80. return None
  81. def update_cursor_auth(email=None, access_token=None, refresh_token=None):
  82. """
  83. 更新Cursor的认证信息的便捷函数
  84. """
  85. auth_manager = CursorAuthManager()
  86. return auth_manager.update_auth(email, access_token, refresh_token)
  87. def sign_up_account(browser, tab):
  88. print("开始执行...")
  89. tab.get(sign_up_url)
  90. try:
  91. if tab.ele("@name=first_name"):
  92. tab.actions.click("@name=first_name").input(first_name)
  93. time.sleep(random.uniform(1, 3))
  94. tab.actions.click("@name=last_name").input(last_name)
  95. time.sleep(random.uniform(1, 3))
  96. tab.actions.click("@name=email").input(account)
  97. time.sleep(random.uniform(1, 3))
  98. tab.actions.click("@type=submit")
  99. except Exception as e:
  100. print("打开注册页面失败")
  101. return False
  102. handle_turnstile(tab)
  103. try:
  104. if tab.ele("@name=password"):
  105. tab.ele("@name=password").input(password)
  106. time.sleep(random.uniform(1, 3))
  107. tab.ele("@type=submit").click()
  108. print("请稍等...")
  109. except Exception as e:
  110. print("执行失败")
  111. return False
  112. time.sleep(random.uniform(1, 3))
  113. if tab.ele("This email is not available."):
  114. print("执行失败")
  115. return False
  116. handle_turnstile(tab)
  117. while True:
  118. try:
  119. if tab.ele("Account Settings"):
  120. break
  121. if tab.ele("@data-index=0"):
  122. code = email_handler.get_verification_code(account)
  123. if not code:
  124. return False
  125. i = 0
  126. for digit in code:
  127. tab.ele(f"@data-index={i}").input(digit)
  128. time.sleep(random.uniform(0.1, 0.3))
  129. i += 1
  130. break
  131. except Exception as e:
  132. print(e)
  133. handle_turnstile(tab)
  134. wait_time = random.randint(3, 6)
  135. for i in range(wait_time):
  136. print(f"等待中... {wait_time-i}秒")
  137. time.sleep(1)
  138. tab.get(settings_url)
  139. try:
  140. usage_selector = (
  141. "css:div.col-span-2 > div > div > div > div > "
  142. "div:nth-child(1) > div.flex.items-center.justify-between.gap-2 > "
  143. "span.font-mono.text-sm\\/\\[0\\.875rem\\]"
  144. )
  145. usage_ele = tab.ele(usage_selector)
  146. if usage_ele:
  147. usage_info = usage_ele.text
  148. total_usage = usage_info.split("/")[-1].strip()
  149. print("可用上限: " + total_usage)
  150. except Exception as e:
  151. print("获取可用上限失败")
  152. print("注册完成")
  153. account_info = f"\nCursor 账号: {account} 密码: {password}"
  154. logging.info(account_info)
  155. time.sleep(5)
  156. return True
  157. class EmailGenerator:
  158. def __init__(
  159. self,
  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 = Config().get_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. MachineIDResetter().reset_machine_ids()
  218. else:
  219. print("账户注册失败")
  220. print("执行完毕")
  221. except Exception as e:
  222. logging.error(f"程序执行出错: {str(e)}")
  223. import traceback
  224. logging.error(traceback.format_exc())
  225. finally:
  226. if browser_manager:
  227. browser_manager.quit()
  228. input("\n按回车键退出...")