cursor_pro_keep_alive.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. import os
  2. from license_manager import LicenseManager
  3. os.environ["PYTHONVERBOSE"] = "0"
  4. os.environ["PYINSTALLER_VERBOSE"] = "0"
  5. import re
  6. import time
  7. import random
  8. from cursor_auth_manager import CursorAuthManager
  9. import os
  10. import sys
  11. import logging
  12. from browser_utils import BrowserManager
  13. from get_veri_code import EmailVerificationHandler
  14. # 在文件开头设置日志
  15. logging.basicConfig(
  16. level=logging.WARNING,
  17. format="%(asctime)s - %(levelname)s - %(message)s",
  18. handlers=[
  19. logging.StreamHandler(),
  20. logging.FileHandler("cursor_keep_alive.log", encoding="utf-8"),
  21. ],
  22. )
  23. def handle_turnstile(tab):
  24. """处理 Turnstile 验证"""
  25. print("准备处理验证")
  26. try:
  27. while True:
  28. try:
  29. challengeCheck = (
  30. tab.ele("@id=cf-turnstile", timeout=2)
  31. .child()
  32. .shadow_root.ele("tag:iframe")
  33. .ele("tag:body")
  34. .sr("tag:input")
  35. )
  36. if challengeCheck:
  37. print("验证框加载完成")
  38. time.sleep(random.uniform(1, 3))
  39. challengeCheck.click()
  40. print("验证按钮已点击,等待验证完成...")
  41. time.sleep(2)
  42. return True
  43. except:
  44. pass
  45. if tab.ele("@name=password"):
  46. print("无需验证")
  47. break
  48. if tab.ele("@data-index=0"):
  49. print("无需验证")
  50. break
  51. if tab.ele("Account Settings"):
  52. print("无需验证")
  53. break
  54. time.sleep(random.uniform(1, 2))
  55. except Exception as e:
  56. print(e)
  57. print("跳过验证")
  58. return False
  59. def delete_account(browser, tab):
  60. """删除账户流程"""
  61. print("\n开始删除账户...")
  62. try:
  63. if tab.ele("@name=email"):
  64. tab.ele("@name=email").input(account)
  65. print("输入账号")
  66. time.sleep(random.uniform(1, 3))
  67. except Exception as e:
  68. print(f"输入账号失败: {str(e)}")
  69. try:
  70. if tab.ele("Continue"):
  71. tab.ele("Continue").click()
  72. print("点击Continue")
  73. except Exception as e:
  74. print(f"点击Continue失败: {str(e)}")
  75. handle_turnstile(tab)
  76. time.sleep(5)
  77. try:
  78. if tab.ele("@name=password"):
  79. tab.ele("@name=password").input(password)
  80. print("输入密码")
  81. time.sleep(random.uniform(1, 3))
  82. except Exception as e:
  83. print("输入密码失败")
  84. sign_in_button = tab.ele(
  85. "xpath:/html/body/div[1]/div/div/div[2]/div/form/div/button"
  86. )
  87. try:
  88. if sign_in_button:
  89. sign_in_button.click(by_js=True)
  90. print("点击Sign in")
  91. except Exception as e:
  92. print(f"点击Sign in失败: {str(e)}")
  93. handle_turnstile(tab)
  94. # 处理验证码
  95. while True:
  96. try:
  97. if tab.ele("Invalid email or password"):
  98. print("Invalid email or password")
  99. return False
  100. if tab.ele("Account Settings"):
  101. break
  102. if tab.ele("@data-index=0"):
  103. code = email_handler.get_verification_code(account)
  104. if code:
  105. print("获取验证码成功:", code)
  106. else:
  107. print("获取验证码失败,程序退出")
  108. return False
  109. i = 0
  110. for digit in code:
  111. tab.ele(f"@data-index={i}").input(digit)
  112. time.sleep(random.uniform(0.1, 0.3))
  113. i += 1
  114. break
  115. except Exception as e:
  116. print(e)
  117. handle_turnstile(tab)
  118. time.sleep(5)
  119. tab.get(settings_url)
  120. print("进入设置页面")
  121. try:
  122. if tab.ele("@class=mt-1"):
  123. tab.ele("@class=mt-1").click()
  124. print("点击Adavance")
  125. time.sleep(random.uniform(1, 2))
  126. except Exception as e:
  127. print(f"点击Adavance失败: {str(e)}")
  128. try:
  129. if tab.ele("Delete Account"):
  130. tab.ele("Delete Account").click()
  131. print("点击Delete Account")
  132. time.sleep(random.uniform(1, 2))
  133. except Exception as e:
  134. print(f"点击Delete Account失败: {str(e)}")
  135. try:
  136. if tab.ele("tag:input"):
  137. tab.actions.click("tag:input").type("delete")
  138. print("输入delete")
  139. time.sleep(random.uniform(1, 2))
  140. except Exception as e:
  141. print(f"输入delete失败: {str(e)}")
  142. delete_button = tab.ele(
  143. "xpath:/html/body/main/div/div/div/div/div/div[1]/div[2]/div[3]/div[2]/div/div/div[2]/button[2]"
  144. )
  145. try:
  146. if delete_button:
  147. print("点击Delete")
  148. delete_button.click()
  149. time.sleep(5)
  150. # tab.get_screenshot('delete_account.png')
  151. # print("删除账户截图")
  152. return True
  153. except Exception as e:
  154. print(f"点击Delete失败: {str(e)}")
  155. return False
  156. def get_cursor_session_token(tab, max_attempts=3, retry_interval=2):
  157. """
  158. 获取Cursor会话token,带有重试机制
  159. :param tab: 浏览器标签页
  160. :param max_attempts: 最大尝试次数
  161. :param retry_interval: 重试间隔(秒)
  162. :return: session token 或 None
  163. """
  164. print("开始获取cookie")
  165. attempts = 0
  166. while attempts < max_attempts:
  167. try:
  168. cookies = tab.cookies()
  169. for cookie in cookies:
  170. if cookie.get("name") == "WorkosCursorSessionToken":
  171. return cookie["value"].split("%3A%3A")[1]
  172. attempts += 1
  173. if attempts < max_attempts:
  174. print(
  175. f"第 {attempts} 次尝试未获取到CursorSessionToken,{retry_interval}秒后重试..."
  176. )
  177. time.sleep(retry_interval)
  178. else:
  179. print(f"已达到最大尝试次数({max_attempts}),获取CursorSessionToken失败")
  180. except Exception as e:
  181. print(f"获取cookie失败: {str(e)}")
  182. attempts += 1
  183. if attempts < max_attempts:
  184. print(f"将在 {retry_interval} 秒后重试...")
  185. time.sleep(retry_interval)
  186. return None
  187. def update_cursor_auth(email=None, access_token=None, refresh_token=None):
  188. """
  189. 更新Cursor的认证信息的便捷函数
  190. """
  191. auth_manager = CursorAuthManager()
  192. return auth_manager.update_auth(email, access_token, refresh_token)
  193. def sign_up_account(browser, tab):
  194. print("\n开始注册新账户...")
  195. tab.get(sign_up_url)
  196. try:
  197. if tab.ele("@name=first_name"):
  198. print("已打开注册页面")
  199. tab.actions.click("@name=first_name").input(first_name)
  200. time.sleep(random.uniform(1, 3))
  201. tab.actions.click("@name=last_name").input(last_name)
  202. time.sleep(random.uniform(1, 3))
  203. tab.actions.click("@name=email").input(account)
  204. print("输入邮箱")
  205. time.sleep(random.uniform(1, 3))
  206. tab.actions.click("@type=submit")
  207. print("点击注册按钮")
  208. except Exception as e:
  209. print("打开注册页面失败")
  210. return False
  211. handle_turnstile(tab)
  212. try:
  213. if tab.ele("@name=password"):
  214. tab.ele("@name=password").input(password)
  215. print("输入密码")
  216. time.sleep(random.uniform(1, 3))
  217. tab.ele("@type=submit").click()
  218. print("点击Continue按钮")
  219. except Exception as e:
  220. print("输入密码失败")
  221. return False
  222. time.sleep(random.uniform(1, 3))
  223. if tab.ele("This email is not available."):
  224. print("This email is not available.")
  225. return False
  226. handle_turnstile(tab)
  227. while True:
  228. try:
  229. if tab.ele("Account Settings"):
  230. break
  231. if tab.ele("@data-index=0"):
  232. code = email_handler.get_verification_code(account)
  233. if not code:
  234. return False
  235. i = 0
  236. for digit in code:
  237. tab.ele(f"@data-index={i}").input(digit)
  238. time.sleep(random.uniform(0.1, 0.3))
  239. i += 1
  240. break
  241. except Exception as e:
  242. print(e)
  243. handle_turnstile(tab)
  244. wait_time = random.randint(3, 6)
  245. for i in range(wait_time):
  246. print(f"等待中... {wait_time-i}秒")
  247. time.sleep(1)
  248. tab.get(settings_url)
  249. try:
  250. usage_selector = (
  251. "css:div.col-span-2 > div > div > div > div > "
  252. "div:nth-child(1) > div.flex.items-center.justify-between.gap-2 > "
  253. "span.font-mono.text-sm\\/\\[0\\.875rem\\]"
  254. )
  255. usage_ele = tab.ele(usage_selector)
  256. if usage_ele:
  257. usage_info = usage_ele.text
  258. total_usage = usage_info.split("/")[-1].strip()
  259. print("可用上限: " + total_usage)
  260. except Exception as e:
  261. print("获取可用上限失败")
  262. # tab.get_screenshot("sign_up_success.png")
  263. # print("注册账户截图")
  264. print("注册完成")
  265. print("Cursor 账号: " + account)
  266. print(" 密码: " + password)
  267. time.sleep(5)
  268. return True
  269. def cleanup_temp_files():
  270. """清理临时文件和缓存"""
  271. try:
  272. temp_dirs = [
  273. os.path.join(os.getcwd(), "__pycache__"),
  274. os.path.join(os.getcwd(), "build"),
  275. ]
  276. for dir_path in temp_dirs:
  277. if os.path.exists(dir_path):
  278. import shutil
  279. shutil.rmtree(dir_path)
  280. except Exception as e:
  281. logging.warning(f"清理临时文件失败: {str(e)}")
  282. class EmailGenerator:
  283. def __init__(
  284. self,
  285. domain="mailto.plus",
  286. password="".join(
  287. random.choices(
  288. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",
  289. k=12,
  290. )
  291. ),
  292. first_name="yuyan",
  293. last_name="peng",
  294. ):
  295. self.domain = domain
  296. self.default_password = password
  297. self.default_first_name = first_name
  298. self.default_last_name = last_name
  299. def generate_email(self, length=8):
  300. """生成随机邮箱地址"""
  301. random_str = "".join(random.choices("abcdefghijklmnopqrstuvwxyz", k=length))
  302. timestamp = str(int(time.time()))[-6:] # 使用时间戳后6位
  303. return f"{random_str}{timestamp}@{self.domain}"
  304. def get_account_info(self):
  305. """获取完整的账号信息"""
  306. return {
  307. "email": self.generate_email(),
  308. "password": self.default_password,
  309. "first_name": self.default_first_name,
  310. "last_name": self.default_last_name,
  311. }
  312. if __name__ == "__main__":
  313. browser_manager = None
  314. try:
  315. license_manager = LicenseManager()
  316. # 验证许可证
  317. is_valid, message = license_manager.verify_license()
  318. if not is_valid:
  319. print(f"许可证验证失败: {message}")
  320. # 提示用户激活
  321. license_key = input("请输入激活码: ")
  322. success, activate_message = license_manager.activate_license(license_key)
  323. if not success:
  324. print(f"激活失败: {activate_message}")
  325. sys.exit(1)
  326. print("激活成功!")
  327. # 初始化浏览器
  328. browser_manager = BrowserManager()
  329. browser = browser_manager.init_browser()
  330. # 初始化邮箱验证处理器
  331. email_handler = EmailVerificationHandler(browser)
  332. # 固定的 URL 配置
  333. login_url = "https://authenticator.cursor.sh"
  334. sign_up_url = "https://authenticator.cursor.sh/sign-up"
  335. settings_url = "https://www.cursor.com/settings"
  336. mail_url = "https://tempmail.plus"
  337. # 生成随机邮箱
  338. email_generator = EmailGenerator()
  339. account = email_generator.generate_email()
  340. password = email_generator.default_password
  341. first_name = email_generator.default_first_name
  342. last_name = email_generator.default_last_name
  343. auto_update_cursor_auth = True
  344. tab = browser.latest_tab
  345. tab.run_js("try { turnstile.reset() } catch(e) { }")
  346. tab.get(login_url)
  347. if sign_up_account(browser, tab):
  348. token = get_cursor_session_token(tab)
  349. if token:
  350. update_cursor_auth(
  351. email=account, access_token=token, refresh_token=token
  352. )
  353. else:
  354. print("账户注册失败")
  355. print("脚本执行完毕")
  356. except Exception as e:
  357. logging.error(f"程序执行出错: {str(e)}")
  358. import traceback
  359. logging.error(traceback.format_exc())
  360. finally:
  361. if browser_manager:
  362. browser_manager.quit()
  363. input("\n按回车键退出...")