73 lines
2.4 KiB
Python
73 lines
2.4 KiB
Python
"""Chrome/egress helpers for the Netlify farm (proxy mode + ZTE rotation)."""
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
|
|
CHROME_EXE = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
|
|
ROTATOR = r'C:\Users\User\tmp\zte_rotate3.py'
|
|
ZTE_PROXY = 'http://127.0.0.1:8899'
|
|
|
|
|
|
def kill_all_chrome():
|
|
"""Kill every chrome process tree (MSYS needs MSYS_NO_PATHCONV for taskkill)."""
|
|
env = dict(os.environ, MSYS_NO_PATHCONV='1')
|
|
try:
|
|
subprocess.run('taskkill /F /IM chrome.exe /T', shell=True,
|
|
capture_output=True, timeout=60, env=env)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def cdp_alive(port: int) -> bool:
|
|
try:
|
|
with urllib.request.urlopen(f'http://127.0.0.1:{port}/json/version', timeout=3) as r:
|
|
return r.status == 200
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def ensure_chrome(port: int = 9233, profile: str = None, proxy: str = None) -> bool:
|
|
"""Start a real Chrome with CDP (optionally behind a proxy) if not already up."""
|
|
if cdp_alive(port):
|
|
return True
|
|
prof = profile or os.path.join(
|
|
os.environ.get('LOCALAPPDATA', r'C:\Windows\Temp'), 'hermes', 'cache', 'scratch',
|
|
f'nl_prof_{port}')
|
|
args = [CHROME_EXE, f'--remote-debugging-port={port}', f'--user-data-dir={prof}',
|
|
'--no-first-run', '--no-default-browser-check',
|
|
'--disable-blink-features=AutomationControlled']
|
|
if proxy:
|
|
args.append(f'--proxy-server={proxy}')
|
|
args.append('about:blank')
|
|
subprocess.Popen(args, env=dict(os.environ))
|
|
for _ in range(20):
|
|
time.sleep(1.5)
|
|
if cdp_alive(port):
|
|
return True
|
|
return False
|
|
|
|
|
|
def rotate_zte(timeout: int = 120) -> str:
|
|
"""Reconnect ZTE PPP; returns new public IP seen through the proxy, or ''."""
|
|
try:
|
|
subprocess.run([sys.executable, ROTATOR], timeout=timeout,
|
|
capture_output=True, text=True, errors='replace')
|
|
except Exception:
|
|
pass
|
|
time.sleep(6)
|
|
return egress_ip(ZTE_PROXY)
|
|
|
|
|
|
def egress_ip(proxy: str = None) -> str:
|
|
try:
|
|
if proxy:
|
|
op = urllib.request.build_opener(
|
|
urllib.request.ProxyHandler({'http': proxy, 'https': proxy}))
|
|
else:
|
|
op = urllib.request.build_opener()
|
|
with op.open('https://api.ipify.org', timeout=15) as r:
|
|
return r.read().decode().strip()
|
|
except Exception:
|
|
return '' |