init
This commit is contained in:
commit
f4a511ca44
12 files changed
+159
No files matched your search
@@ -0,0 +1,2 @@
|
|||||||
|
log
|
||||||
|
*.log
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
BOT_TOKEN = "7789844906:AAHScz2s22sceuY-nvE8ZRDuoRiBvRmZL6o"
|
||||||
|
HOST_SERVER= "82.147.75.252"
|
||||||
|
ADMIN_USERNAME = "admin"
|
||||||
|
ADMIN_PASSWORD = "Terrarik22"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
.venv
|
||||||
|
log
|
||||||
Vendored
+3
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"python.terminal.useEnvFile": true
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
FROM python:3.14
|
||||||
Binary file not shown.
Binary file not shown.
@@ -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
|
||||||
@@ -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()
|
||||||
Binary file not shown.
@@ -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()
|
||||||
Reference in new issue
Block a user