cursor_pro_keep_alive.py 15 KB

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