cursor_pro_keep_alive.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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):
  157. print("开始获取cookie")
  158. try:
  159. # 获取指定域名的所有cookies
  160. cookies = tab.cookies()
  161. for cookie in cookies:
  162. if cookie.get("name") == "WorkosCursorSessionToken":
  163. return cookie["value"].split("%3A%3A")[1]
  164. print("未能获取到CursorSessionToken")
  165. return None
  166. except Exception as e:
  167. print(f"获取cookie失败: {str(e)}")
  168. return None
  169. def update_cursor_auth(email=None, access_token=None, refresh_token=None):
  170. """
  171. 更新Cursor的认证信息的便捷函数
  172. """
  173. auth_manager = CursorAuthManager()
  174. return auth_manager.update_auth(email, access_token, refresh_token)
  175. def sign_up_account(browser, tab):
  176. print("\n开始注册新账户...")
  177. tab.get(sign_up_url)
  178. try:
  179. if tab.ele("@name=first_name"):
  180. print("已打开注册页面")
  181. tab.actions.click("@name=first_name").input(first_name)
  182. time.sleep(random.uniform(1, 3))
  183. tab.actions.click("@name=last_name").input(last_name)
  184. time.sleep(random.uniform(1, 3))
  185. tab.actions.click("@name=email").input(account)
  186. print("输入邮箱")
  187. time.sleep(random.uniform(1, 3))
  188. tab.actions.click("@type=submit")
  189. print("点击注册按钮")
  190. except Exception as e:
  191. print("打开注册页面失败")
  192. return False
  193. handle_turnstile(tab)
  194. try:
  195. if tab.ele("@name=password"):
  196. tab.ele("@name=password").input(password)
  197. print("输入密码")
  198. time.sleep(random.uniform(1, 3))
  199. tab.ele("@type=submit").click()
  200. print("点击Continue按钮")
  201. except Exception as e:
  202. print("输入密码失败")
  203. return False
  204. time.sleep(random.uniform(1, 3))
  205. if tab.ele("This email is not available."):
  206. print("This email is not available.")
  207. return False
  208. handle_turnstile(tab)
  209. while True:
  210. try:
  211. if tab.ele("Account Settings"):
  212. break
  213. if tab.ele("@data-index=0"):
  214. code = email_handler.get_verification_code(account)
  215. if not code:
  216. return False
  217. i = 0
  218. for digit in code:
  219. tab.ele(f"@data-index={i}").input(digit)
  220. time.sleep(random.uniform(0.1, 0.3))
  221. i += 1
  222. break
  223. except Exception as e:
  224. print(e)
  225. handle_turnstile(tab)
  226. print("等待进入设置页面")
  227. # 等待页面加载完成
  228. max_wait_time = 30 # 最大等待时间(秒)
  229. start_time = time.time()
  230. while time.time() - start_time < max_wait_time:
  231. try:
  232. # 检查页面是否仍在加载
  233. is_loading = tab.run_js("return document.readyState !== 'complete'")
  234. if not is_loading:
  235. break
  236. time.sleep(1)
  237. except Exception as e:
  238. print(f"检查页面加载状态时出错: {str(e)}")
  239. break
  240. print("进入设置页面")
  241. tab.get(settings_url)
  242. try:
  243. usage_selector = (
  244. "css:div.col-span-2 > div > div > div > div > "
  245. "div:nth-child(1) > div.flex.items-center.justify-between.gap-2 > "
  246. "span.font-mono.text-sm\\/\\[0\\.875rem\\]"
  247. )
  248. usage_ele = tab.ele(usage_selector)
  249. if usage_ele:
  250. usage_info = usage_ele.text
  251. total_usage = usage_info.split("/")[-1].strip()
  252. print("可用上限: " + total_usage)
  253. except Exception as e:
  254. print("获取可用上限失败")
  255. # tab.get_screenshot("sign_up_success.png")
  256. # print("注册账户截图")
  257. print("注册完成")
  258. print("Cursor 账号: " + account)
  259. print(" 密码: " + password)
  260. time.sleep(5)
  261. return True
  262. def cleanup_temp_files():
  263. """清理临时文件和缓存"""
  264. try:
  265. temp_dirs = [
  266. os.path.join(os.getcwd(), "__pycache__"),
  267. os.path.join(os.getcwd(), "build"),
  268. ]
  269. for dir_path in temp_dirs:
  270. if os.path.exists(dir_path):
  271. import shutil
  272. shutil.rmtree(dir_path)
  273. except Exception as e:
  274. logging.warning(f"清理临时文件失败: {str(e)}")
  275. class EmailGenerator:
  276. def __init__(
  277. self,
  278. domain="mailto.plus",
  279. password="".join(
  280. random.choices(
  281. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",
  282. k=12,
  283. )
  284. ),
  285. first_name="yuyan",
  286. last_name="peng",
  287. ):
  288. self.domain = domain
  289. self.default_password = password
  290. self.default_first_name = first_name
  291. self.default_last_name = last_name
  292. def generate_email(self, length=8):
  293. """生成随机邮箱地址"""
  294. random_str = "".join(random.choices("abcdefghijklmnopqrstuvwxyz", k=length))
  295. timestamp = str(int(time.time()))[-6:] # 使用时间戳后6位
  296. return f"{random_str}{timestamp}@{self.domain}"
  297. def get_account_info(self):
  298. """获取完整的账号信息"""
  299. return {
  300. "email": self.generate_email(),
  301. "password": self.default_password,
  302. "first_name": self.default_first_name,
  303. "last_name": self.default_last_name,
  304. }
  305. if __name__ == "__main__":
  306. browser_manager = None
  307. try:
  308. license_manager = LicenseManager()
  309. # 验证许可证
  310. is_valid, message = license_manager.verify_license()
  311. if not is_valid:
  312. print(f"许可证验证失败: {message}")
  313. # 提示用户激活
  314. license_key = input("请输入激活码: ")
  315. success, activate_message = license_manager.activate_license(license_key)
  316. if not success:
  317. print(f"激活失败: {activate_message}")
  318. sys.exit(1)
  319. print("激活成功!")
  320. # 初始化浏览器
  321. browser_manager = BrowserManager()
  322. browser = browser_manager.init_browser()
  323. # 初始化邮箱验证处理器
  324. email_handler = EmailVerificationHandler(browser)
  325. # 固定的 URL 配置
  326. login_url = "https://authenticator.cursor.sh"
  327. sign_up_url = "https://authenticator.cursor.sh/sign-up"
  328. settings_url = "https://www.cursor.com/settings"
  329. mail_url = "https://tempmail.plus"
  330. # 生成随机邮箱
  331. email_generator = EmailGenerator()
  332. account = email_generator.generate_email()
  333. password = email_generator.default_password
  334. first_name = email_generator.default_first_name
  335. last_name = email_generator.default_last_name
  336. auto_update_cursor_auth = True
  337. tab = browser.latest_tab
  338. tab.run_js("try { turnstile.reset() } catch(e) { }")
  339. tab.get(login_url)
  340. if sign_up_account(browser, tab):
  341. token = get_cursor_session_token(tab)
  342. if token:
  343. update_cursor_auth(
  344. email=account, access_token=token, refresh_token=token
  345. )
  346. else:
  347. print("账户注册失败")
  348. print("脚本执行完毕")
  349. except Exception as e:
  350. logging.error(f"程序执行出错: {str(e)}")
  351. import traceback
  352. logging.error(traceback.format_exc())
  353. finally:
  354. if browser_manager:
  355. browser_manager.quit()
  356. input("\n按回车键退出...")