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