cursor_pro_keep_alive.py 12 KB

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