cursor_pro_keep_alive.py 8.2 KB

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