"""Free proxy source backed by the iishko proxygrabb pool. The pool lives on the iishko prod box (SQLite, refreshed by the grabber). This module pulls live proxies over SSH, verifies them from the local machine, caches the result and hands out working ones round-robin. Fallbacks, in order: 1. fresh pull from iishko (if SSH reachable) 2. local cache file (proxies_cache.json) 3. built-in seed list (last known good) """ import json import os import random import subprocess import time import urllib.request from concurrent.futures import ThreadPoolExecutor HERE = os.path.dirname(os.path.abspath(__file__)) CACHE = os.path.join(HERE, 'proxies_cache.json') IISHKO_HOST = 'root@2.27.98.196' IISHKO_KEY = r'C:\Users\User\.ssh\id_ed25519' DB = '/opt/proxygrab/proxies.db' SQL = ("select proxy from pool where alive=1 and https_ok=1 " "order by (case when protocol='socks5' then 0 else 1 end), score desc limit {n};") SEED = [ 'http://185.195.254.72:5432', 'http://128.199.202.122:8080', 'socks5://69.55.49.177:38182', 'socks5://82.180.146.251:10800', 'http://161.35.70.249:80', ] def _ssh(cmd: str, timeout: int = 45) -> str: args = ['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=15', '-o', 'BatchMode=yes'] if os.path.exists(IISHKO_KEY): args += ['-i', IISHKO_KEY] args += [IISHKO_HOST, cmd] try: r = subprocess.run(args, capture_output=True, text=True, timeout=timeout, errors='replace') if r.returncode != 0: return '' return r.stdout except Exception: return '' def fetch_from_iishko(limit: int = 60): """Pull live https-capable proxies from the pool on iishko.""" out = _ssh(f'sqlite3 {DB} "{SQL.format(n=limit)}"') items = [l.strip() for l in out.splitlines() if l.strip().startswith(('http', 'socks'))] return items TARGET = 'https://app.netlify.com/signup/email' def verify(proxy: str, timeout: int = 10, target: str = TARGET) -> str: """Return the exit IP if the proxy reaches the real target over HTTPS. Uses curl so SOCKS5 works too. Plain HTTP proxies that MITM TLS fail here (they surface in Chrome as ERR_CERT_AUTHORITY_INVALID) and get dropped. """ target = target.replace('TARGET', '') # tolerate an accidental literal try: r = subprocess.run( ['curl', '-s', '-o', os.devnull, '-m', str(timeout), '-w', '%{http_code}', '-x', proxy, target], capture_output=True, text=True, timeout=timeout + 5) if r.stdout.strip() not in ('200', '301', '302'): return '' except Exception: return '' try: r2 = subprocess.run( ['curl', '-s', '-m', str(timeout), '-x', proxy, 'https://api.ipify.org'], capture_output=True, text=True, timeout=timeout + 5) ip = r2.stdout.strip() return ip if (ip.count('.') == 3 or ':' in ip) else '' except Exception: return '' def load_cache(): if os.path.exists(CACHE): try: return json.load(open(CACHE, encoding='utf-8')) except Exception: pass return {'updated': 0, 'items': []} def save_cache(items, checked): data = {'updated': time.time(), 'items': checked} try: json.dump(data, open(CACHE, 'w', encoding='utf-8'), indent=1) except Exception: pass return data class ProxyPool: """Hands out working proxies one by one, refreshing when exhausted.""" def __init__(self, limit: int = 60, check: int = 12, verbose: bool = True): self.verbose = verbose self.check = check self.limit = limit self.items = [] self.used = 0 self.source = '' self.refresh() def log(self, msg): if self.verbose: print(msg, flush=True) def refresh(self): cache = load_cache() # reuse a warm cache (< 10 min) instead of re-checking everything if cache.get('items') and (time.time() - cache.get('updated', 0)) < 600: alive = [c for c in cache['items'] if (time.time() - c.get('ts', 0)) < 1800] if len(alive) >= max(2, self.check // 3): self.items = [c['proxy'] for c in alive] self.used = 0 self.source = 'cache' self.log(f'[proxy] source=cache, {len(self.items)} alive proxies') return fresh = fetch_from_iishko(self.limit) candidates = fresh or [c['proxy'] for c in cache.get('items', [])] or SEED self.source = 'iishko' if fresh else ('cache' if cache.get('items') else 'seed') socks = [c for c in candidates if c.startswith('socks')] plain = [c for c in candidates if not c.startswith('socks')] batch = (socks + plain)[:max(self.check, 12)] self.log(f'[proxy] source={self.source}, checking {len(batch)} in parallel') checked = [] with ThreadPoolExecutor(max_workers=10) as ex: for p, ip in zip(batch, ex.map(verify, batch)): if ip: checked.append({'proxy': p, 'exit_ip': ip, 'ts': time.time()}) self.log(f'[proxy] ok {p} -> {ip}') if len(checked) >= self.check: break if not checked: self.log('[proxy] nothing verified, falling back to seed') for p in SEED: ip = verify(p) if ip: checked.append({'proxy': p, 'exit_ip': ip, 'ts': time.time()}) self.log(f'[proxy] ok {p} -> {ip}') if checked: save_cache(candidates, checked) self.items = [c['proxy'] for c in checked] self.used = 0 def take(self) -> str: if not self.items or self.used >= len(self.items): self.refresh() if not self.items: return '' p = self.items[self.used % len(self.items)] self.used += 1 return p def __len__(self): return len(self.items) if __name__ == '__main__': pool = ProxyPool(limit=40, check=6) print('verified:', len(pool), 'source:', pool.source) for _ in range(min(3, len(pool))): print(' take:', pool.take())