cursor_pro_keep_alive.py 12 KB

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