commit f4a511ca445034b99e81f47975c92b9d29b1460f Author: Кирилл Карачев Date: Wed Dec 2 17:37:02 2026 +0700 init diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..bd1615a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +log +*.log \ No newline at end of file diff --git a/.env b/.env new file mode 100644 index 0000000..3f394be --- /dev/null +++ b/.env @@ -0,0 +1,4 @@ +BOT_TOKEN = "7789844906:AAHScz2s22sceuY-nvE8ZRDuoRiBvRmZL6o" +HOST_SERVER= "82.147.75.252" +ADMIN_USERNAME = "admin" +ADMIN_PASSWORD = "Terrarik22" \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..edfe748 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.venv +log diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..1e26040 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.terminal.useEnvFile": true +} \ No newline at end of file diff --git a/DockerFile b/DockerFile new file mode 100644 index 0000000..91776e6 --- /dev/null +++ b/DockerFile @@ -0,0 +1 @@ +FROM python:3.14 diff --git a/__pycache__/secret.cpython-312.pyc b/__pycache__/secret.cpython-312.pyc new file mode 100644 index 0000000..375049a Binary files /dev/null and b/__pycache__/secret.cpython-312.pyc differ diff --git a/__pycache__/serverssh.cpython-315.pyc b/__pycache__/serverssh.cpython-315.pyc new file mode 100644 index 0000000..88b2131 Binary files /dev/null and b/__pycache__/serverssh.cpython-315.pyc differ diff --git a/app.db b/app.db new file mode 100644 index 0000000..af53bc5 Binary files /dev/null and b/app.db differ diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..8bcb4b4 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,15 @@ +version: '3.3' +networks: + auditbot: + driver: bridge + +services: + auditbot: + container_name: auditbot + env_file: + - .env + build: + context: . + dockerfile: Dockerfile + networks: + - backend diff --git a/main.py b/main.py new file mode 100644 index 0000000..9622956 --- /dev/null +++ b/main.py @@ -0,0 +1,40 @@ +import os +from datetime import date + +from dotenv import load_dotenv +from telegram import BotCommand, Update +from telegram.ext import Application, ApplicationBuilder, CommandHandler, ContextTypes + +from serverssh import ( + create_download_link, + execute_server_audit, + get_user_by_tid, + remove_audit_file, +) + +load_dotenv() + +async def load_menu(app: Application) -> None: + await app.bot.set_my_commands( + [ + BotCommand("get_analytic_server", "Получить аналитику по удаленному серверу"), + BotCommand("download_data", "Получить данные пользователя"), + ]) + +app = ApplicationBuilder().token(os.getenv('BOT_TOKEN')).post_init(load_menu).build() + +async def download_data(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + await update.message.reply_text('Обращаемся к удаленному серверу по данным пользователя...') + user = get_user_by_tid(tid=update.effective_user.id) + now_utc = date.today() + if user: + execute_server_audit(user=user[2], pwd=user[3]) + create_download_link(user=user[2], pwd=user[3]) + remove_audit_file(user=user[2], pwd=user[3]) + chat_id = update.effective_chat.id + context.bot.send_document(chat_id, document=open(f'audit_{now_utc}.txt', 'rb')) + +app.add_handler(CommandHandler("download_data", download_data)) + +if __name__ == '__main__': + app.run_polling() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..6f4c3bc Binary files /dev/null and b/requirements.txt differ diff --git a/serverssh.py b/serverssh.py new file mode 100644 index 0000000..6b255b1 --- /dev/null +++ b/serverssh.py @@ -0,0 +1,92 @@ +import fnmatch +import logging +import os +import sqlite3 +from datetime import date + +import paramiko +from dotenv import load_dotenv + +load_dotenv() + + +class RegisteredUser: + tid: str + username: str + password: str + +class AnalyticData: + memory: str + containers: list + +logging.basicConfig(filename="app.log", + level=logging.INFO, + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + encoding="utf-8") + +logger = logging.getLogger(__name__) + +def find_latest_file( + sftp, + remote_dir: str, + pattern: str = "*", +) -> str | None: + try: + entries = sftp.listdir_attr(remote_dir) + except FileNotFoundError: + return None + + candidates = [ + e for e in entries + if fnmatch.fnmatch(e.filename, pattern) + and not e.filename.startswith(".") + ] + if not candidates: + return None + + # Самый свежий по времени модификации + latest = max(candidates, key=lambda e: e.st_mtime) + return f"{remote_dir.rstrip('/')}/{latest.filename}" + + +def get_user_by_tid(tid: str) -> RegisteredUser: + try: + db = sqlite3.connect("app.db") + cursor = db.cursor() + cursor.execute(f"SELECT * FROM telegram_users WHERE tid = '{tid}'") + user: list[RegisteredUser] = cursor.fetchall() + if user.count == 0: + return "(Пользователь не найден)" + return user[0] + finally: + db.close() + +def execute_server_audit(user: str, pwd: str) -> None: + try: + client = paramiko.SSHClient() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(hostname=os.getenv('HOST_SERVER'), username=user, password=pwd, timeout=60, banner_timeout=30) + client.exec_command("cd /usr/audit && sudo ./server_audit.sh") + finally: + client.close() + +def remove_audit_file(user: str, pwd: str): + try: + client = paramiko.SSHClient() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(hostname=os.getenv('HOST_SERVER'), username=user, password=pwd, timeout=60, banner_timeout=30) + client.exec_command("cd /usr/audit && sudo rm -- *.txt") + finally: + client.close() + +def create_download_link(user: str, pwd: str) -> None: + try: + with paramiko.SSHClient() as client: + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(hostname=os.getenv('HOST_SERVER'), username=user, password=pwd, timeout=60, banner_timeout=30) + sftp = client.open_sftp() + now_utc = date.today() + sftp.get(find_latest_file(sftp=sftp, remote_dir="/usr/audit", pattern="server_report_*.txt"), f"audit_{now_utc}.txt") + finally: + client.close() + sftp.close() \ No newline at end of file