#!/bin/bash
============================================================
👻 GHOST KERNEL - بلوك واحد للنسخ والتشغيل من الصفر
انسخ هذا البلوك بالكامل والصقه في Termux واضغط Enter
============================================================
1️⃣ تثبيت الحزم
echo "[1/6] Installing packages..."
pkg update -y && pkg upgrade -y
pkg install python git nano -y
pip install requests
2️⃣ إنشاء المجلدات
echo "[2/6] Creating folders..."
mkdir -p Ghost_Kernel/core Ghost_Kernel/modules Ghost_Kernel/lib Ghost_Kernel/logs Ghost_Kernel/backup
cd Ghost_Kernel
3️⃣ إنشاء ملف helper.py
echo "[3/6] Creating helper.py..."
cat > lib/helper.py << 'HELPER_EOF'
#!/usr/bin/env python3
import os, sys, time, json, subprocess, hashlib, platform, shutil
from datetime import datetime
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))
LOGS_DIR = os.path.join(BASE_DIR, "logs")
FINGERPRINT_DIR = os.path.join(LOGS_DIR, "fingerprints")
os.makedirs(LOGS_DIR, exist_ok=True)
os.makedirs(FINGERPRINT_DIR, exist_ok=True)
def get_device_id():
try:
r = subprocess.run(["getprop", "ro.serialno"], capture_output=True, text=True, timeout=2)
if r.stdout.strip(): return r.stdout.strip()
except: pass
try:
r = subprocess.run(["ip", "link", "show", "wlan0"], capture_output=True, text=True, timeout=2)
for line in r.stdout.split('\n'):
if 'link/ether' in line:
return line.split('link/ether')[1].strip().split(' ')[0]
except: pass
return platform.node()
def get_file_hash(filepath):
try:
with open(filepath, 'rb') as f:
return hashlib.sha256(f.read()).hexdigest()
except: return None
def get_battery():
try:
r = subprocess.run(["termux-battery-status"], capture_output=True, text=True, timeout=3)
return json.loads(r.stdout).get("percentage", 100)
except: return 100
def log_event(function_name, message, level="info"):
timestamp = datetime.now().isoformat()
log_entry = {"timestamp": timestamp, "function": function_name, "message": message, "level": level, "device_id": get_device_id()}
log_file = os.path.join(LOGS_DIR, "ghost.log")
with open(log_file, 'a', encoding='utf-8') as f:
f.write(json.dumps(log_entry, ensure_ascii=False) + "\n")
colors = {"info": "\033[94m", "success": "\033[92m", "warning": "\033[93m", "error": "\033[91m", "reset": "\033[0m"}
print(f"{colors.get(level, colors['info'])}[{datetime.now().strftime('%H:%M:%S')}] [{function_name}] {message}{colors['reset']}")
return log_entry
def log_suspicious(function_name, message, extra=None):
timestamp = datetime.now().isoformat()
log_entry = {"timestamp": timestamp, "function": function_name, "message": message, "device_id": get_device_id(), "extra": extra or {}}
suspicious_file = os.path.join(LOGS_DIR, "suspicious.log")
with open(suspicious_file, 'a', encoding='utf-8') as f:
f.write(json.dumps(log_entry, ensure_ascii=False) + "\n")
print(f"\033[91m[🚨] {message}\033[0m")
return log_entry
def save_fingerprint(filepath, modifier="system"):
file_hash = get_file_hash(filepath)
if not file_hash: return None
data = {"file": filepath, "hash": file_hash, "timestamp": datetime.now().isoformat(), "device_id": get_device_id(), "modifier": modifier, "size": os.path.getsize(filepath) if os.path.exists(filepath) else 0}
safe_name = os.path.basename(filepath).replace('.', '_')
fp_file = os.path.join(FINGERPRINT_DIR, f"{safe_name}_fingerprint.json")
with open(fp_file, 'w') as f:
json.dump(data, f, indent=2)
return data
def check_integrity(filepath):
safe_name = os.path.basename(filepath).replace('.', '_')
fp_file = os.path.join(FINGERPRINT_DIR, f"{safe_name}_fingerprint.json")
if not os.path.exists(fp_file):
save_fingerprint(filepath, "system")
return True, "First time"
with open(fp_file, 'r') as f:
saved = json.load(f)
current_hash = get_file_hash(filepath)
if current_hash != saved.get("hash"):
log_suspicious("integrity", f"🚨 تم تعديل الملف: {filepath}")
return False, "Modified"
return True, "Clean"
def restore_backup(filepath):
backup_files = sorted([f for f in os.listdir(os.path.join(BASE_DIR, "backup")) if f.endswith('.py')])
if not backup_files: return False, "No backup"
latest = backup_files[-1]
backup_path = os.path.join(BASE_DIR, "backup", latest)
shutil.copy2(backup_path, filepath)
save_fingerprint(filepath, "restored")
return True, f"Restored from {latest}"
def enforce_protection(filepath):
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read(500)
if '!@#' not in content:
log_suspicious("protection", f"⚠️ علامة الحماية مفقودة: {filepath}")
success, msg = restore_backup(filepath)
if success: return True, "Auto-restored"
return False, "Manual fix needed"
return True, "OK"
except: return False, "Error"
HELPER_EOF
4️⃣ إنشاء ملفات الموديولات
echo "[4/6] Creating modules..."
cat > modules/mirror.py << 'MIRROR_EOF'
#!/usr/bin/env python3
!@# وحدة تمويه الشبكة
import random, time, requests, sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(file))))
from lib.helper import log_event, log_suspicious
def task_mirror():
log_event("task_mirror", "بدء مهمة تمويه الشبكة", "info")
sites = ["https://news.google.com";, "https://www.bbc.com/news";, "https://www.youtube.com";, "https://www.reddit.com/r/all";]
try:
url = random.choice(sites)
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
r = requests.get(url, headers=headers, timeout=10)
log_event("task_mirror", f"✅ {url[:30]}... ({r.status_code})", "success")
return {"task": "mirror", "status": r.status_code}
except Exception as e:
log_suspicious("task_mirror", f"فشل تمويه الشبكة: {e}")
return {"task": "mirror", "status": "failed"}
MIRROR_EOF
cat > modules/bluetooth.py << 'BLUETOOTH_EOF'
#!/usr/bin/env python3
!@# وحدة تشويش البلوتوث
import time, random, subprocess, sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(file))))
from lib.helper import log_event, log_suspicious
def task_bluetooth():
log_event("task_bluetooth", "بدء مهمة تشويش البلوتوث", "info")
try:
subprocess.run(["which", "termux-bluetooth-enable"], capture_output=True, check=True)
except:
log_suspicious("task_bluetooth", "⚠️ termux-bluetooth-enable غير موجود، تخطي المهمة")
return {"task": "bluetooth", "status": "disabled", "reason": "command not found"}
try:
subprocess.run(["termux-bluetooth-enable"], timeout=2, check=False)
time.sleep(random.randint(2, 4))
subprocess.run(["termux-bluetooth-disable"], timeout=2, check=False)
log_event("task_bluetooth", "✅ تم تشغيل وإيقاف البلوتوث", "success")
return {"task": "bluetooth", "status": "toggled"}
except Exception as e:
log_suspicious("task_bluetooth", f"فشل تشويش البلوتوث: {e}")
return {"task": "bluetooth", "status": "failed", "error": str(e)}
BLUETOOTH_EOF
cat > modules/bot.py << 'BOT_EOF'
#!/usr/bin/env python3
!@# وحدة بوت التشويش
import random, time, requests, sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(file))))
from lib.helper import log_event, log_suspicious
def task_bot():
log_event("task_bot", "بدء مهمة بوت التشويش", "info")
sites = ["https://news.google.com";, "https://www.wikipedia.org";]
try:
url = random.choice(sites)
requests.get(url, timeout=5)
log_event("task_bot", f"✅ {url[:30]}...", "success")
return {"task": "bot", "status": "success"}
except Exception as e:
log_suspicious("task_bot", f"فشل بوت التشويش: {e}")
return {"task": "bot", "status": "failed"}
BOT_EOF
cat > modules/init.py << 'INIT_EOF'
!@# ملف تهيئة الموديولات
INIT_EOF
5️⃣ إنشاء ملف المحرك (engine.py)
echo "[5/6] Creating engine.py..."
cat > core/engine.py << 'ENGINE_EOF'
#!/usr/bin/env python3
-- coding: utf-8 --
!@# المسودة الأساسية
import os, sys, time, json, random, subprocess, threading, queue, shutil, hashlib, platform
from datetime import datetime
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(file))))
from lib.helper import get_device_id, get_file_hash, get_battery, log_event, log_suspicious, check_integrity, save_fingerprint, restore_backup, enforce_protection
from modules.mirror import task_mirror
from modules.bluetooth import task_bluetooth
from modules.bot import task_bot
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))
LOGS_DIR = os.path.join(BASE_DIR, "logs")
BACKUP_DIR = os.path.join(BASE_DIR, "backup")
CONTROL_FILE = os.path.join(LOGS_DIR, "control.json")
RESPONSE_FILE = os.path.join(LOGS_DIR, "response.json")
os.makedirs(LOGS_DIR, exist_ok=True)
os.makedirs(BACKUP_DIR, exist_ok=True)
system_state = {
"running": True,
"paused": False,
"cycle_count": 0,
"errors": 0,
"speed": "normal",
"tasks": ["mirror", "bluetooth", "bot"],
"workers": {
"mirror": {"status": "idle", "last_run": None, "frozen": False, "error": None},
"bluetooth": {"status": "idle", "last_run": None, "frozen": False, "error": None},
"bot": {"status": "idle", "last_run": None, "frozen": False, "error": None}
}
}
def process_commands():
if not os.path.exists(CONTROL_FILE): return None
try:
with open(CONTROL_FILE, 'r') as f: command = json.load(f)
os.remove(CONTROL_FILE)
cmd = command.get("command")
params = command.get("params", {})
log_event("engine", f"📥 استلام أمر: {cmd}", "info")
response = {"status": "ok", "message": ""}
if cmd == "status":
workers_status = {}
for name, data in system_state["workers"].items():
workers_status[name] = {"status": data["status"], "frozen": data["frozen"], "error": data["error"]}
response["message"] = {"cycles": system_state["cycle_count"], "errors": system_state["errors"], "speed": system_state["speed"], "workers": workers_status}
elif cmd == "pause": system_state["paused"] = True; response["message"] = "⏸️ تم الإيقاف المؤقت"
elif cmd == "resume": system_state["paused"] = False; response["message"] = "▶️ تم الاستئناف"
elif cmd == "restart": response["message"] = "🔄 إعادة تشغيل..."
elif cmd == "stop": system_state["running"] = False; response["message"] = "🛑 تم الإيقاف"
elif cmd == "backup":
backup_file = os.path.join(BACKUP_DIR, f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.py")
shutil.copy2(file, backup_file)
response["message"] = f"✅ نسخة احتياطية: {backup_file}"
elif cmd == "restore": success, msg = restore_backup(file); response["message"] = msg
elif cmd == "check": status, msg = check_integrity(file); response["message"] = msg
elif cmd == "log":
log_file = os.path.join(LOGS_DIR, "ghost.log")
if os.path.exists(log_file):
with open(log_file, 'r') as f: lines = f.readlines()[-5:]; response["message"] = "".join(lines)
else: response["message"] = "لا توجد سجلات"
elif cmd == "self_check": response["message"] = json.dumps(self_check(), ensure_ascii=False)
elif cmd == "unfreeze":
task_name = params.get("task")
if task_name and task_name in system_state["workers"]:
system_state["workers"][task_name]["frozen"] = False
system_state["workers"][task_name]["error"] = None
system_state["workers"][task_name]["status"] = "idle"
response["message"] = f"✅ تم فك تجميد: {task_name}"
else: response["message"] = "⚠️ المهمة غير موجودة"
elif cmd == "add_task":
task = params.get("task")
if task and task not in system_state["tasks"]:
system_state["tasks"].append(task); response["message"] = f"✅ تم إضافة: {task}"
else: response["message"] = "⚠️ موجودة أو غير صالحة"
elif cmd == "remove_task":
task = params.get("task")
if task in system_state["tasks"]:
system_state["tasks"].remove(task); response["message"] = f"✅ تم حذف: {task}"
else: response["message"] = "⚠️ غير موجودة"
elif cmd == "list_tasks": response["message"] = system_state["tasks"]
elif cmd == "set_speed":
speed = params.get("speed")
if speed in ["بطيء", "متوسط", "سريع"]:
system_state["speed"] = speed; response["message"] = f"✅ السرعة: {speed}"
else: response["message"] = "⚠️ السرعات: بطيء، متوسط، سريع"
else: response["message"] = f"⚠️ أمر غير معروف: {cmd}"
with open(RESPONSE_FILE, 'w') as f: json.dump(response, f, indent=2)
return command
except Exception as e: log_suspicious("engine", f"خطأ في معالجة الأوامر: {e}"); return None
def self_check():
check_results = {"timestamp": datetime.now().isoformat(), "workers": {}, "system": {}}
battery = get_battery()
check_results["system"]["battery"] = battery
if battery < 15: log_suspicious("self_check", f"⚠️ بطارية منخفضة: {battery}%")
integrity_status, _ = check_integrity(file)
check_results["system"]["integrity"] = "ok" if integrity_status else "corrupted"
if not integrity_status: log_suspicious("self_check", "🚨 الملف الأساسي متغير!")
for worker_name, worker_data in system_state["workers"].items():
check_results["workers"][worker_name] = {"status": worker_data["status"], "frozen": worker_data["frozen"], "error": worker_data["error"], "last_run": worker_data["last_run"]}
log_event("self_check", f"📋 مراجعة: {json.dumps(check_results, ensure_ascii=False)}", "info")
return check_results
def execute_safe(task_name, task_func):
worker = system_state["workers"].get(task_name)
if not worker: return {"status": "error", "message": "مهمة غير معروفة"}
if worker["frozen"]:
log_event("engine", f"⏸️ {task_name} مجمدة، تخطي", "warning")
return {"status": "frozen", "message": "المهمة مجمدة"}
try:
worker["status"] = "running"
result = task_func()
if result.get("status") in [200, "success", "toggled"]:
worker["status"] = "success"
worker["last_run"] = datetime.now().isoformat()
worker["error"] = None
if worker["frozen"]:
worker["frozen"] = False
log_event("engine", f"✅ تم فك تجميد {task_name} تلقائياً", "success")
log_event("engine", f"✅ {task_name} نجحت", "success")
return result
else:
error_msg = result.get("error", "فشل غير معروف")
worker["status"] = "failed"
worker["error"] = error_msg
worker["frozen"] = True
system_state["errors"] += 1
log_suspicious("engine", f"⛔ {task_name} فشلت وتم تجميدها: {error_msg}")
return {"status": "frozen", "message": f"تم تجميد {task_name}"}
except Exception as e:
worker["status"] = "error"
worker["error"] = str(e)
worker["frozen"] = True
system_state["errors"] += 1
log_suspicious("engine", f"💥 {task_name} خطأ وتم تجميدها: {e}")
return {"status": "error", "message": str(e)}
def engine_loop():
print("""
╔══════════════════════════════════════════════════════════════╗
║ 👻 GHOST ENGINE V6 - التجميد التلقائي للمهام المعطلة ║
║ أي خلل → تجميد المهمة → المسودة تكمل ║
╚══════════════════════════════════════════════════════════════╝
""")
log_event("engine", "🚀 بدء تشغيل المحرك", "success")
backup_file = os.path.join(BACKUP_DIR, f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.py")
shutil.copy2(file, backup_file)
log_event("engine", f"📦 نسخة احتياطية: {backup_file}", "info")
print("[✅] جميع الأنظمة جاهزة")
print("[📡] استخدم controller.py للتحكم")
while system_state["running"]:
try:
process_commands()
if system_state["paused"]: time.sleep(2); continue
system_state["cycle_count"] += 1
speed_map = {"بطيء": 60, "متوسط": 30, "سريع": 15}
wait_time = speed_map.get(system_state["speed"], 30)
available_tasks = [t for t in system_state["tasks"] if not system_state["workers"][t]["frozen"]]
if available_tasks:
task_name = random.choice(available_tasks)
log_event("engine", f"🔄 تنفيذ: {task_name}", "info")
task_map = {"mirror": task_mirror, "bluetooth": task_bluetooth, "bot": task_bot}
if task_name in task_map:
result = execute_safe(task_name, task_map[task_name])
if result.get("status") == "frozen":
log_suspicious("engine", f"⛔ {task_name} مجمدة، تخطي", {"task": task_name})
else:
log_event("engine", "⚠️ لا توجد مهام متاحة (كلها مجمدة)", "warning")
wait_time = 60
if system_state["cycle_count"] % 5 == 0: self_check()
time.sleep(wait_time)
except KeyboardInterrupt:
log_event("engine", "🛑 تم إيقاف المحرك", "warning"); break
except Exception as e:
log_suspicious("engine", f"💥 خطأ: {e}"); time.sleep(30)
log_event("engine", "🛑 المحرك توقف", "warning")
if name == "main":
try: engine_loop()
except KeyboardInterrupt: print("\n[🛑] Stopped by user")
ENGINE_EOF
6️⃣ إنشاء ملف التحكم (controller.py)
echo "[6/6] Creating controller.py..."
cat > controller.py << 'CONTROLLER_EOF'
#!/usr/bin/env python3
-- coding: utf-8 --
!@# وحدة التحكم
import os, sys, time, json
BASE_DIR = os.path.dirname(os.path.abspath(file))
LOGS_DIR = os.path.join(BASE_DIR, "logs")
CONTROL_FILE = os.path.join(LOGS_DIR, "control.json")
RESPONSE_FILE = os.path.join(LOGS_DIR, "response.json")
os.makedirs(LOGS_DIR, exist_ok=True)
def send_command(cmd, params=None):
command = {"timestamp": time.time(), "command": cmd, "params": params or {}}
with open(CONTROL_FILE, 'w') as f: json.dump(command, f, indent=2)
print(f"[📤] أمر مرسل: {cmd}")
time.sleep(1)
if os.path.exists(RESPONSE_FILE):
with open(RESPONSE_FILE, 'r') as f:
response = json.load(f)
print(f"[📥] الرد: {response.get('message', '')}")
return response
print("[⚠️] لا يوجد رد")
return None
def main():
print("""
╔══════════════════════════════════════════════════════════════╗
║ 🎮 CONTROLLER - التحكم في البوت ║
║ أدخل أمراً للتحكم بالبوت وهو شغال ║
╚══════════════════════════════════════════════════════════════╝
""")
while True:
try:
cmd = input("[🎮] أمر: ").strip()
if cmd.lower() in ["exit", "quit", "q"]: print("[👋] الخروج"); break
elif cmd == "help":
print("""
الأوامر المتاحة:
──────────────────────────────────
status → عرض حالة البوت
pause → إيقاف مؤقت
resume → استئناف
restart → إعادة تشغيل
stop → إيقاف نهائي
backup → نسخة احتياطية
restore → استرجاع
check → فحص الملفات
log → آخر السجلات
list_tasks → عرض المهام
self_check → مراجعة ذاتية
add_task X → إضافة مهمة X
remove_task X → حذف مهمة X
unfreeze X → فك تجميد مهمة X
set_speed S → بطيء/متوسط/سريع
help → هذه المساعدة
──────────────────────────────────
""")
elif cmd.startswith("add_task "):
task = cmd.split(" ", 1)[1]; send_command("add_task", {"task": task})
elif cmd.startswith("remove_task "):
task = cmd.split(" ", 1)[1]; send_command("remove_task", {"task": task})
elif cmd.startswith("unfreeze "):
task = cmd.split(" ", 1)[1]; send_command("unfreeze", {"task": task})
elif cmd.startswith("set_speed "):
speed = cmd.split(" ", 1)[1]
if speed in ["بطيء", "متوسط", "سريع"]: send_command("set_speed", {"speed": speed})
else: print("❌ السرعات: بطيء، متوسط، سريع")
else: send_command(cmd)
except KeyboardInterrupt: print("\n[👋] الخروج"); break
except Exception as e: print(f"[❌] خطأ: {e}")
if name == "main": main()
CONTROLLER_EOF
7️⃣ إنشاء ملف start.sh
echo "[7/7] Creating start.sh..."
cat > start.sh << 'START_EOF'
#!/bin/bash
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " 👻 GHOST KERNEL - بدء التشغيل"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
mkdir -p logs backup
python3 core/engine.py &
echo "✅ البوت شغال في الخلفية"
echo "📡 استخدم: python3 controller.py للتحكم"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
wait
START_EOF
8️⃣ منح الصلاحيات
chmod +x start.sh
9️⃣ التشغيل
echo "[🔟] Starting Ghost Kernel..."
bash start.sh
pkill -f engine.pyللاغلاق
cd ~/Ghost_Kernel
python3 controller.py
للتحكم