autoreg-kit: api-route + tokvi autoreg, health, new-api inject and gates
This commit is contained in:
+112
@@ -0,0 +1,112 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ar_auto.py — сторож api-route: проба почтового канала -> волна рег -> health -> инжект в iishko.
|
||||
Запуск по крону (раз в 30 мин). Молчит, если канал закрыт.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import os as _os
|
||||
PROD_HOST = _os.environ.get("PROD_HOST", "root@127.0.0.1")
|
||||
FARM_HOST = _os.environ.get("FARM_HOST", "root@127.0.0.1")
|
||||
PX_USER = _os.environ.get("PX_USER", "")
|
||||
PX_PASS = _os.environ.get("PX_PASS", "")
|
||||
PX_HOST1 = _os.environ.get("PX_HOST1", "127.0.0.1")
|
||||
PX_HOST2 = _os.environ.get("PX_HOST2", "127.0.0.1")
|
||||
PX_HOST3 = _os.environ.get("PX_HOST3", "127.0.0.1")
|
||||
PX_HOST4 = _os.environ.get("PX_HOST4", "127.0.0.1")
|
||||
MAIL_LOCAL = _os.environ.get("MAIL_LOCAL", "user")
|
||||
PROBE_EMAIL = _os.environ.get("PROBE_EMAIL", "probe@example.com")
|
||||
PROBE_EMAIL2 = _os.environ.get("PROBE_EMAIL2", "probe2@example.com")
|
||||
PROBE_EMAIL3 = _os.environ.get("PROBE_EMAIL3", "probe3@example.com")
|
||||
|
||||
|
||||
TMP = r"C:\Users\User\tmp"
|
||||
PY = r"C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe"
|
||||
LOG = os.path.join(TMP, "ar_auto.log")
|
||||
STATE = os.path.join(TMP, "ar_auto_state.json")
|
||||
PROBE = PROBE_EMAIL3
|
||||
LANES = ("8891", "8892", "8893", "8894")
|
||||
|
||||
|
||||
def log(msg):
|
||||
line = "%s %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg)
|
||||
print(line, flush=True)
|
||||
with open(LOG, "a", encoding="utf-8") as f:
|
||||
f.write(line + "\n")
|
||||
|
||||
|
||||
def state():
|
||||
try:
|
||||
return json.load(open(STATE, encoding="utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def probe():
|
||||
"""True только если API реально принял адрес к отправке."""
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
body = json.dumps({"email": PROBE}).encode()
|
||||
req = urllib.request.Request(
|
||||
"https://www.api-route.com/api/dist/user/email-verification", data=body,
|
||||
headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
r = urllib.request.urlopen(req, timeout=30)
|
||||
j = json.loads(r.read().decode("utf-8", "replace"))
|
||||
return bool(j.get("success")) is True, str(j.get("message") or "")[:60]
|
||||
except Exception as e:
|
||||
return False, "%s %s" % (type(e).__name__, str(e)[:50])
|
||||
|
||||
|
||||
def browsers_running():
|
||||
import psutil
|
||||
n = 0
|
||||
for p in psutil.process_iter(["cmdline"]):
|
||||
cl = p.info.get("cmdline") or []
|
||||
if cl and "browser_reg_ar2.py" in " ".join(cl):
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def run(cmd, timeout=None):
|
||||
p = subprocess.run(cmd, shell=True, capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace", timeout=timeout)
|
||||
return p.returncode, ((p.stdout or "") + (p.stderr or "")).strip()
|
||||
|
||||
|
||||
def main():
|
||||
ok, msg = probe()
|
||||
st = state()
|
||||
st["last_probe"] = time.strftime("%F %T")
|
||||
st["probe_ok"] = ok
|
||||
json.dump(st, open(STATE, "w"))
|
||||
log("probe: %s | %s" % (ok, msg))
|
||||
if not ok:
|
||||
return
|
||||
before = sum(1 for _ in open(os.path.join(TMP, "panel_bank.jsonl"), encoding="utf-8", errors="replace"))
|
||||
log("channel open, bank lines=%d -> wave" % before)
|
||||
env = dict(os.environ)
|
||||
env.pop("PYTHONPATH", None)
|
||||
env["USERPROFILE"] = r"C:\Users\User"
|
||||
subprocess.run([PY, os.path.join(TMP, "spawn_ar.py"), "10"], cwd=TMP, env=env,
|
||||
capture_output=True, text=True, timeout=180)
|
||||
t_end = time.time() + 2700
|
||||
while time.time() < t_end and browsers_running() > 0:
|
||||
time.sleep(60)
|
||||
after = sum(1 for _ in open(os.path.join(TMP, "panel_bank.jsonl"), encoding="utf-8", errors="replace"))
|
||||
log("wave done, bank lines=%d (+%d)" % (after, after - before))
|
||||
for script, args in (("ar_health.py", " --apply"),):
|
||||
rc, out = run('scp -o StrictHostKeyChecking=no %s " + PROD_HOST + ":/root/%s'
|
||||
% (os.path.join(TMP, script), script), timeout=180)
|
||||
rc, out = run('ssh -o StrictHostKeyChecking=no " + PROD_HOST + " "cd /root && python3 %s%s"'
|
||||
% (script, args), timeout=900)
|
||||
log("health rc=%s %s" % (rc, out.replace("\n", " ")[-220:]))
|
||||
rc, out = run('cd %s && %s ar_sync.py' % (TMP, PY), timeout=1200)
|
||||
log("sync rc=%s %s" % (rc, out.replace("\n", " ")[-260:]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+99
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ar_heal.py — поднять каналы ar-* (api-route) в iishko: status, abilities, model_limits, квоты юзеров.
|
||||
usage: python3 ar_heal.py [--apply]
|
||||
"""
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
|
||||
DB = "/opt/grok-gateway/new-api/one-api.db"
|
||||
POOL = "/root/ar_keys.jsonl"
|
||||
BASE = "https://www.api-route.com"
|
||||
MODELS = ["gpt-6.1-sol", "gpt-6-sol", "gpt-5.6-sol", "gpt-6-astra"]
|
||||
GROUPS = ["default", "premium", "t1", "t2", "t3", "t4"]
|
||||
TAG = "ar"
|
||||
PRIO = 660
|
||||
MAP = '{"401":429,"402":429,"403":429}'
|
||||
APPLY = "--apply" in sys.argv
|
||||
|
||||
keys, seen = [], set()
|
||||
for l in open(POOL, encoding="utf-8"):
|
||||
l = l.strip()
|
||||
if not l:
|
||||
continue
|
||||
try:
|
||||
k = json.loads(l).get("key")
|
||||
except Exception:
|
||||
continue
|
||||
if k and k not in seen:
|
||||
seen.add(k)
|
||||
keys.append(k)
|
||||
|
||||
con = sqlite3.connect(DB, timeout=300)
|
||||
con.execute("pragma busy_timeout=300000")
|
||||
cur = con.cursor()
|
||||
now = int(time.time())
|
||||
|
||||
cids = []
|
||||
for k in keys:
|
||||
name = "ar-" + k[-6:]
|
||||
row = cur.execute("select id from channels where name=?", (name,)).fetchone()
|
||||
if row:
|
||||
cid = row[0]
|
||||
if APPLY:
|
||||
cur.execute(
|
||||
"""update channels set status=1, auto_ban=0, priority=?, models=?, base_url=?,
|
||||
"group"=?, key=?, status_code_mapping=?, tag=? where id=?""",
|
||||
(PRIO, ",".join(MODELS), BASE, ",".join(GROUPS), k, MAP, TAG, cid),
|
||||
)
|
||||
elif APPLY:
|
||||
cur.execute(
|
||||
"""insert into channels (type,key,status,name,weight,created_time,test_time,base_url,other,
|
||||
balance,balance_updated_time,models,"group",used_quota,priority,auto_ban,tag,channel_info,
|
||||
status_code_mapping)
|
||||
values (1,?,1,?,1,?,?,?,'',0,?,?,?,0,?,0,?,'{}',?)""",
|
||||
(k, name, now, now, BASE, now, ",".join(MODELS), ",".join(GROUPS), PRIO, TAG, MAP),
|
||||
)
|
||||
cid = cur.lastrowid
|
||||
else:
|
||||
cid = row[0]
|
||||
cids.append(cid)
|
||||
|
||||
if APPLY:
|
||||
for cid in cids:
|
||||
for m in MODELS:
|
||||
for g in GROUPS:
|
||||
cur.execute(
|
||||
"""insert into abilities ("group",model,channel_id,enabled,priority,weight,tag)
|
||||
values (?,?,?,1,?,1,?)
|
||||
on conflict("group",model,channel_id) do update set enabled=1,priority=?,weight=1""",
|
||||
(g, m, cid, PRIO, TAG, PRIO),
|
||||
)
|
||||
# квоты юзеров: quota считается как quota - used_quota
|
||||
u = cur.execute("select count(*) from users where quota - used_quota < 2000000000").fetchone()[0]
|
||||
cur.execute("update users set quota = used_quota + 20000000000 where quota - used_quota < 2000000000")
|
||||
# model_limits: дописать модели всем живым токенам
|
||||
patched = 0
|
||||
for tid, ml in cur.execute("select id, coalesce(model_limits,'') from tokens where status=1").fetchall():
|
||||
have = [x for x in ml.split(",") if x]
|
||||
need = [m for m in MODELS if m not in have]
|
||||
if need:
|
||||
cur.execute("update tokens set model_limits=? where id=?", (",".join(have + need), tid))
|
||||
patched += 1
|
||||
con.commit()
|
||||
print("users_quota_fixed:", u, "| tokens_patched:", patched)
|
||||
|
||||
alive = cur.execute(
|
||||
"""select count(distinct c.id) from channels c join abilities a on a.channel_id=c.id
|
||||
where c.tag='ar' and a.model='gpt-6.1-sol' and a.enabled=1 and c.status=1"""
|
||||
).fetchone()[0]
|
||||
statuses = cur.execute("select status, count(*) from channels where name like 'ar-%' group by 1").fetchall()
|
||||
abil = cur.execute(
|
||||
"""select a.model, a.enabled, count(*) from abilities a
|
||||
join channels c on c.id=a.channel_id where c.tag='ar' group by 1,2"""
|
||||
).fetchall()
|
||||
con.close()
|
||||
print("keys:", len(keys), "| channels alive:", alive, "| statuses:", statuses)
|
||||
print("abilities:", abil)
|
||||
Executable
+82
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ar_health.py — проба ключей api-route (обычный chat sol) и парковка мёртвых каналов.
|
||||
usage: python3 ar_health.py [--apply]
|
||||
"""
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import urllib3
|
||||
import requests
|
||||
|
||||
urllib3.disable_warnings()
|
||||
DB = "/opt/grok-gateway/new-api/one-api.db"
|
||||
POOL = "/root/ar_keys.jsonl"
|
||||
BASE = "https://www.api-route.com"
|
||||
MODEL = "gpt-6.1-sol"
|
||||
APPLY = "--apply" in sys.argv
|
||||
|
||||
keys, seen = [], set()
|
||||
for l in open(POOL, encoding="utf-8"):
|
||||
l = l.strip()
|
||||
if not l:
|
||||
continue
|
||||
try:
|
||||
k = json.loads(l).get("key")
|
||||
except Exception:
|
||||
continue
|
||||
if k and k not in seen:
|
||||
seen.add(k)
|
||||
keys.append(k)
|
||||
|
||||
|
||||
def probe(k):
|
||||
try:
|
||||
r = requests.post(
|
||||
BASE + "/v1/chat/completions",
|
||||
timeout=60,
|
||||
verify=False,
|
||||
headers={"Authorization": "Bearer " + k, "Content-Type": "application/json"},
|
||||
json={"model": MODEL, "messages": [{"role": "user", "content": "ok"}], "max_tokens": 4},
|
||||
)
|
||||
return k, r.status_code, r.text[:120]
|
||||
except Exception as e:
|
||||
return k, -1, type(e).__name__
|
||||
|
||||
|
||||
alive, dead = [], []
|
||||
t0 = time.time()
|
||||
with ThreadPoolExecutor(max_workers=10) as ex:
|
||||
for k, code, txt in ex.map(probe, keys):
|
||||
if code == 200 and "choices" in txt:
|
||||
alive.append(k)
|
||||
else:
|
||||
dead.append((k, code, txt.replace("\n", " ")[:90]))
|
||||
print("probe: alive=%d dead=%d in %.0fs" % (len(alive), len(dead), time.time() - t0))
|
||||
for d in dead[:8]:
|
||||
print(" dead", d[1], d[2][:80])
|
||||
|
||||
if APPLY:
|
||||
con = sqlite3.connect(DB, timeout=300)
|
||||
con.execute("pragma busy_timeout=300000")
|
||||
cur = con.cursor()
|
||||
on = off = 0
|
||||
for k in keys:
|
||||
name = "ar-" + k[-6:]
|
||||
want = 1 if k in alive else 2
|
||||
cur.execute("update channels set status=? where name=?", (want, name))
|
||||
cur.execute(
|
||||
"""update abilities set enabled=? where channel_id=(select id from channels where name=?)""",
|
||||
(1 if want == 1 else 0, name),
|
||||
)
|
||||
if want == 1:
|
||||
on += 1
|
||||
else:
|
||||
off += 1
|
||||
con.commit()
|
||||
n = cur.execute("select count(*) from channels where tag='ar' and status=1").fetchone()[0]
|
||||
con.close()
|
||||
print("channels on=%d off=%d | ar active=%d" % (on, off, n))
|
||||
@@ -0,0 +1,95 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ar_sync.py — синк ключей api-route (sol 6.1) с ПК на прод iishko.
|
||||
panel_bank.jsonl -> проба sol -> ar_keys.jsonl -> scp -> ar_inject.py --apply -> restart new-api.
|
||||
Молчит, если новых живых ключей нет.
|
||||
"""
|
||||
import base64, json, os, subprocess, sys
|
||||
import requests
|
||||
import urllib3
|
||||
|
||||
import os as _os
|
||||
PROD_HOST = _os.environ.get("PROD_HOST", "root@127.0.0.1")
|
||||
FARM_HOST = _os.environ.get("FARM_HOST", "root@127.0.0.1")
|
||||
PX_USER = _os.environ.get("PX_USER", "")
|
||||
PX_PASS = _os.environ.get("PX_PASS", "")
|
||||
PX_HOST1 = _os.environ.get("PX_HOST1", "127.0.0.1")
|
||||
PX_HOST2 = _os.environ.get("PX_HOST2", "127.0.0.1")
|
||||
PX_HOST3 = _os.environ.get("PX_HOST3", "127.0.0.1")
|
||||
PX_HOST4 = _os.environ.get("PX_HOST4", "127.0.0.1")
|
||||
MAIL_LOCAL = _os.environ.get("MAIL_LOCAL", "user")
|
||||
PROBE_EMAIL = _os.environ.get("PROBE_EMAIL", "probe@example.com")
|
||||
PROBE_EMAIL2 = _os.environ.get("PROBE_EMAIL2", "probe2@example.com")
|
||||
PROBE_EMAIL3 = _os.environ.get("PROBE_EMAIL3", "probe3@example.com")
|
||||
|
||||
|
||||
urllib3.disable_warnings()
|
||||
TMP = r"C:\Users\User\tmp"
|
||||
BANK = TMP + r"\panel_bank.jsonl"
|
||||
OUT = TMP + r"\ar_keys.jsonl"
|
||||
LOG = TMP + r"\ar_sync.log"
|
||||
BASE = "https://www.api-route.com"
|
||||
HOST = PROD_HOST
|
||||
DIRECT = "-o ConnectTimeout=20 -o StrictHostKeyChecking=no"
|
||||
|
||||
|
||||
def log(s):
|
||||
print(s, flush=True)
|
||||
open(LOG, "a", encoding="utf-8").write(s + "\n")
|
||||
|
||||
|
||||
def load_keys():
|
||||
if not os.path.exists(OUT):
|
||||
return set()
|
||||
out = set()
|
||||
for l in open(OUT, encoding="utf-8"):
|
||||
l = l.strip()
|
||||
if l.startswith("{"):
|
||||
try:
|
||||
out.add(json.loads(l)["key"])
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
have = load_keys()
|
||||
recs = []
|
||||
if os.path.exists(BANK):
|
||||
for l in open(BANK, encoding="utf-8", errors="replace"):
|
||||
l = l.strip()
|
||||
if l.startswith("{"):
|
||||
try:
|
||||
recs.append(json.loads(l))
|
||||
except Exception:
|
||||
pass
|
||||
cand = [r for r in recs if r.get("base") == BASE and r.get("key") and r["key"] not in have]
|
||||
new = []
|
||||
for r in cand:
|
||||
try:
|
||||
resp = requests.post(BASE + "/v1/chat/completions", timeout=45, verify=False,
|
||||
headers={"Authorization": "Bearer " + r["key"],
|
||||
"Content-Type": "application/json"},
|
||||
json={"model": "gpt-6.1-sol",
|
||||
"messages": [{"role": "user", "content": "say OK"}]})
|
||||
if resp.status_code == 200 and "choices" in resp.text:
|
||||
new.append(r["key"])
|
||||
except Exception:
|
||||
pass
|
||||
if not new:
|
||||
return
|
||||
with open(OUT, "a", encoding="utf-8") as f:
|
||||
for k in new:
|
||||
f.write(json.dumps({"key": k}) + "\n")
|
||||
p = subprocess.run('scp %s %s %s:/root/ar_keys.jsonl' % (DIRECT, OUT, HOST),
|
||||
shell=True, capture_output=True, text=True, timeout=240)
|
||||
if p.returncode != 0:
|
||||
return log("scp FAIL %s" % (p.stderr or p.stdout)[-100:])
|
||||
b = base64.b64encode(b"cd /root && python3 ar_inject_pg.py --apply && systemctl restart new-api && sleep 5 && systemctl is-active new-api").decode()
|
||||
cmd = 'ssh %s %s "echo %s | base64 -d | bash"' % (DIRECT, HOST, b)
|
||||
p2 = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=280)
|
||||
out = (p2.stdout or "") + (p2.stderr or "")
|
||||
log("sync +%d total=%d | %s" % (len(new), len(have) + len(new), out.strip().replace("\n", " ")[-200:]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,207 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""browser_reg_ar.py — браузерная рега api-route.com (invisible Turnstile проходит сам).
|
||||
usage: python browser_reg_ar.py [count]
|
||||
"""
|
||||
import json, os, random, re, string, subprocess, sys, time
|
||||
from camoufox.sync_api import Camoufox
|
||||
|
||||
import os as _os
|
||||
PROD_HOST = _os.environ.get("PROD_HOST", "root@127.0.0.1")
|
||||
FARM_HOST = _os.environ.get("FARM_HOST", "root@127.0.0.1")
|
||||
PX_USER = _os.environ.get("PX_USER", "")
|
||||
PX_PASS = _os.environ.get("PX_PASS", "")
|
||||
PX_HOST1 = _os.environ.get("PX_HOST1", "127.0.0.1")
|
||||
PX_HOST2 = _os.environ.get("PX_HOST2", "127.0.0.1")
|
||||
PX_HOST3 = _os.environ.get("PX_HOST3", "127.0.0.1")
|
||||
PX_HOST4 = _os.environ.get("PX_HOST4", "127.0.0.1")
|
||||
MAIL_LOCAL = _os.environ.get("MAIL_LOCAL", "user")
|
||||
PROBE_EMAIL = _os.environ.get("PROBE_EMAIL", "probe@example.com")
|
||||
PROBE_EMAIL2 = _os.environ.get("PROBE_EMAIL2", "probe2@example.com")
|
||||
PROBE_EMAIL3 = _os.environ.get("PROBE_EMAIL3", "probe3@example.com")
|
||||
|
||||
|
||||
BASE = "https://www.api-route.com"
|
||||
_PORT = os.environ.get("AR_PORT", "8891")
|
||||
_HOSTMAP = {"8891": PX_HOST1, "8892": PX_HOST2, "8893": PX_HOST3,
|
||||
"8894": PX_HOST4, "8895": _os.environ.get("PX_HOST5", "127.0.0.1")}
|
||||
PROXY = {"server": "http://%s:8901" % _HOSTMAP.get(_PORT, PX_HOST1),
|
||||
"username": os.environ.get("PX_USER", ""), "password": os.environ.get("PX_PASS", "")}
|
||||
TAGP = os.environ.get("AR_TAG", "br")
|
||||
LOG = r"C:\Users\User\tmp\browser_reg.log"
|
||||
BANK = r"C:\Users\User\tmp\panel_bank.jsonl"
|
||||
|
||||
|
||||
def log(*a):
|
||||
s = " ".join(str(x) for x in a)
|
||||
print(s, flush=True)
|
||||
open(LOG, "a", encoding="utf-8").write(time.strftime("%H:%M:%S ") + s + "\n")
|
||||
|
||||
|
||||
def mk(n=8):
|
||||
return "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(n))
|
||||
|
||||
|
||||
def read_code(alias, wait=150, min_ts=0):
|
||||
cmd = 'ssh -o ConnectTimeout=20 -o StrictHostKeyChecking=no " + PROD_HOST + " "python3 /root/pcode.py %s %d %d"' % (alias, wait, min_ts)
|
||||
p = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=wait + 90)
|
||||
out = (p.stdout or "") + (p.stderr or "")
|
||||
m = re.search(r"CODE\s+([0-9A-Za-z]{4,8})", out)
|
||||
return (m.group(1) if m else None), out.strip()[:100]
|
||||
|
||||
|
||||
def one(idx=1):
|
||||
user = "u" + mk(8)
|
||||
pw = "Zx" + mk(10) + "!7"
|
||||
alias = MAIL_LOCAL + "+%s%s@gmail.com" % (TAGP, mk(5))
|
||||
ts = int(time.time())
|
||||
log("=== account:", user, alias)
|
||||
with Camoufox(headless=True, geoip=False, humanize=True, os=["windows"],
|
||||
proxy=PROXY, locale="en-US") as br:
|
||||
pg = br.new_page()
|
||||
pg.set_default_timeout(45000)
|
||||
pg.goto(BASE + "/register", wait_until="domcontentloaded")
|
||||
time.sleep(3)
|
||||
pg.fill("#register-username", user)
|
||||
pg.fill("#register-email", alias)
|
||||
pg.fill("#register-password", pw)
|
||||
pg.fill("#register-password2", pw)
|
||||
time.sleep(1)
|
||||
# отправляем код (до 3 попыток, пока кнопка не станет "Resend")
|
||||
sent = False
|
||||
for attempt in range(3):
|
||||
pg.evaluate("""() => {
|
||||
const b=[...document.querySelectorAll('button')].find(x=>/send code/i.test(x.innerText||''));
|
||||
if(b){b.scrollIntoView();b.dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));b.click();}
|
||||
}""")
|
||||
for _ in range(8):
|
||||
time.sleep(1.5)
|
||||
txt = pg.evaluate("() => [...document.querySelectorAll('button')].map(b=>b.innerText.trim()).join('|')")
|
||||
if re.search(r"resend|\d+s", txt):
|
||||
sent = True
|
||||
break
|
||||
if sent:
|
||||
break
|
||||
try:
|
||||
pg.get_by_role("button", name=re.compile("send code", re.I)).first.click(timeout=5000)
|
||||
except Exception as e:
|
||||
log("click retry err", type(e).__name__)
|
||||
time.sleep(3)
|
||||
log("send-code sent:", sent)
|
||||
body = pg.evaluate("() => document.body.innerText.slice(0,300)").replace("\n", " | ")
|
||||
log("after send-code:", body[:200])
|
||||
code, info = read_code(alias, 150, ts)
|
||||
if not code:
|
||||
log("NOCODE", info)
|
||||
return {"stage": "mail"}
|
||||
log("code:", code)
|
||||
pg.fill("#register-code", code)
|
||||
time.sleep(2)
|
||||
# ждём invisible turnstile
|
||||
for i in range(12):
|
||||
tok = pg.evaluate("() => { const e=document.querySelector('input[name=cf-turnstile-response]'); return e?e.value:''; }")
|
||||
if tok and len(tok) > 30:
|
||||
log("turnstile token len:", len(tok))
|
||||
break
|
||||
time.sleep(2)
|
||||
pg.evaluate("""() => {
|
||||
const b=[...document.querySelectorAll('button')].find(x=>/create account/i.test(x.innerText||''));
|
||||
if(b){b.scrollIntoView();b.click();}
|
||||
}""")
|
||||
for i in range(20):
|
||||
time.sleep(2)
|
||||
if "/login" not in pg.url:
|
||||
break
|
||||
body = pg.evaluate("() => document.body.innerText.slice(0,400)").replace("\n", " | ")
|
||||
log("after submit url:", pg.url, "| body:", body[:220])
|
||||
if "register" in pg.url and ("error" in body.lower() or "invalid" in body.lower() or "失败" in body):
|
||||
pg.screenshot(path=r"C:\Users\User\tmp\ar_fail.png")
|
||||
return {"stage": "register", "info": body[:120]}
|
||||
# идём на страницу API-ключей и создаём ключ через UI
|
||||
pg.goto(BASE + "/api-keys", wait_until="domcontentloaded")
|
||||
time.sleep(5)
|
||||
if "/login" in pg.url:
|
||||
log("session lost -> login fallback")
|
||||
pg.fill("#login-username", alias)
|
||||
pg.fill("#login-password", pw)
|
||||
pg.evaluate("""() => {
|
||||
const b=[...document.querySelectorAll('button')].find(x=>/sign in|log in|login|登录/i.test(x.innerText||''));
|
||||
if(b){b.click();}
|
||||
}""")
|
||||
for i in range(15):
|
||||
time.sleep(2)
|
||||
if "/login" not in pg.url:
|
||||
break
|
||||
log("after login url:", pg.url)
|
||||
if "/login" in pg.url:
|
||||
return {"stage": "login", "info": pg.url}
|
||||
pg.goto(BASE + "/api-keys", wait_until="domcontentloaded")
|
||||
time.sleep(4)
|
||||
txt = pg.evaluate("() => document.body.innerText.slice(0,600)").replace("\n", " | ")
|
||||
log("api-keys page:", txt[:260])
|
||||
# шаг 1: найти кнопку создания
|
||||
created = pg.evaluate("""() => {
|
||||
const btns=[...document.querySelectorAll('button')].map(b=>(b.innerText||'').trim()).filter(Boolean);
|
||||
const b=[...document.querySelectorAll('button')].find(x=>/create|new key|add|generate|新建|创建/i.test(x.innerText||''));
|
||||
if(b){b.scrollIntoView();b.click();return btns;}
|
||||
return btns;
|
||||
}""")
|
||||
log("buttons:", json.dumps(created, ensure_ascii=True)[:200])
|
||||
time.sleep(3)
|
||||
ins = pg.evaluate("""() => [...document.querySelectorAll('input')].map(e=>({id:e.id,ph:e.placeholder||'',type:e.type}))""")
|
||||
log("inputs:", json.dumps(ins, ensure_ascii=True)[:200])
|
||||
name = "k" + mk(4)
|
||||
sel = None
|
||||
for i in ins:
|
||||
if i.get("id"):
|
||||
sel = "#" + i["id"]
|
||||
break
|
||||
if i.get("ph"):
|
||||
sel = "input[placeholder='%s']" % i["ph"]
|
||||
break
|
||||
if sel:
|
||||
try:
|
||||
pg.fill(sel, name)
|
||||
except Exception as e:
|
||||
log("fill err", type(e).__name__)
|
||||
pg.evaluate("""() => {
|
||||
const b=[...document.querySelectorAll('button')].find(x=>/confirm|create|submit|确定|保存|save/i.test(x.innerText||''));
|
||||
if(b){b.click();}
|
||||
}""")
|
||||
time.sleep(5)
|
||||
body = pg.evaluate("() => document.body.innerText")
|
||||
key = None
|
||||
m = re.search(r"(sk-[A-Za-z0-9_\-]{20,})", body)
|
||||
if m:
|
||||
key = m.group(1)
|
||||
if not key:
|
||||
r2 = pg.evaluate("""async () => {
|
||||
const out={};
|
||||
for (const u of ['/api/user/token','/api/token/?p=1&size=10','/api/dist/token/list']) {
|
||||
try { const r=await fetch(u); out[u]=[r.status,(await r.text()).slice(0,400)]; } catch(e){ out[u]=['err'] }
|
||||
}
|
||||
return out;
|
||||
}""")
|
||||
log("probe:", json.dumps(r2, ensure_ascii=True)[:420])
|
||||
mm = re.search(r'"key"\s*:\s*"([A-Za-z0-9_\-]{20,})"', json.dumps(r2, ensure_ascii=True))
|
||||
if mm:
|
||||
key = mm.group(1)
|
||||
log("key found:", bool(key), "| page:", pg.url)
|
||||
if not key:
|
||||
pg.screenshot(path=r"C:\Users\User\tmp\ar_nokey.png")
|
||||
open(r"C:\Users\User\tmp\ar_tokenpage.txt", "w", encoding="utf-8").write(
|
||||
json.dumps({"username": user, "password": pw, "email": alias}, ensure_ascii=True) + "\n---\n" + body[:2000])
|
||||
rec = {"base": BASE, "username": user, "password": pw, "email": alias, "key": key,
|
||||
"models": [], "ts": int(time.time())}
|
||||
with open(BANK, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
return {"stage": "ok" if key else "nokey", "key": bool(key)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
|
||||
for i in range(n):
|
||||
try:
|
||||
log("RESULT", json.dumps(one(i + 1), ensure_ascii=True))
|
||||
except Exception as e:
|
||||
log("EXC", type(e).__name__, str(e)[:120])
|
||||
time.sleep(3)
|
||||
@@ -0,0 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""spawn_ar.py — параллельные браузерные реги api-route по прокси-лейнам."""
|
||||
import os, subprocess, sys, time
|
||||
PY = r"C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe"
|
||||
TMP = r"C:\Users\User\tmp"
|
||||
PER = int(sys.argv[1]) if len(sys.argv) > 1 else 2
|
||||
PORTS = [("8891","p1"),("8892","p2"),("8893","p3"),("8894","p4")]
|
||||
DETACH = 0x00000008 | 0x00000200
|
||||
for port, tag in PORTS:
|
||||
env = dict(os.environ); env.pop("PYTHONPATH", None)
|
||||
env.update({"AR_PORT": port, "AR_TAG": tag, "USERPROFILE": r"C:\Users\User", "HOMEDRIVE": "C:", "HOMEPATH": r"\Users\User"})
|
||||
log = os.path.join(TMP, "ar_wave_%s.log" % port)
|
||||
out = open(log, "a", encoding="utf-8", errors="replace")
|
||||
p = subprocess.Popen([PY, os.path.join(TMP, "browser_reg_ar2.py"), str(PER)],
|
||||
cwd=TMP, stdout=out, stderr=subprocess.STDOUT, creationflags=DETACH, env=env)
|
||||
print("started", port, tag, p.pid, flush=True)
|
||||
time.sleep(3)
|
||||
Reference in New Issue
Block a user