import os
import asyncio
import aiohttp
import aiofiles
import zipfile
import shutil
import time
import json
from datetime import datetime
from colorama import init, Fore, Style
init()
print("""
▒█████ ██▓███ ███▄ ▄███▓ ▒█████ ▓██ ██▓ ▄▄▄
▒██▒ ██▒▓██░ ██ ▓██▒▀█▀ ██▒▒██▒ ██▒ ▒██ ██▒▒████▄
▒██░ ██▒▓██░ ██▓▒ ▓██ ▓██░▒██░ ██▒ ▒██ ██░▒██ ▀█▄
▒██ ██░▒██▄█▓▒ ▒ ▒██ ▒██ ▒██ ██░ ░ ▐██▓░░██▄▄▄▄██
░ ████▓▒░▒██▒ ░ ░▒▒██▒ ░██▒░ ████▓▒░ ░ ██▒▓░▒▓█ ▓██
░ ▒░▒░▒░ ▒▓▒░ ░ ░░░ ▒░ ░ ░░ ▒░▒░▒░ ██▒▒▒ ░▒▒ ▓▒█
░ ▒ ▒░ ░▒ ░ ░░ ░ ░ ░ ▒ ▒░ ▓██ ░▒░ ░ ░ ▒▒
░ ░ ░ ▒ ░░ ░ ░ ░ ░ ░ ▒ ▒ ▒ ░░ ░ ▒
░ ░ ░ ░ ░ ░ ░ ░ ░ \n
""")
config_file = 'config.json'
def load_config():
if not os.path.exists(config_file):
print(f"{Fore.RED}[!!!] Файл конфигурации {config_file} не найден, создаю.{Fore.RESET}")
config_data = {
"telegram_token": "TOKEN_TELEGRAM_BOT",
"chat_id": "CHAT_ID"
}
with open(config_file, 'w') as f:
json.dump(config_data, f, indent=4)
print(f'{Fore.GREEN}[+] Конфиг создан, заполните его и запускайте программу!\n{Fore.RESET}')
os.system('pause')
exit()
else:
print(f'{Fore.CYAN}[+++] Конфиг существует, начинаю работу!{Fore.RESET}')
#main()
with open(config_file, 'r') as f:
try:
config = json.load(f)
return config
except json.JSONDecodeError:
print(f"{Fore.RED}[!!!] Ошибка чтения конфигурационного файла {config_file}.{Fore.RESET}")
return None
now = datetime.now()
fdt = now.strftime("%Y-%m-%d ! %H - %M - %S")
async def parse_file(filename, queries, result_folder):
results = {}
found_queries = 0
not_found_queries = 0
async with aiofiles.open(filename, 'r', errors='replace') as file:
async for line_num, line in enumerate(file, start=1):
line = line.strip()
for query in queries:
if query['domain'] in line.lower():
found_queries += 1
os.makedirs(result_folder, exist_ok=True)
folder_name = query['name'].replace('/', '_').replace(':', '_')
folder_path = os.path.join(result_folder, folder_name)
os.makedirs(folder_path, exist_ok=True)
file_name = f'{query["name"]}.txt'
file_name = file_name.replace('/', '_').replace(':', '_')
file_path = os.path.join(folder_path, file_name)
results[file_name] = results.get(file_name, 0) + 1
try:
async with aiofiles.open(file_path, 'a', encoding='utf-8') as result_file:
await result_file.write(f'{line}\n')
except Exception as e:
print(f'Ошибка при сохранении строки в файл: {e} (строка {line_num})')
else:
not_found_queries += 1
return results, found_queries, not_found_queries, line_num
async def archive_results(result_folder):
zip_file_name = f'{result_folder}.zip'
if os.path.exists(result_folder):
try:
with zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, _, files in os.walk(result_folder):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, os.path.relpath(file_path, result_folder))
except Exception as e:
print(f'{Fore.RED}[!!!] Ошибка при создании архива: {e}{Fore.RESET}')
return None
print(f'{Fore.GREEN}[+] {Fore.RESET}Результаты успешно запакованы в архив: {zip_file_name}{Fore.RESET}')
return zip_file_name
else:
print(f'{Fore.RED}[!!!] Папка с результатами не найдена.{Fore.RESET}')
return None
async def send_to_telegram(token, chat_id, file_path):
if not file_path:
return
api_url = f'https://api.telegram.org/bot{token}/sendDocument'
try:
async with aiohttp.ClientSession() as session:
form_data = aiohttp.FormData()
form_data.add_field('chat_id', str(chat_id))
form_data.add_field('document', open(file_path, 'rb'))
async with session.post(api_url, data=form_data) as response:
if response.status == 200:
print(f'{Fore.GREEN}[+] {Fore.RESET}Результаты успешно отправлены в Telegram бота.{Fore.RESET}')
else:
print(f'{Fore.RED}[!!!] Ошибка при отправке результатов в Telegram. \n{response.text}{Fore.RESET}')
except Exception as e:
print(f'{Fore.RED}[!!!] Ошибка при отправке результатов в Telegram: {e}{Fore.RESET}')
# Удаляем архив после отправки
if os.path.exists(file_path):
os.remove(file_path)
def process_file_line(line):
for query in queries:
if query['domain'] in line.lower():
return query['name'], line
return None
if __name__ == '__main__':
config = load_config()
if config is None:
os.system('pause')
exit()
filename = 'req.txt'
queries = []
with open('qr.txt', 'r', encoding='utf-8') as qr_file:
lines = qr_file.readlines()
for line in lines:
line = line.strip()
if line:
query = {
'name': line,
'domain': line.lower()
}
queries.append(query)
result_folder = str("Results ") + str(datetime.now().strftime("%Y-%m-%d %H-%M-%S"))
found_queries = 0
total_lines = 0
results = {}
os.makedirs(result_folder, exist_ok=True)
start_time = time.time()
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
line = line.strip()
total_lines += 1
result = process_file_line(line)
if result:
query_name, result_line = result
found_queries += 1
folder_name = query_name.replace('/', '_').replace(':', '_')
folder_path = os.path.join(os.getcwd(), result_folder, folder_name)
os.makedirs(folder_path, exist_ok=True)
file_name = f'{query_name}.txt'
file_name = file_name.replace('/', '_').replace(':', '_')
file_path = os.path.join(folder_path, file_name)
if file_name in results:
results[file_name] += 1
else:
results[file_name] = 1
try:
with open(file_path, 'a', encoding='utf-8') as result_file:
result_file.write(f'{result_line}\n')
except Exception as e:
print(f'Ошибка при сохранении строки в файл: {e}')
for file_name, count in results.items():
if count > 0:
file_path = os.path.join(result_folder, file_name)
if os.path.exists(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as result_file:
for line in result_file:
print(line.strip())
except Exception as e:
print(f'Ошибка при чтении файла: {e}')
else:
print(f'Файл не существует: {file_name}')
end_time = time.time()
elapsed_time = end_time - start_time
print(f'Найдено: {Fore.GREEN}{found_queries}{Fore.RESET} | Не найдено: {Fore.RED}{total_lines - found_queries}{Fore.RESET} | Всего строк: {Fore.YELLOW}{total_lines}{Fore.RESET}')
print(f'Затраченное время: {Fore.CYAN}{elapsed_time // 60} {Fore.RESET}минут {Fore.BLUE}{elapsed_time % 60:.2f} {Fore.RESET}секунд\n')
print(f'\n{Fore.CYAN}[!] Результаты сохранены в: {Fore.WHITE}{Style.BRIGHT}{str("Results ") + str(fdt)}{Fore.RESET}')
# Архивация папки и отправка в Telegram
zip_file_name = asyncio.run(archive_results(result_folder))
if zip_file_name is not None:
telegram_token = config.get('telegram_token', '')
chat_id = config.get('chat_id', '')
asyncio.run(send_to_telegram(telegram_token, chat_id, zip_file_name))
# Получение полного пути для удаления архива
zip_file_path = os.path.abspath(zip_file_name)
# Удаление папки с результатами и архива после отправки в Telegram
#if os.path.exists(result_folder):
# shutil.rmtree(result_folder)
# Удаление архива
if os.path.exists(zip_file_path):
os.remove(zip_file_path)
os.system('pause')
Here is my code, rewrite it to Rust please, i'm very need. Be helpful