cursor_pro_keep_alive.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. logging.info("正在检测 Turnstile 验证...")
  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. logging.info("检测到 Turnstile 验证,正在处理...")
  29. time.sleep(random.uniform(1, 3))
  30. challengeCheck.click()
  31. time.sleep(2)
  32. logging.info("Turnstile 验证通过")
  33. return True
  34. except:
  35. pass
  36. if tab.ele("@name=password"):
  37. logging.info("验证成功 - 已到达密码输入页面")
  38. break
  39. if tab.ele("@data-index=0"):
  40. logging.info("验证成功 - 已到达验证码输入页面")
  41. break
  42. if tab.ele("Account Settings"):
  43. logging.info("验证成功 - 已到达账户设置页面")
  44. break
  45. time.sleep(random.uniform(1, 2))
  46. except Exception as e:
  47. logging.error(f"Turnstile 验证失败: {str(e)}")
  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. logging.info("开始获取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. logging.warning(
  68. f"第 {attempts} 次尝试未获取到CursorSessionToken,{retry_interval}秒后重试..."
  69. )
  70. time.sleep(retry_interval)
  71. else:
  72. logging.error(
  73. f"已达到最大尝试次数({max_attempts}),获取CursorSessionToken失败"
  74. )
  75. except Exception as e:
  76. logging.error(f"获取cookie失败: {str(e)}")
  77. attempts += 1
  78. if attempts < max_attempts:
  79. logging.info(f"将在 {retry_interval} 秒后重试...")
  80. time.sleep(retry_interval)
  81. return None
  82. def update_cursor_auth(email=None, access_token=None, refresh_token=None):
  83. """
  84. 更新Cursor的认证信息的便捷函数
  85. """
  86. auth_manager = CursorAuthManager()
  87. return auth_manager.update_auth(email, access_token, refresh_token)
  88. def sign_up_account(browser, tab):
  89. logging.info("=== 开始注册账号流程 ===")
  90. logging.info(f"正在访问注册页面: {sign_up_url}")
  91. tab.get(sign_up_url)
  92. try:
  93. if tab.ele("@name=first_name"):
  94. logging.info("正在填写个人信息...")
  95. tab.actions.click("@name=first_name").input(first_name)
  96. logging.info(f"已输入名字: {first_name}")
  97. time.sleep(random.uniform(1, 3))
  98. tab.actions.click("@name=last_name").input(last_name)
  99. logging.info(f"已输入姓氏: {last_name}")
  100. time.sleep(random.uniform(1, 3))
  101. tab.actions.click("@name=email").input(account)
  102. logging.info(f"已输入邮箱: {account}")
  103. time.sleep(random.uniform(1, 3))
  104. logging.info("提交个人信息...")
  105. tab.actions.click("@type=submit")
  106. except Exception as e:
  107. logging.error(f"注册页面访问失败: {str(e)}")
  108. return False
  109. handle_turnstile(tab)
  110. try:
  111. if tab.ele("@name=password"):
  112. logging.info("正在设置密码...")
  113. tab.ele("@name=password").input(password)
  114. time.sleep(random.uniform(1, 3))
  115. logging.info("提交密码...")
  116. tab.ele("@type=submit").click()
  117. logging.info("密码设置完成,等待系统响应...")
  118. except Exception as e:
  119. logging.error(f"密码设置失败: {str(e)}")
  120. return False
  121. time.sleep(random.uniform(1, 3))
  122. if tab.ele("This email is not available."):
  123. logging.error("注册失败:邮箱已被使用")
  124. return False
  125. handle_turnstile(tab)
  126. while True:
  127. try:
  128. if tab.ele("Account Settings"):
  129. logging.info("注册成功 - 已进入账户设置页面")
  130. break
  131. if tab.ele("@data-index=0"):
  132. logging.info("正在获取邮箱验证码...")
  133. code = email_handler.get_verification_code(account)
  134. if not code:
  135. logging.error("获取验证码失败")
  136. return False
  137. logging.info(f"成功获取验证码: {code}")
  138. logging.info("正在输入验证码...")
  139. i = 0
  140. for digit in code:
  141. tab.ele(f"@data-index={i}").input(digit)
  142. time.sleep(random.uniform(0.1, 0.3))
  143. i += 1
  144. logging.info("验证码输入完成")
  145. break
  146. except Exception as e:
  147. logging.error(f"验证码处理过程出错: {str(e)}")
  148. handle_turnstile(tab)
  149. wait_time = random.randint(3, 6)
  150. for i in range(wait_time):
  151. logging.info(f"等待系统处理中... 剩余 {wait_time-i} 秒")
  152. time.sleep(1)
  153. logging.info("正在获取账户信息...")
  154. tab.get(settings_url)
  155. try:
  156. usage_selector = (
  157. "css:div.col-span-2 > div > div > div > div > "
  158. "div:nth-child(1) > div.flex.items-center.justify-between.gap-2 > "
  159. "span.font-mono.text-sm\\/\\[0\\.875rem\\]"
  160. )
  161. usage_ele = tab.ele(usage_selector)
  162. if usage_ele:
  163. usage_info = usage_ele.text
  164. total_usage = usage_info.split("/")[-1].strip()
  165. logging.info(f"账户可用额度上限: {total_usage}")
  166. else:
  167. logging.error("无法获取账户额度信息")
  168. return False
  169. except Exception as e:
  170. logging.error(f"获取账户额度信息失败: {str(e)}")
  171. logging.info("\n=== 注册完成 ===")
  172. account_info = f"Cursor 账号信息:\n邮箱: {account}\n密码: {password}"
  173. logging.info(account_info)
  174. time.sleep(5)
  175. return True
  176. class EmailGenerator:
  177. def __init__(
  178. self,
  179. password="".join(
  180. random.choices(
  181. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",
  182. k=12,
  183. )
  184. ),
  185. ):
  186. configInstance = Config()
  187. configInstance.print_config()
  188. self.default_password = password
  189. self.default_first_name = self.generate_random_name()
  190. self.default_last_name = self.generate_random_name()
  191. def generate_random_name(self, length=6):
  192. """生成随机用户名"""
  193. first_letter = random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
  194. rest_letters = "".join(
  195. random.choices("abcdefghijklmnopqrstuvwxyz", k=length - 1)
  196. )
  197. return first_letter + rest_letters
  198. def generate_email(self, length=8):
  199. """获取可用的邮箱地址"""
  200. try:
  201. email_handler = EmailVerificationHandler()
  202. email_handler._create_mailbox()
  203. email_list = email_handler._get_email_list()
  204. if email_list and len(email_list) > 0:
  205. return email_list[-1] # 直接返回最后一个邮箱地址
  206. raise Exception("无法获取可用的邮箱地址")
  207. except Exception as e:
  208. logging.error(f"获取邮箱地址失败: {str(e)}")
  209. raise
  210. def get_account_info(self):
  211. """获取完整的账号信息"""
  212. return {
  213. "email": self.generate_email(),
  214. "password": self.default_password,
  215. "first_name": self.default_first_name,
  216. "last_name": self.default_last_name,
  217. }
  218. if __name__ == "__main__":
  219. print_logo()
  220. browser_manager = None
  221. try:
  222. logging.info("\n=== 初始化程序 ===")
  223. ExitCursor()
  224. logging.info("正在初始化浏览器...")
  225. browser_manager = BrowserManager()
  226. browser = browser_manager.init_browser()
  227. logging.info("正在初始化邮箱验证模块...")
  228. email_handler = EmailVerificationHandler()
  229. logging.info("\n=== 配置信息 ===")
  230. login_url = "https://authenticator.cursor.sh"
  231. sign_up_url = "https://authenticator.cursor.sh/sign-up"
  232. settings_url = "https://www.cursor.com/settings"
  233. logging.info("正在生成随机账号信息...")
  234. email_generator = EmailGenerator()
  235. account = email_generator.generate_email()
  236. password = email_generator.default_password
  237. first_name = email_generator.default_first_name
  238. last_name = email_generator.default_last_name
  239. logging.info(f"生成的邮箱账号: {account}")
  240. auto_update_cursor_auth = True
  241. tab = browser.latest_tab
  242. tab.run_js("try { turnstile.reset() } catch(e) { }")
  243. logging.info("\n=== 开始注册流程 ===")
  244. logging.info(f"正在访问登录页面: {login_url}")
  245. tab.get(login_url)
  246. if sign_up_account(browser, tab):
  247. logging.info("正在获取会话令牌...")
  248. token = get_cursor_session_token(tab)
  249. if token:
  250. logging.info("更新认证信息...")
  251. update_cursor_auth(
  252. email=account, access_token=token, refresh_token=token
  253. )
  254. logging.info("重置机器码...")
  255. MachineIDResetter().reset_machine_ids()
  256. logging.info("所有操作已完成")
  257. else:
  258. logging.error("获取会话令牌失败,注册流程未完成")
  259. except Exception as e:
  260. logging.error(f"程序执行出现错误: {str(e)}")
  261. import traceback
  262. logging.error(traceback.format_exc())
  263. finally:
  264. if browser_manager:
  265. browser_manager.quit()
  266. input("\n程序执行完毕,按回车键退出...")