#!/usr/bin/env python3 """ keygens/ita_keygen.py 意大利 Prenot@Mi (https://prenotami.esteri.it/) 自动注册机器人。 功能: 1. 自动生成爱尔兰都柏林本地化人设与 @text.skin 邮箱凭据; 2. 驱动 Chromium 浏览器打开 https://prenotami.esteri.it/Account/Register; 3. 自动关闭引导弹窗,填入 14 项完整表单字段,包括密码前端加密与下拉映射; 4. 自动等待并穿透 Cloudflare Turnstile 人机验证盾; 5. 提交表单并等待跳转至 /Account/SentEmail; 6. 调用云端邮件接口轮询激活邮件,提取 ConfirmEmail 链接并在浏览器中打开完成激活; 7. 激活成功后自动上报账号到云端账号池(默认 ie.it.sentinel)。 使用方法: .venv/bin/python keygens/ita_keygen.py --dry-run # 仅填表与盾测试,不最终提交 .venv/bin/python keygens/ita_keygen.py --target 1 # 真实注册 1 个账号并入库 .venv/bin/python keygens/ita_keygen.py --target 5 # 批量注册 5 个账号 """ import os import sys import re import json import time import random import string import logging import argparse import requests import uuid import shutil from datetime import datetime, timezone, timedelta # 切换项目根路径 PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if PROJECT_ROOT not in sys.path: sys.path.insert(0, PROJECT_ROOT) from DrissionPage import ChromiumPage from DrissionPage.errors import PageDisconnectedError, AlertExistsError from utils.plugin_utils import init_chromium_options, get_free_port from utils.cloudflare_bypass_for_scraping import CloudflareBypasser from utils.mouse import HumanMouse from utils.keyboard import HumanKeyboard from core_types import Proxy logging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%H:%M:%S' ) logger = logging.getLogger("ItaRegistrar") # 常量配置 HOME_URL = "https://prenotami.esteri.it/" REGISTER_URL = "https://prenotami.esteri.it/Account/Register" DEFAULT_POOL_NAME = "ie.it.sentinel" DEFAULT_MASTER_EMAIL = "hujiarui8@gmail.com" DEFAULT_UPLOAD_URL = "https://api.text.skin/api/account/add" DEFAULT_UPLOAD_TOKEN = "tok_e946329a60ff45ba807f3f41b0e8b7fc" DEFAULT_EMAIL_FETCH_URL = "https://api.text.skin/api/email-authorizations/fetch" DEFAULT_ADDRESS_FILE = os.path.join(PROJECT_ROOT, "data", "random-ireland-address-2026-09-22.json") EMAIL_SENDER = "noreply-prenotami at esteri.it" # 爱尔兰本土常见名库(男女合集) IRISH_FIRST_NAMES = [ "Cillian", "Aoife", "Conor", "Saoirse", "Liam", "Niamh", "Fionn", "Ciara", "Sean", "Roisin", "Eoin", "Orla", "Oisin", "Maeve", "Patrick", "Darragh", "Cian", "Siobhan", "Ronan", "Aisling", "Tadhg", "Clodagh", "Cathal", "Sinead", "Cormac", "Fiona", "Niall", "Grainne", "Colm", "Deirdre", "Brian", "Emer", "Aidan", "Sorcha", "Caoimhe", "Padraig", "Daithi", "Donnacha", "Rory", "Finbar" ] # 爱尔兰本土常见姓氏库 IRISH_LAST_NAMES = [ "Murphy", "Kelly", "OBrien", "Walsh", "Smith", "ONeill", "Gallagher", "Doyle", "McCarthy", "Byrne", "Ryan", "Quinn", "Lynch", "Brennan", "Daly", "Nolan", "Connolly", "Higgins", "Flynn", "Kavanagh", "Cullen", "Connors", "Dunne", "Kennedy", "Maguire", "Maher", "Sweeney", "Farrell", "OConnor", "ODwyer", "OShea", "Keane", "Power", "Fitzgerald", "Brady" ] # 爱尔兰本土主要城镇/出生地 IRISH_BIRTH_PLACES = [ "Dublin", "Cork", "Galway", "Limerick", "Waterford", "Drogheda", "Dundalk", "Swords", "Bray", "Navan", "Kilkenny", "Ennis", "Carlow", "Tralee", "Newbridge", "Portlaoise", "Athlone", "Mullingar", "Wexford", "Sligo", "Clonmel", "Letterkenny", "Killarney", "Castlebar", "Tullamore" ] # 备用爱尔兰常用街道(当 JSON 地址耗尽或不存在时动态生成不重复地址) BACKUP_STREETS = [ "Grafton Street", "O'Connell Street", "Henry Street", "Dame Street", "Dawson Street", "Kildare Street", "Baggot Street", "Leeson Street", "Patrick Street", "Oliver Plunkett Street", "Shop Street", "Eyre Square", "O'Connell Avenue", "George's Street", "The Quay", "Main Street", "Church Street", "High Street", "Castle Street", "Market Square" ] BACKUP_CITIES_POSTCODES = [ ("Dublin", "D02"), ("Dublin", "D01"), ("Dublin", "D04"), ("Dublin", "D08"), ("Cork", "T12"), ("Galway", "H91"), ("Limerick", "V94"), ("Waterford", "X91") ] class ItaRegistrationBot: def __init__(self, args): self.args = args self.page = None self.tunnel = None self.workspace = os.path.join(PROJECT_ROOT, "data", "temp_reg_browser") # 去重追踪集合 self.used_emails = set() self.used_passwords = set() self.used_phones = set() self.used_addresses = set() # 加载外部地址池 self.address_pool = self._load_address_pool() def _log(self, msg: str): logger.info(f"[ItaBot] {msg}") def _load_address_pool(self) -> list: """加载提供的 JSON 地址文件""" addr_file = getattr(self.args, "address_file", DEFAULT_ADDRESS_FILE) pool = [] if os.path.exists(addr_file): try: with open(addr_file, "r", encoding="utf-8") as f: raw_data = json.load(f) if isinstance(raw_data, list): for item in raw_data: street = item.get("streetAddress") or item.get("address") city = item.get("city") or "Dublin" cap = item.get("postcode") or item.get("cap") or "D02 YF90" dob = item.get("dateOfBirth") if street: pool.append({ "street": street, "city": city, "cap": cap, "dob": dob }) self._log(f"Loaded {len(pool)} addresses from {os.path.basename(addr_file)}") except Exception as e: self._log(f"Failed to load address file {addr_file}: {e}") else: self._log(f"Address file {addr_file} not found, will use dynamic generator.") random.shuffle(pool) return pool def _get_unique_address(self) -> tuple: """获取一个唯一的爱尔兰地址 (street, city, cap, optional_dob)""" # 1. 优先从加载的 JSON 地址池中消耗 while self.address_pool: item = self.address_pool.pop(0) key = f"{item['street']}|{item['city']}|{item['cap']}".lower() if key not in self.used_addresses: self.used_addresses.add(key) return item['street'], item['city'], item['cap'], item.get('dob') # 2. 地址池耗尽或不存在时,生成动态且不重复的真实爱尔兰地址 for _ in range(100): num = random.randint(1, 380) street_name = random.choice(BACKUP_STREETS) street = f"{num} {street_name}" city, prefix = random.choice(BACKUP_CITIES_POSTCODES) eir_suffix = "".join(random.choices(string.ascii_uppercase + string.digits, k=4)) cap = f"{prefix} {eir_suffix}" key = f"{street}|{city}|{cap}".lower() if key not in self.used_addresses: self.used_addresses.add(key) return street, city, cap, None # 兜底保底 rand_id = "".join(random.choices(string.digits, k=4)) return f"{rand_id} Grafton Street", "Dublin", "D02 YF90", None def _generate_unique_password(self) -> str: """ 生成严格满足 Prenot@Mi 规范的高强度且不重复的密码: 8-20 位,至少包含大写、小写、数字、特殊符号 """ for _ in range(100): uppers = "".join(random.choices(string.ascii_uppercase, k=2)) lowers = "".join(random.choices(string.ascii_lowercase, k=6)) digits = "".join(random.choices(string.digits, k=3)) symbol = random.choice(["!", "@", "#", "$", "%", "*"]) chars = list(uppers + lowers + digits + symbol) random.shuffle(chars) pwd = "".join(chars) if pwd not in self.used_passwords: self.used_passwords.add(pwd) return pwd return f"ItaPass@{random.randint(1000, 9999)}!" def _generate_unique_phone(self) -> str: """随机生成合法且不重复的爱尔兰手机号(9位:83/85/86/87/89开头)""" for _ in range(100): mobile_prefix = random.choice(["83", "85", "86", "87", "89"]) suffix = "".join(random.choices(string.digits, k=7)) phone = f"{mobile_prefix}{suffix}" if phone not in self.used_phones: self.used_phones.add(phone) return phone return f"85{random.randint(1000000, 9999999)}" def _generate_birth_date(self, dob_candidate: str = None) -> str: """生成确保年龄 > 20 岁的生日(格式:dd/mm/yyyy)""" if dob_candidate: # 尝试转换 YYYY-MM-DD 为 dd/mm/yyyy try: parts = dob_candidate.strip().split("-") if len(parts) == 3: y, m, d = int(parts[0]), int(parts[1]), int(parts[2]) # 确保当前年份(2026)时年龄 > 20(出生年 <= 2005) if y <= 2005: return f"{d:02d}/{m:02d}/{y}" except Exception: pass # 随机出生年(1972 - 2004,确保当前年龄在 22 到 54 岁之间) year = random.randint(1972, 2004) month = random.randint(1, 12) day = random.randint(1, 28) return f"{day:02d}/{month:02d}/{year}" def generate_account_profile(self) -> dict: """生成全面满足本土化、年龄>20、地址不重复、密码不重复、随机手机号的账号数据""" first_name = random.choice(IRISH_FIRST_NAMES) last_name = random.choice(IRISH_LAST_NAMES) birth_place = random.choice(IRISH_BIRTH_PLACES) # 确保邮箱唯一且与姓名契合 clean_first = re.sub(r"[^a-z0-9]", "", first_name.lower()) clean_last = re.sub(r"[^a-z0-9]", "", last_name.lower()) rand_num = random.randint(1000, 9999) email = f"{clean_first}{clean_last}{rand_num}@{self.args.email_domain}" while email in self.used_emails: rand_num = random.randint(1000, 9999) email = f"{clean_first}{clean_last}{rand_num}@{self.args.email_domain}" self.used_emails.add(email) # 唯一强密码 password = self._generate_unique_password() # 唯一真实地址(优先从 json 加载) address, town, cap, dob_from_addr = self._get_unique_address() # 年龄 > 20 岁生日 (dd/mm/yyyy) birth_date = self._generate_birth_date(dob_from_addr) # 随机爱尔兰手机号 phone = self._generate_unique_phone() return { "first_name": first_name, "last_name": last_name, "birth_place": birth_place, "birth_date": birth_date, "email": email, "password": password, "address": address, "cap": cap, "town": town, "nation_value": "103", # IRLANDA "prefix": "353", "phone": phone, "consulate_value": "101", # IRLANDA DUBLINO AMBASCIATA D'ITALIA } def _init_browser(self): """初始化 ChromiumPage""" session_id = uuid.uuid4().hex[:8] self.workspace = os.path.join(PROJECT_ROOT, "data", "temp_reg_browser", f"session_{session_id}") os.makedirs(self.workspace, exist_ok=True) proxy_obj = None if self.args.proxy: proxy_clean = self.args.proxy.replace("http://", "").replace("https://", "") parts = proxy_clean.split(":") if len(parts) == 2: proxy_obj = Proxy(ip=parts[0], port=int(parts[1]), proto="http") elif len(parts) == 4: proxy_obj = Proxy(ip=parts[0], port=int(parts[1]), username=parts[2], password=parts[3], proto="http") co, self.tunnel = init_chromium_options( user_data_path=self.workspace, username_seed=f"ita_reg_{uuid.uuid4().hex[:8]}", proxy=proxy_obj, headless=self.args.headless, window_size="1440,900", logger=self._log ) self.page = ChromiumPage(co) self.page.set.timeouts(page_load=self.args.timeout, script=self.args.timeout) try: self.page.run_cdp( "Page.addScriptToEvaluateOnNewDocument", source="window.alert = function(msg){ console.log('[Alert suppressed]:', msg); };" ) except Exception as e: self._log(f"CDP alert suppression non-fatal: {e}") # 初始化高仿真拟人鼠标与键盘控制器 self.mouse = HumanMouse(self.page, debug=False) self.keyboard = HumanKeyboard(self.page) try: viewport = self.page.rect.viewport_size self.mouse.move(random.randint(50, max(60, viewport[0] - 50)), random.randint(50, max(60, viewport[1] - 50))) except Exception: pass def _close_welcome_modal(self): """关闭初始引导弹窗 #register-modal""" try: close_btn = self.page.ele('#register-modal button.close', timeout=2) if close_btn and close_btn.states.is_displayed: self._log("Closing #register-modal via close button...") close_btn.click() time.sleep(1) # 原生 DOM 彻底清理 modal 遮罩,无需强赖 jQuery self.page.run_js(''' const modal = document.getElementById("register-modal"); if (modal) { modal.style.display = "none"; modal.classList.remove("show"); } document.querySelectorAll(".modal-backdrop").forEach(b => b.remove()); document.body.classList.remove("modal-open"); if (window.$ && typeof $("#register-modal").modal === "function") { try { $("#register-modal").modal("hide"); } catch(e){} } ''') time.sleep(0.5) except Exception as e: self._log(f"Modal check non-fatal: {e}") def _fill_registration_form(self, acc: dict): """填入 14 项完整表单(深度拟人化鼠标点击 + 键盘击键)""" self._log(f"Filling personal info for {acc['first_name']} {acc['last_name']} ({acc['email']}) with human-like mouse & keyboard...") def _human_input(selector, val): el = self.page.ele(selector, timeout=5) if el: try: self.mouse.human_click_ele(el) except Exception: try: el.click() except Exception: pass time.sleep(random.uniform(0.1, 0.25)) el.clear() self.keyboard.type_text(val, humanize=True) time.sleep(random.uniform(0.15, 0.35)) else: self._log(f"Warning: selector {selector} not found") # 文本项 (姓名、出生地) _human_input('#Name', acc['first_name']) _human_input('#Surname', acc['last_name']) _human_input('#BirthPlace', acc['birth_place']) # Flatpickr 出生日期 (鼠标点击输入框 + 原生 DOM 驱动) bdate_el = self.page.ele('#BirthDate', timeout=5) if bdate_el: try: self.mouse.human_click_ele(bdate_el) except Exception: pass self.page.run_js(''' const d = arguments[0]; const el = document.getElementById("BirthDate"); if (el) { el.value = d; if (el._flatpickr) { try { el._flatpickr.setDate(d, true); } catch(e){} } el.dispatchEvent(new Event('input', {bubbles: true})); el.dispatchEvent(new Event('change', {bubbles: true})); } if (window.$) { try { $("#BirthDate").val(d).trigger("change"); } catch(e){} } ''', acc['birth_date']) time.sleep(random.uniform(0.2, 0.4)) # 账号凭据 (邮箱、密码、确认密码) _human_input('#Email', acc['email']) _human_input('#Password1', acc['password']) _human_input('#ConfirmPassword1', acc['password']) # 地址与邮编 _human_input('#HomeAddress', acc['address']) _human_input('#CAP', acc['cap']) _human_input('#Town', acc['town']) # 国家下拉框 (Nation=103 / IRLANDA) nation_el = self.page.ele('#Nation', timeout=5) if nation_el: try: self.mouse.human_click_ele(nation_el) except Exception: pass self.page.run_js(''' const nVal = arguments[0]; const sel = document.getElementById("Nation"); if (sel) { sel.value = nVal; sel.dispatchEvent(new Event('change', {bubbles: true})); } if (window.$ && typeof $("#Nation").selectpicker === "function") { try { $("#Nation").val(nVal).selectpicker("refresh").trigger("change"); } catch(e){} } ''', acc['nation_value']) time.sleep(random.uniform(0.3, 0.6)) # 手机号与区号 pref_el = self.page.ele('#prefix', timeout=5) if pref_el: try: self.mouse.human_click_ele(pref_el) except Exception: pass self.page.run_js(''' const pref = arguments[0]; const el = document.getElementById("prefix"); if (el) { el.value = pref; el.dispatchEvent(new Event('change', {bubbles: true})); el.dispatchEvent(new Event('input', {bubbles: true})); } if (window.$) { try { $("#prefix").val(pref).trigger("change"); } catch(e){} } ''', acc['prefix']) _human_input('#PhoneNumber', acc['phone']) # 使馆下拉框 (Consulate=101 / IRLANDA DUBLINO AMBASCIATA D'ITALIA) consulate_el = self.page.ele('#Consulate', timeout=5) if not consulate_el: raise ValueError("Registration consulate selector is missing") # Use the select API without leaving a native dropdown open while filling # subsequent controls; the caller also verifies the selected consulate. consulate_el.select.by_value(acc['consulate_value']) time.sleep(random.uniform(0.3, 0.6)) # 勾选隐私协议 agreement = self.page.ele('#PersonalDataAgreement', timeout=5) if agreement and not agreement.states.is_checked: try: self.mouse.human_click_ele(agreement) except Exception: agreement.click() self.page.run_js(''' const agree = document.getElementById("PersonalDataAgreement"); if (agree && !agree.checked) { agree.checked = true; agree.dispatchEvent(new Event('change', {bubbles: true})); } if (window.$) { try { $("#PersonalDataAgreement").prop("checked", true).trigger("change"); } catch(e){} } ''') time.sleep(random.uniform(0.4, 0.8)) self._log("All 14 form fields populated successfully with realistic human interactions.") def _wait_and_bypass_turnstile(self, max_wait: int = 90) -> bool: """等待或穿透 Cloudflare Turnstile 人机验证(对齐 plugins/ita_plugin.py 标准策略)""" self._log("Waiting for Cloudflare Turnstile verification...") start_t = time.time() last_logged = 0 bypasser = CloudflareBypasser(self.page, log=True, logger=self._log) click_attempted_basic = False # 平滑滚动使 Turnstile 容器处于视口中央,激活前台渲染 try: self.page.run_js(''' const cf = document.querySelector(".cf-turnstile"); if (cf) cf.scrollIntoView({behavior: "smooth", block: "center"}); ''') time.sleep(0.5) # 拟人化鼠标移至 Turnstile 区域,提供生物特征活跃度 cf_ele = self.page.ele('.cf-turnstile', timeout=1) if cf_ele and hasattr(self, 'mouse'): rect = cf_ele.rect mid_x = rect.location[0] + rect.size[0] / 2 mid_y = rect.location[1] + rect.size[1] / 2 self.mouse.move(mid_x, mid_y) except Exception as e: self._log(f"Turnstile viewport scroll non-fatal: {e}") while time.time() - start_t < max_wait: # 处理可能残留的 alert 弹窗 try: if self.page.states.has_alert: self.page.handle_alert(accept=True) except Exception: pass # 1. 检查页面中 Turnstile token 是否已就绪,以及提交按钮状态 status = self.page.run_js(''' const el = document.querySelector('input[name="cf-turnstile-response"]'); const btn = document.getElementById("btnRegister"); let resp = ""; if (el && el.value) { resp = el.value; } else if (typeof turnstile !== "undefined") { try { resp = turnstile.getResponse() || ""; } catch(e){} } return { token: resp, btn_disabled: btn ? btn.disabled : true }; ''') or {} token = status.get("token", "") btn_disabled = status.get("btn_disabled", True) # 只要拿到 token 或者按钮已经解除 disabled,都代表 Turnstile 成功 if token or not btn_disabled: token_disp = token[:20] if token else "already_unlocked" self._log(f"✅ Cloudflare Turnstile verified successfully (token: {token_disp}...).") # 确保提交按钮解除 disabled 并调用回调 self.page.run_js(''' const btn = document.getElementById("btnRegister"); if (btn) btn.disabled = false; if (typeof turnstileCallback === "function") { try { turnstileCallback(); } catch(e){} } if (window.$) { try { $("#btnRegister").prop("disabled", false); } catch(e){} } ''') return True elapsed = int(time.time() - start_t) if elapsed - last_logged >= 5: last_logged = elapsed self._log(f"Waiting for Turnstile... ({elapsed}s/{max_wait}s, URL: {self.page.url})") # 策略:严格对齐 plugins/ita_plugin.py # 1. 前 5 秒被动等待(TURNSTILE_PASSIVE_SECONDS = 5) # 2. 5 秒后尝试一次定向穿透点击(is_dfs=False,耗时 <0.2s,不进行耗时阻塞的全局 DFS) if elapsed >= 5 and not click_attempted_basic: click_attempted_basic = True self._log("Turnstile pending after 5s. Triggering CloudflareBypasser targeted click (is_dfs=False)...") try: clicked = bypasser.click_verification_button(is_dfs=False) self._log(f"CloudflareBypasser targeted click result: {clicked}") except Exception as e: self._log(f"CloudflareBypasser click error: {e}") time.sleep(1.0) self._log(f"⚠️ Turnstile not resolved within {max_wait}s.") return False def _fetch_activation_link(self, email: str, sent_at_utc: str, max_wait: int = 120) -> str: """通过云端 API 轮询激活邮件并提取 ConfirmEmail 链接""" self._log(f"Polling cloud API for activation email to {email} (since UTC {sent_at_utc})...") start_time = time.time() headers = { "Authorization": f"Bearer {self.args.upload_token}", "Accept": "application/json" } # SimpleLogin 转发会把发件人改写为包含 'at' 的格式: "Prenotami - noreply-prenotami at esteri.it" # 经实机验证,直接以 "noreply-prenotami at esteri.it" 查收件人,不加多余关键词,5秒内即可命中 sender_candidates = [ "noreply-prenotami at esteri.it", "noreply-prenotami@esteri.it" ] while time.time() - start_time < max_wait: for sdr in sender_candidates: params = { "email": self.args.master_email, "sender": sdr, "recipient": email, "sentDate": sent_at_utc, "expiry": "3600", "onlyText": False } try: resp = requests.post(self.args.email_fetch_url, headers=headers, params=params, json={}, timeout=25) if resp.status_code == 200: data = resp.json() if data.get("code") == 0: body = data.get("data", {}).get("body", "") match = re.search(r'https?://prenotami\.esteri\.it/Account/ConfirmEmail\?[^\s"\'<>]+', body) if match: link = match.group(0).replace("http://", "https://") self._log(f"✅ Found activation link: {link}") return link except requests.exceptions.Timeout: pass except Exception as e: self._log(f"Email poll exception ({sdr}): {e}") elapsed = int(time.time() - start_time) self._log(f"Waiting for activation email to arrive... ({elapsed}s/{max_wait}s)") time.sleep(3) return "" def _activate_account_in_browser(self, link: str) -> bool: """在当前浏览器会话中打开激活链接""" self._log(f"Opening activation link in browser session: {link}") try: activate_tab = self.page.new_tab(link) except Exception as e: self._log(f"Failed to open new tab, navigating in current page: {e}") self.page.get(link) activate_tab = self.page try: time.sleep(5) curr_url = "" curr_html = "" try: curr_url = activate_tab.url or "" curr_html = activate_tab.html or "" except Exception: pass if "radware" in curr_html.lower() and "captcha" in curr_html.lower(): self._log("Radware challenge encountered on activation, waiting 6s...") time.sleep(6) try: curr_url = activate_tab.url or "" except Exception: pass self._log(f"Activation tab reached URL: {curr_url}") return True finally: if activate_tab != self.page: try: activate_tab.close() except Exception: pass def upload_account_to_server(self, acc: dict) -> bool: """将激活后的账号上报至云端数据库""" self._log(f"Uploading account {acc['email']} to pool {self.args.pool_name}...") headers = { "Authorization": f"Bearer {self.args.upload_token}", "Content-Type": "application/json", "Accept": "application/json" } payload = { "pool_name": self.args.pool_name, "username": acc["email"], "password": acc["password"], "extra_data": { "full_name": f"{acc['first_name']} {acc['last_name']}", "birth_date": acc["birth_date"], "birth_place": acc["birth_place"], "address": acc["address"], "cap": acc["cap"], "town": acc["town"], "mobile": f"+{acc['prefix']}{acc['phone']}", "consulate": "IRLANDA DUBLINO AMBASCIATA D'ITALIA", "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S") }, "status": "active" } try: resp = requests.post(self.args.upload_url, json=payload, headers=headers, timeout=15) if resp.status_code == 200 and resp.json().get("code") == 0: self._log(f"✅ Successfully registered and uploaded account: {acc['email']}") return True else: self._log(f"❌ Upload failed: Status {resp.status_code}, Body: {resp.text}") return False except Exception as e: self._log(f"❌ Upload error: {e}") return False def run_single(self, account_profile=None, *, upload=True) -> bool: """注册一个账户;真实申请人由调用方提供完整资料,并单独保存凭据。""" if account_profile is not None and upload: raise ValueError("Applicant registration requires upload=False; do not add it to the sentinel pool") acc = dict(account_profile) if account_profile is not None else self.generate_account_profile() self._log("=" * 65) self._log(f"Starting Registration: {acc['first_name']} {acc['last_name']} | {acc['email']}") self._log("=" * 65) try: self._init_browser() # 1. 先访问首页建立合法会话与安全 Cookie(绕过直接冷启动注册页时的 Radware 防火墙拦截) self._log(f"Establishing session on home page {HOME_URL}...") self.page.get(HOME_URL) time.sleep(3) # 2. 跳转至注册页面 self._log(f"Navigating to registration page {REGISTER_URL}...") self.page.get(REGISTER_URL) time.sleep(3) # 3. 检查是否出现 Radware 拦截 curr_url = self.page.url or "" if "perfdrive" in curr_url or "validate" in curr_url: self._log("⚠️ Encountered Radware challenge, waiting 5s...") time.sleep(5) # 4. 关闭初始引导弹窗 self._close_welcome_modal() # 5. 确保表单核心元素已就绪 if not self.page.wait.ele_displayed('#Name', timeout=15): self._close_welcome_modal() if not self.page.wait.ele_displayed('#Name', timeout=10): self._log(f"❌ Form element #Name not displayed. Current URL: {self.page.url}") return False self._fill_registration_form(acc) # 等待 Turnstile 验证(对齐 ita_plugin 预留充裕人机挑战交互窗口) turnstile_ok = self._wait_and_bypass_turnstile(max_wait=90) if not turnstile_ok: self._log("❌ Turnstile verification failed. Aborting current attempt.") return False if self.args.dry_run: self._log("🔍 [DRY-RUN] Form filled and Turnstile verified. Skipping submit & upload.") time.sleep(5) return True # 拟人化提交点击 self._log("Preparing form submission...") sent_at_utc = (datetime.now(timezone.utc) - timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M:%S") # 确保隐藏字段 Password / ConfirmPassword / hiddenOtherMailOrPhone 深度同步 self.page.run_js(''' const pw = arguments[0]; const pEl = document.getElementById("Password"); const cpEl = document.getElementById("ConfirmPassword"); if (pEl) pEl.value = btoa(pw); if (cpEl) cpEl.value = btoa(pw); const omEl = document.getElementById("OtherMailOrPhone"); const homEl = document.getElementById("hiddenOtherMailOrPhone"); if (omEl && homEl) homEl.value = omEl.value; ''', acc['password']) btn_submit = self.page.ele('#btnRegister', timeout=10) if not btn_submit: self._log("❌ Could not find submit button #btnRegister") return False self._log("Simulating human pre-submit check (0.8 ~ 1.5s)...") time.sleep(random.uniform(0.8, 1.5)) self._log("Submitting form with HumanMouse click...") try: self.mouse.human_click_ele(btn_submit) except Exception as e: self._log(f"Human click fallback: {e}") try: btn_submit.click() except Exception: pass # 等待跳转至 SentEmail(捕获 PageDisconnectedError 并在页面导航重连后自愈) reached_sent_email = False start_submit_wait = time.time() max_submit_wait = 45 while time.time() - start_submit_wait < max_submit_wait: time.sleep(1.5) # 处理可能出现的 Alert 弹窗 try: if self.page.states.has_alert: alert_msg = self.page.states.has_alert self._log(f"Handling browser alert: {alert_msg}") self.page.handle_alert(accept=True) except Exception: pass # 安全读取当前页面 URL curr_url = "" try: curr_url = self.page.url or "" except PageDisconnectedError: self._log("Page disconnected during POST navigation, waiting 2s for tab reconnect...") time.sleep(2) try: self.page.reconnect(wait=0.5) curr_url = self.page.url or "" except Exception: pass except Exception as e: self._log(f"Waiting for URL change ({e})...") if "SentEmail" in curr_url: self._log(f"✅ Reached SentEmail confirmation page: {curr_url}") reached_sent_email = True break # 若超过 8 秒仍在 Register 页且未发生跳转,触发 JS submit 兜底 if account_profile is None and "Register" in curr_url and (time.time() - start_submit_wait > 8): self._log("Register page still active after 8s, triggering direct submit fallback...") try: self.page.run_js(''' const form = document.getElementById("register-form"); if (form) { if (window.$ && typeof $("#btnRegister").click === "function") { try { $("#btnRegister").click(); } catch(e){} } else { try { form.submit(); } catch(e){} } } ''') except Exception: pass if not reached_sent_email: curr_u = "" try: curr_u = self.page.url except Exception: pass self._log(f"⚠️ Page did not clearly show SentEmail, current url: {curr_u}") # 轮询获取激活链接 link = self._fetch_activation_link(acc['email'], sent_at_utc, max_wait=120) if not link: self._log(f"❌ Failed to receive activation email for {acc['email']}.") return False # 打开链接激活 activated = self._activate_account_in_browser(link) if not activated: self._log(f"❌ Activation tab failed for {acc['email']}.") return False # 上报入库 return self.upload_account_to_server(acc) if upload else True finally: self.cleanup() def cleanup(self): """释放浏览器与临时目录""" if self.page: try: self.page.quit() except Exception: pass self.page = None if self.tunnel: try: self.tunnel.stop() except Exception: pass self.tunnel = None if hasattr(self, 'workspace') and self.workspace and os.path.exists(self.workspace): try: shutil.rmtree(self.workspace, ignore_errors=True) except Exception: pass def parse_args(): parser = argparse.ArgumentParser(description="Prenot@Mi 意大利签证账号全自动注册机器人") parser.add_argument("--target", type=int, default=1, help="需要成功注册的账号数量") parser.add_argument("--interval", type=int, default=600, help="账号注册之间的冷却等待时间(秒,默认 600 秒即 10 分钟)") parser.add_argument("--proxy", type=str, default="http://127.0.0.1:7897", help="代理服务器地址 (如 http://127.0.0.1:7897)") parser.add_argument("--pool-name", type=str, default=DEFAULT_POOL_NAME, help="云端账号池名称") parser.add_argument("--master-email", type=str, default=DEFAULT_MASTER_EMAIL, help="接收验证邮件的主邮箱") parser.add_argument("--email-domain", type=str, default="text.skin", help="生成的邮箱域名") parser.add_argument("--address-file", type=str, default=DEFAULT_ADDRESS_FILE, help="真实爱尔兰地址 JSON 文件路径") parser.add_argument("--upload-url", type=str, default=DEFAULT_UPLOAD_URL, help="账号上报接口 URL") parser.add_argument("--upload-token", type=str, default=DEFAULT_UPLOAD_TOKEN, help="接口 Bearer Token") parser.add_argument("--email-fetch-url", type=str, default=DEFAULT_EMAIL_FETCH_URL, help="邮件读取接口 URL") parser.add_argument("--timeout", type=int, default=40, help="页面加载与交互超时时间(秒)") parser.add_argument("--headless", action="store_true", help="是否以无头模式运行") parser.add_argument("--dry-run", action="store_true", help="演练模式:填写表单与过盾,不点击最终提交与入库") return parser.parse_args() def main(): args = parse_args() bot = ItaRegistrationBot(args) target_success = args.target max_attempts = max(args.target * 2, args.target + 3) attempt = 0 success_count = 0 fail_count = 0 print("=" * 70) print("🇮🇹 [Prenot@Mi Registration Bot] 自动化注册任务启动") print(f"目标成功数量: {target_success} | 冷却间隔: {args.interval}s ({args.interval // 60}m) | 账号池: {args.pool_name}") print(f"演练模式: {args.dry_run} | 网络代理: {args.proxy} | 邮件主箱: {args.master_email}") print("=" * 70) while success_count < target_success and attempt < max_attempts: attempt += 1 logger.info(f"=== [Attempt {attempt} | Success Progress: {success_count}/{target_success}] Starting Registration ===") ok = bot.run_single() if ok: success_count += 1 logger.info(f"✅ [Account {success_count}/{target_success}] Registration Succeeded! (Total Success: {success_count}, Failed: {fail_count})") else: fail_count += 1 logger.warning(f"❌ [Attempt {attempt}] Registration Failed! (Total Success: {success_count}, Failed: {fail_count})") # 若尚未达成目标数量,进入冷却等待(默认 10 分钟) if success_count < target_success and attempt < max_attempts: wait_sec = args.interval logger.info(f"⏳ Cooldown: Waiting {wait_sec}s ({wait_sec // 60}m) before next registration attempt...") remain = wait_sec while remain > 0: sleep_chunk = min(30, remain) time.sleep(sleep_chunk) remain -= sleep_chunk if remain > 0 and remain % 60 == 0: logger.info(f"⏳ Cooldown in progress: {remain}s ({remain // 60}m) remaining before next attempt...") print("\n" + "=" * 70) print("🎯 [注册任务结束汇总]") print(f"目标数量: {target_success} | 实际尝试: {attempt} | 成功: {success_count} | 失败: {fail_count}") print("=" * 70) if __name__ == "__main__": main()