cursor_pro_keep_alive.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import os
  2. os.environ["PYTHONVERBOSE"] = "0"
  3. os.environ["PYINSTALLER_VERBOSE"] = "0"
  4. from DrissionPage import ChromiumOptions, Chromium
  5. from DrissionPage.common import Keys
  6. import re
  7. import time
  8. import random
  9. from cursor_auth_manager import CursorAuthManager
  10. from configparser import ConfigParser
  11. import os
  12. import sys
  13. import logging
  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 load_config():
  24. """加载配置文件"""
  25. config = ConfigParser()
  26. # 获取程序运行的实际目录
  27. if getattr(sys, "frozen", False):
  28. # 打包后的情况:使用可执行文件所在目录
  29. root_dir = os.path.dirname(sys.executable)
  30. else:
  31. # 开发环境:使用当前工作目录
  32. root_dir = os.getcwd()
  33. config_path = os.path.join(root_dir, "config.ini")
  34. if os.path.exists(config_path):
  35. config.read(config_path, encoding="utf-8")
  36. print(f"已加载配置文件: {config_path}")
  37. print(config["Account"]["email"])
  38. return {
  39. "account": config["Account"]["email"],
  40. "password": config["Account"]["password"],
  41. "first_name": config["Account"]["first_name"],
  42. "last_name": config["Account"]["last_name"],
  43. }
  44. raise FileNotFoundError(f"配置文件不存在: {config_path}")
  45. def get_veri_code(tab):
  46. """获取验证码"""
  47. username = account.split("@")[0]
  48. try:
  49. while True:
  50. if tab.ele("@id=pre_button"):
  51. tab.actions.click("@id=pre_button").type(Keys.CTRL_A).key_down(
  52. Keys.BACKSPACE
  53. ).key_up(Keys.BACKSPACE).input(username).key_down(Keys.ENTER).key_up(
  54. Keys.ENTER
  55. )
  56. break
  57. time.sleep(1)
  58. while True:
  59. new_mail = tab.ele("@class=mail")
  60. if new_mail:
  61. if new_mail.text:
  62. print("最新的邮件:", new_mail.text)
  63. tab.actions.click("@class=mail")
  64. break
  65. else:
  66. print(new_mail)
  67. break
  68. time.sleep(1)
  69. if tab.ele("@class=overflow-auto mb-20"):
  70. email_content = tab.ele("@class=overflow-auto mb-20").text
  71. verification_code = re.search(
  72. r"verification code is (\d{6})", email_content
  73. )
  74. if verification_code:
  75. code = verification_code.group(1)
  76. print("验证码:", code)
  77. else:
  78. print("未找到验证码")
  79. if tab.ele("@id=delete_mail"):
  80. tab.actions.click("@id=delete_mail")
  81. time.sleep(1)
  82. if tab.ele("@id=confirm_mail"):
  83. tab.actions.click("@id=confirm_mail")
  84. print("删除邮件")
  85. tab.close()
  86. except Exception as e:
  87. print(e)
  88. return code
  89. def handle_turnstile(tab):
  90. """处理 Turnstile 验证"""
  91. print("准备处理验证")
  92. try:
  93. while True:
  94. try:
  95. challengeCheck = (
  96. tab.ele("@id=cf-turnstile", timeout=2)
  97. .child()
  98. .shadow_root.ele("tag:iframe")
  99. .ele("tag:body")
  100. .sr("tag:input")
  101. )
  102. if challengeCheck:
  103. print("验证框加载完成")
  104. time.sleep(random.uniform(1, 3))
  105. challengeCheck.click()
  106. print("验证按钮已点击,等待验证完成...")
  107. time.sleep(2)
  108. return True
  109. except:
  110. pass
  111. if tab.ele("@name=password"):
  112. print("无需验证")
  113. break
  114. if tab.ele("@data-index=0"):
  115. print("无需验证")
  116. break
  117. if tab.ele("Account Settings"):
  118. print("无需验证")
  119. break
  120. time.sleep(random.uniform(1, 2))
  121. except Exception as e:
  122. print(e)
  123. print("跳过验证")
  124. return False
  125. def delete_account(browser, tab):
  126. """删除账户流程"""
  127. print("\n开始删除账户...")
  128. try:
  129. if tab.ele("@name=email"):
  130. tab.ele("@name=email").input(account)
  131. print("输入账号")
  132. time.sleep(random.uniform(1, 3))
  133. except Exception as e:
  134. print(f"输入账号失败: {str(e)}")
  135. try:
  136. if tab.ele("Continue"):
  137. tab.ele("Continue").click()
  138. print("点击Continue")
  139. except Exception as e:
  140. print(f"点击Continue失败: {str(e)}")
  141. handle_turnstile(tab)
  142. time.sleep(5)
  143. try:
  144. if tab.ele("@name=password"):
  145. tab.ele("@name=password").input(password)
  146. print("输入密码")
  147. time.sleep(random.uniform(1, 3))
  148. except Exception as e:
  149. print("输入密码失败")
  150. sign_in_button = tab.ele(
  151. "xpath:/html/body/div[1]/div/div/div[2]/div/form/div/button"
  152. )
  153. try:
  154. if sign_in_button:
  155. sign_in_button.click(by_js=True)
  156. print("点击Sign in")
  157. except Exception as e:
  158. print(f"点击Sign in失败: {str(e)}")
  159. handle_turnstile(tab)
  160. # 处理验证码
  161. while True:
  162. try:
  163. if tab.ele("Account Settings"):
  164. break
  165. if tab.ele("@data-index=0"):
  166. tab_mail = browser.new_tab(mail_url)
  167. browser.activate_tab(tab_mail)
  168. print("打开邮箱页面")
  169. code = get_veri_code(tab_mail)
  170. if code:
  171. print("获取验证码成功:", code)
  172. browser.activate_tab(tab)
  173. else:
  174. print("获取验证码失败,程序退出")
  175. return False
  176. i = 0
  177. for digit in code:
  178. tab.ele(f"@data-index={i}").input(digit)
  179. time.sleep(random.uniform(0.1, 0.3))
  180. i += 1
  181. break
  182. except Exception as e:
  183. print(e)
  184. handle_turnstile(tab)
  185. time.sleep(random.uniform(1, 3))
  186. # tab.get_screenshot('sign-in_success.png')
  187. # print("登录账户截图")
  188. tab.get(settings_url)
  189. print("进入设置页面")
  190. try:
  191. if tab.ele("@class=mt-1"):
  192. tab.ele("@class=mt-1").click()
  193. print("点击Adavance")
  194. time.sleep(random.uniform(1, 2))
  195. except Exception as e:
  196. print(f"点击Adavance失败: {str(e)}")
  197. try:
  198. if tab.ele("Delete Account"):
  199. tab.ele("Delete Account").click()
  200. print("点击Delete Account")
  201. time.sleep(random.uniform(1, 2))
  202. except Exception as e:
  203. print(f"点击Delete Account失败: {str(e)}")
  204. try:
  205. if tab.ele("tag:input"):
  206. tab.actions.click("tag:input").type("delete")
  207. print("输入delete")
  208. time.sleep(random.uniform(1, 2))
  209. except Exception as e:
  210. print(f"输入delete失败: {str(e)}")
  211. delete_button = tab.ele(
  212. "xpath:/html/body/main/div/div/div/div/div/div[1]/div[2]/div[3]/div[2]/div/div/div[2]/button[2]"
  213. )
  214. try:
  215. if delete_button:
  216. print("点击Delete")
  217. delete_button.click()
  218. time.sleep(5)
  219. # tab.get_screenshot('delete_account.png')
  220. # print("删除账户截图")
  221. return True
  222. except Exception as e:
  223. print(f"点击Delete失败: {str(e)}")
  224. return False
  225. def get_cursor_session_token(tab):
  226. """获取cursor session token"""
  227. cookies = tab.cookies()
  228. cursor_session_token = None
  229. for cookie in cookies:
  230. if cookie["name"] == "WorkosCursorSessionToken":
  231. cursor_session_token = cookie["value"].split("%3A%3A")[1]
  232. break
  233. return cursor_session_token
  234. def update_cursor_auth(email=None, access_token=None, refresh_token=None):
  235. """
  236. 更新Cursor的认证信息的便捷函数
  237. """
  238. auth_manager = CursorAuthManager()
  239. return auth_manager.update_auth(email, access_token, refresh_token)
  240. def sign_up_account(browser, tab):
  241. """注册账户流程"""
  242. print("\n开始注册新账户...")
  243. tab.get(sign_up_url)
  244. try:
  245. if tab.ele("@name=first_name"):
  246. print("已打开注册页面")
  247. tab.actions.click("@name=first_name").input(first_name)
  248. time.sleep(random.uniform(1, 3))
  249. tab.actions.click("@name=last_name").input(last_name)
  250. time.sleep(random.uniform(1, 3))
  251. tab.actions.click("@name=email").input(account)
  252. print("输入邮箱")
  253. time.sleep(random.uniform(1, 3))
  254. tab.actions.click("@type=submit")
  255. print("点击注册按钮")
  256. except Exception as e:
  257. print("打开注册页面失败")
  258. return False
  259. handle_turnstile(tab)
  260. try:
  261. if tab.ele("@name=password"):
  262. tab.ele("@name=password").input(password)
  263. print("输入密码")
  264. time.sleep(random.uniform(1, 3))
  265. tab.ele("@type=submit").click()
  266. print("点击Continue按钮")
  267. except Exception as e:
  268. print("输入密码失败")
  269. return False
  270. time.sleep(random.uniform(1, 3))
  271. if tab.ele("This email is not available."):
  272. print("This email is not available.")
  273. return False
  274. handle_turnstile(tab)
  275. while True:
  276. try:
  277. if tab.ele("Account Settings"):
  278. break
  279. if tab.ele("@data-index=0"):
  280. tab_mail = browser.new_tab(mail_url)
  281. browser.activate_tab(tab_mail)
  282. print("打开邮箱页面")
  283. code = get_veri_code(tab_mail)
  284. if code:
  285. print("获取验证码成功:", code)
  286. browser.activate_tab(tab)
  287. else:
  288. print("获取验证码失败,程序退出")
  289. return False
  290. i = 0
  291. for digit in code:
  292. tab.ele(f"@data-index={i}").input(digit)
  293. time.sleep(random.uniform(0.1, 0.3))
  294. i += 1
  295. break
  296. except Exception as e:
  297. print(e)
  298. handle_turnstile(tab)
  299. time.sleep(random.uniform(1, 3))
  300. print("进入设置页面")
  301. tab.get(settings_url)
  302. try:
  303. usage_ele = tab.ele(
  304. "xpath:/html/body/main/div/div/div/div/div/div[2]/div/div/div/div[1]/div[1]/span[2]"
  305. )
  306. if usage_ele:
  307. usage_info = usage_ele.text
  308. total_usage = usage_info.split("/")[-1].strip()
  309. print("可用上限: " + total_usage)
  310. except Exception as e:
  311. print("获取可用上限失败")
  312. # tab.get_screenshot("sign_up_success.png")
  313. # print("注册账户截图")
  314. print("注册完成")
  315. print("Cursor 账号: " + account)
  316. print(" 密码: " + password)
  317. return True
  318. def get_extension_path():
  319. """获取插件路径"""
  320. root_dir = os.getcwd()
  321. extension_path = os.path.join(root_dir, "turnstilePatch")
  322. if hasattr(sys, "_MEIPASS"):
  323. print("运行在打包环境中")
  324. extension_path = os.path.join(sys._MEIPASS, "turnstilePatch")
  325. print(f"尝试加载插件路径: {extension_path}")
  326. if not os.path.exists(extension_path):
  327. raise FileNotFoundError(
  328. f"插件不存在: {extension_path}\n请确保 turnstilePatch 文件夹在正确位置"
  329. )
  330. return extension_path
  331. def get_browser_options():
  332. co = ChromiumOptions()
  333. try:
  334. extension_path = get_extension_path()
  335. co.add_extension(extension_path)
  336. except FileNotFoundError as e:
  337. print(f"警告: {e}")
  338. co.headless()
  339. co.set_user_agent(
  340. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.6723.92 Safari/537.36"
  341. )
  342. co.set_pref("credentials_enable_service", False)
  343. co.set_argument("--hide-crash-restore-bubble")
  344. co.auto_port()
  345. # Mac 系统特殊处理
  346. if sys.platform == "darwin":
  347. co.set_argument("--no-sandbox")
  348. co.set_argument("--disable-gpu")
  349. return co
  350. def cleanup_temp_files():
  351. """清理临时文件和缓存"""
  352. try:
  353. temp_dirs = [
  354. os.path.join(os.getcwd(), "__pycache__"),
  355. os.path.join(os.getcwd(), "build"),
  356. ]
  357. for dir_path in temp_dirs:
  358. if os.path.exists(dir_path):
  359. import shutil
  360. shutil.rmtree(dir_path)
  361. except Exception as e:
  362. logging.warning(f"清理临时文件失败: {str(e)}")
  363. if __name__ == "__main__":
  364. browser = None
  365. try:
  366. # 加载配置
  367. config = load_config()
  368. # 固定的 URL 配置
  369. login_url = "https://authenticator.cursor.sh"
  370. sign_up_url = "https://authenticator.cursor.sh/sign-up"
  371. settings_url = "https://www.cursor.com/settings"
  372. mail_url = "https://tempmail.plus"
  373. # 账号信息
  374. account = config["account"]
  375. password = config["password"]
  376. first_name = config["first_name"]
  377. last_name = config["last_name"]
  378. auto_update_cursor_auth = True
  379. # 浏览器配置
  380. co = get_browser_options()
  381. browser = Chromium(co)
  382. tab = browser.latest_tab
  383. tab.run_js("try { turnstile.reset() } catch(e) { }")
  384. print("开始执行删除和注册流程")
  385. print("***请确认已经用https://tempmail.plus/zh邮箱成功申请过cursor账号!***")
  386. tab.get(login_url)
  387. # 执行删除和注册流程
  388. if delete_account(browser, tab):
  389. print("账户删除成功")
  390. time.sleep(3)
  391. if sign_up_account(browser, tab):
  392. token = get_cursor_session_token(tab)
  393. print(f"CursorSessionToken: {token}")
  394. print("账户注册成功")
  395. if auto_update_cursor_auth:
  396. update_cursor_auth(
  397. email=account, access_token=token, refresh_token=token
  398. )
  399. else:
  400. print("账户注册失败")
  401. else:
  402. print("账户删除失败")
  403. print("脚本执行完毕")
  404. except Exception as e:
  405. print(f"程序执行出错: {str(e)}")
  406. import traceback
  407. print(traceback.format_exc())
  408. finally:
  409. # 确保浏览器实例被正确关闭
  410. if browser:
  411. try:
  412. browser.quit()
  413. except:
  414. pass
  415. input("\n按回车键退出...")