from flask import Flask, render_template, request, jsonify, session import subprocess import os import threading import uuid from datetime import datetime import shlex app = Flask(__name__) app.secret_key = os.urandom(24) # Случайный секретный ключ class CommandSession: def __init__(self): self.sessions = {} def create_session(self): session_id = str(uuid.uuid4()) self.sessions[session_id] = { 'created_at': datetime.now(), 'working_dir': os.getcwd(), 'history': [] } return session_id def execute_command(self, session_id, command): if session_id not in self.sessions: return "Сессия не найдена" session_data = self.sessions[session_id] # Добавляем команду в историю session_data['history'].append({ 'command': command, 'timestamp': datetime.now() }) try: # Выполняем команду в текущей директории сессии process = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=session_data['working_dir'], executable='/bin/bash' if os.name != 'nt' else None ) # Ждем завершения с таймаутом try: stdout, stderr = process.communicate(timeout=60) return_code = process.returncode except subprocess.TimeoutExpired: process.kill() stdout, stderr = process.communicate() return f"Ошибка: команда выполнялась слишком долго и была остановлена\n\nSTDOUT:\n{stdout}\nSTDERR:\n{stderr}" # Формируем вывод output = "" if stdout: output += f"STDOUT:\n{stdout}\n" if stderr: output += f"STDERR:\n{stderr}\n" if return_code != 0: output += f"Код возврата: {return_code}" return output.strip() except Exception as e: return f"Ошибка выполнения: {str(e)}" def change_directory(self, session_id, new_dir): if session_id not in self.sessions: return False, "Сессия не найдена" try: if new_dir == "~": new_dir = os.path.expanduser("~") elif new_dir == "-": # Возврат к предыдущей директории (можно реализовать при необходимости) new_dir = os.getcwd() new_dir = os.path.abspath(new_dir) if os.path.exists(new_dir) and os.path.isdir(new_dir): os.chdir(new_dir) self.sessions[session_id]['working_dir'] = new_dir return True, f"Директория изменена на: {new_dir}" else: return False, f"Директория не существует: {new_dir}" except Exception as e: return False, f"Ошибка смены директории: {str(e)}" command_manager = CommandSession() @app.route('/') def index(): if 'session_id' not in session: session['session_id'] = command_manager.create_session() return render_template('index.html') @app.route('/execute', methods=['POST']) def execute_command(): if 'session_id' not in session: return jsonify({'error': 'Сессия не найдена'}) data = request.get_json() command = data.get('command', '').strip() if not command: return jsonify({'error': 'Пустая команда'}) # Обработка команды cd if command.startswith('cd '): new_dir = command[3:].strip() success, message = command_manager.change_directory(session['session_id'], new_dir) return jsonify({ 'output': message, 'command': command, 'timestamp': datetime.now().strftime('%H:%M:%S'), 'current_dir': command_manager.sessions[session['session_id']]['working_dir'] }) # Выполняем команду output = command_manager.execute_command(session['session_id'], command) return jsonify({ 'output': output, 'command': command, 'timestamp': datetime.now().strftime('%H:%M:%S'), 'current_dir': command_manager.sessions[session['session_id']]['working_dir'] }) @app.route('/sessions', methods=['GET']) def list_sessions(): return jsonify({ 'active_sessions': len(command_manager.sessions), 'current_session': session.get('session_id'), 'current_dir': command_manager.sessions.get(session.get('session_id', ''), {}).get('working_dir', '') }) @app.route('/history', methods=['GET']) def command_history(): if 'session_id' not in session: return jsonify({'error': 'Сессия не найдена'}) session_data = command_manager.sessions.get(session['session_id']) if not session_data: return jsonify({'error': 'Данные сессии не найдены'}) history = session_data.get('history', [])[-10:] # Последние 10 команд formatted_history = [ { 'command': item['command'], 'timestamp': item['timestamp'].strftime('%H:%M:%S') } for item in history ] return jsonify({'history': formatted_history}) @app.route('/clear-session', methods=['POST']) def clear_session(): session_id = session.get('session_id') if session_id in command_manager.sessions: del command_manager.sessions[session_id] session.pop('session_id', None) return jsonify({'message': 'Сессия очищена'}) @app.route('/system-info', methods=['GET']) def system_info(): """Базовая информация о системе""" try: # Информация о системе system_info = { 'platform': os.uname().sysname if hasattr(os, 'uname') else os.name, 'current_user': os.getenv('USER', 'Unknown'), 'cpu_count': os.cpu_count(), 'current_directory': os.getcwd() } return jsonify(system_info) except Exception as e: return jsonify({'error': f'Не удалось получить информацию о системе: {str(e)}'}) if __name__ == '__main__': # Создаем папку для шаблонов если её нет os.makedirs('templates', exist_ok=True) # Создаем HTML шаблон with open('templates/index.html', 'w', encoding='utf-8') as f: f.write(''' Web Shell - Полный доступ

Web Shell - Полный доступ к системе

⚠️ ВНИМАНИЕ: Полный доступ к оболочке системы! Будьте осторожны с командами.
Добро пожаловать в Web Shell с полным доступом!
Доступны все команды системы. Таймаут выполнения: 60 секунд.
Текущая директория:
$
Загрузка... Команд выполнено: 0
''') print("Запуск Web Shell с полным доступом...") print("⚠️ ПРЕДУПРЕЖДЕНИЕ: Этот сервер предоставляет полный доступ к системе!") print("🚫 Не используйте в production без дополнительных мер безопасности!") print("🌐 Сервер запущен: http://0.0.0.0:5000") app.run(host='0.0.0.0', port=5000, debug=False)