cursor_pro_keep_alive.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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.INFO,
  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. print("注册完成")
  263. account_info = f"\nCursor 账号: {account} 密码: {password}"
  264. logging.info(account_info)
  265. time.sleep(5)
  266. return True
  267. def cleanup_temp_files():
  268. """清理临时文件和缓存"""
  269. try:
  270. temp_dirs = [
  271. os.path.join(os.getcwd(), "__pycache__"),
  272. os.path.join(os.getcwd(), "build"),
  273. ]
  274. for dir_path in temp_dirs:
  275. if os.path.exists(dir_path):
  276. import shutil
  277. shutil.rmtree(dir_path)
  278. except Exception as e:
  279. logging.warning(f"清理临时文件失败: {str(e)}")
  280. class EmailGenerator:
  281. def __init__(
  282. self,
  283. domain="mailto.plus",
  284. password="".join(
  285. random.choices(
  286. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",
  287. k=12,
  288. )
  289. ),
  290. first_name="yuyan",
  291. last_name="peng",
  292. ):
  293. self.domain = domain
  294. self.default_password = password
  295. self.default_first_name = first_name
  296. self.default_last_name = last_name
  297. def generate_email(self, length=8):
  298. """生成随机邮箱地址"""
  299. random_str = "".join(random.choices("abcdefghijklmnopqrstuvwxyz", k=length))
  300. timestamp = str(int(time.time()))[-6:] # 使用时间戳后6位
  301. return f"{random_str}{timestamp}@{self.domain}"
  302. def get_account_info(self):
  303. """获取完整的账号信息"""
  304. return {
  305. "email": self.generate_email(),
  306. "password": self.default_password,
  307. "first_name": self.default_first_name,
  308. "last_name": self.default_last_name,
  309. }
  310. if __name__ == "__main__":
  311. browser_manager = None
  312. try:
  313. license_manager = LicenseManager()
  314. # 验证许可证
  315. is_valid, message = license_manager.verify_license()
  316. if not is_valid:
  317. print(f"许可证验证失败: {message}")
  318. # 提示用户激活
  319. license_key = input("请输入激活码: ")
  320. success, activate_message = license_manager.activate_license(license_key)
  321. if not success:
  322. print(f"激活失败: {activate_message}")
  323. sys.exit(1)
  324. print("激活成功!")
  325. # 初始化浏览器
  326. browser_manager = BrowserManager()
  327. browser = browser_manager.init_browser()
  328. # 初始化邮箱验证处理器
  329. email_handler = EmailVerificationHandler(browser)
  330. # 固定的 URL 配置
  331. login_url = "https://authenticator.cursor.sh"
  332. sign_up_url = "https://authenticator.cursor.sh/sign-up"
  333. settings_url = "https://www.cursor.com/settings"
  334. mail_url = "https://tempmail.plus"
  335. # 生成随机邮箱
  336. email_generator = EmailGenerator()
  337. account = email_generator.generate_email()
  338. password = email_generator.default_password
  339. first_name = email_generator.default_first_name
  340. last_name = email_generator.default_last_name
  341. auto_update_cursor_auth = True
  342. tab = browser.latest_tab
  343. tab.run_js("try { turnstile.reset() } catch(e) { }")
  344. tab.get(login_url)
  345. if sign_up_account(browser, tab):
  346. token = get_cursor_session_token(tab)
  347. if token:
  348. update_cursor_auth(
  349. email=account, access_token=token, refresh_token=token
  350. )
  351. else:
  352. print("账户注册失败")
  353. print("脚本执行完毕")
  354. except Exception as e:
  355. logging.error(f"程序执行出错: {str(e)}")
  356. import traceback
  357. logging.error(traceback.format_exc())
  358. finally:
  359. if browser_manager:
  360. browser_manager.quit()
  361. input("\n按回车键退出...")