Сортер паролей

Сортер паролей

Тема в разделе Python создана пользователем Georstargiystar
Georstargiystar Автор темы
точно не помню откуда но вот немного изменений код:

kod:
import os
import asyncio
import aiohttp
import aiofiles
import zipfile
import shutil
import time
import re
import json
from datetime import datetime
from colorama import init, Fore, Style

regexPattern = r"http*.*?:.*?:"

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='latin-1') 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 merge_results(result_folder):
    merged_file_name = 'All_Lines_Merged_LP.txt'
    merged_file_path = os.path.join(result_folder, merged_file_name)
    merged_file_name_ulp = 'All_Lines_Merged_ULP.txt'
    merged_file_path_ulp = os.path.join(result_folder, merged_file_name_ulp)

    try:
        with open(merged_file_path, 'w', encoding='latin-1') as merged_file:
            for root, _, files in os.walk(result_folder):
                for file in files:
                    file_path = os.path.join(root, file)
                    if file.endswith("_logpass.txt"):
                        try:
                            with open(file_path, 'r', encoding='latin-1') as result_file:
                                for line in result_file:
                                    if ":" in line:
                                        merged_file.write(line)
                        except Exception as e:
                            print(f'Ошибка при чтении файла {file_path}: {e}')
        with open(merged_file_path_ulp, 'w', encoding='latin-1') as merged_file_ulp:
            for root, _, files in os.walk(result_folder):
                for file in files:
                    file_path = os.path.join(root, file)
                    if file.endswith("_ulp.txt"):
                        try:
                            with open(file_path, 'r', encoding='latin-1') as result_file_ulp:
                                for line in result_file_ulp:
                                    if ":" in line:
                                        merged_file_ulp.write(line)
                        except Exception as e:
                            print(f'Ошибка при чтении файла {file_path}: {e}')
    except Exception as e:
        print(f'Ошибка при создании объединенного файла: {e}')
        return None

    print(f'{Fore.GREEN}[+] {Fore.RESET}Все строки с log:pass успешно объединены в файл: {merged_file_name}{Fore.RESET}\n{Fore.GREEN}[+] {Fore.RESET}Все строки с url:log:pass успешно объединены в файл: {merged_file_name_ulp}{Fore.RESET}')
    return merged_file_path, merged_file_path_ulp


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, found_queries, total_lines, elapsed_time):
    if not file_path:
        return

    api_url = f'https://api.telegram.org/bot{token}/sendDocument'

    additional_info = (
        f'\nНайдено: {found_queries}\n'
        f'Не найдено: {total_lines - found_queries}\n'
        f'Всего строк: {total_lines}\n'
        f'Затраченное время: {elapsed_time // 60} минут '
        f'{elapsed_time % 60:.2f} секунд\n'
    )

    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'))
            form_data.add_field('caption', additional_info)

            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):
    logpass_data = None
    for query in queries:
        if query['domain'] in line.lower():
            try:
                loope = re.search(regexPattern, line)
                if loope:
                    parts = line.split(":")
                    logpass_data = parts
            except Exception:
                continue
            return query['name'], line, logpass_data
    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='latin-1') 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='latin-1') as file:
        for line in file:
            line = line.strip()
            total_lines += 1

            result = process_file_line(line)
            if result:
                query_name, result_line, logpass_data = 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}_ulp.txt'
                file_name = file_name.replace('/', '_').replace(':', '_')
                file_path = os.path.join(folder_path, file_name)

                file_name_lp = f'{query_name}_logpass.txt'
                file_name_lp = file_name_lp.replace('/', '_').replace(':', '_')
                file_path_lp = os.path.join(folder_path, file_name_lp)

                if file_name in results:
                    results[file_name] += 1
                else:
                    results[file_name] = 1

                if file_name_lp in results:
                    results[file_name_lp] += 1
                else:
                    results[file_name_lp] = 1

                try:
                    with open(file_path, 'a', encoding='latin-1') as result_file:
                        result_file.write(f'{result_line}\n')
                except Exception as e:
                    print(f'Ошибка при сохранении строки в файл: {e}')

                try:
                    with open(file_path_lp, 'a', encoding="latin-1") as result_file_lp:
                        result_file_lp.write(f"{logpass_data[2]}:{logpass_data[3]}\n")
                except Exception as e:
                    #print(f"Ошибка при сохранении строки в файл: {e}")
                    continue

    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='latin-1') 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}')

    # print(results.items())

    merged_file_path = asyncio.run(merge_results(result_folder))

    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, found_queries, total_lines, elapsed_time))

        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')

При первом запуске он создаст конфиг который нужно заполнить (телеграм токен и ид куда он будет кидать результат)

Создаете 2 файла txt
req.txt , туда кидаете строки которые нужно отсортить
qr.txt запросы которые вам нужны, каждый запрос с новой строчке
- - Сообщение объединено с предыдущим:

1
Georstargiystar Автор темы
Немного переписал с gpt код теперь собирает строки из всех txt в папке а не только req + детальная статистика отправляется в тг:

сортер:
import os
import zipfile
import json
from datetime import datetime
from colorama import init, Fore
import requests

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}')

    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

def parse_file(filename, queries, result_folder):
    results = {}
    
    with open(filename, 'r', encoding='latin-1') as file:
        for line_num, line in enumerate(file, start=1):
            line = line.strip()

            for query in queries:
                if query['domain'] in line.lower():
                    folder_name = query['name'].replace('/', '_').replace(':', '_')
                    folder_path = os.path.join(result_folder, folder_name)
                    file_name = f'{query["name"]}.txt'

                    results[file_name] = results.get(file_name, 0) + 1


                    os.makedirs(folder_path, exist_ok=True)

                    # Файлы для URL и log:pass
                    file_name_ulp = f'{query["name"]}_ulp.txt'
                    file_name_logpass = f'{query["name"]}_logpass.txt'
                    
                    file_path_ulp = os.path.join(folder_path, file_name_ulp)
                    file_path_logpass = os.path.join(folder_path, file_name_logpass)

                    # Запись в файл url:log:pass
                    with open(file_path_ulp, 'a', encoding='latin-1') as result_file_ulp:
                        result_file_ulp.write(f'{line}\n')

                    # Запись log:pass
                    if ":" in line:
                        logpass_data = line.split(":")
                        with open(file_path_logpass, 'a', encoding='latin-1') as result_file_logpass:
                            result_file_logpass.write(f'{logpass_data[-2]}:{logpass_data[-1]}\n')

    return results

def merge_results(result_folder):
    merged_file_name = 'All_Lines_Merged_LP.txt'
    merged_file_path = os.path.join(result_folder, merged_file_name)
    merged_file_name_ulp = 'All_Lines_Merged_ULP.txt'
    merged_file_path_ulp = os.path.join(result_folder, merged_file_name_ulp)

    with open(merged_file_path, 'w', encoding='latin-1') as merged_file:
        for root, _, files in os.walk(result_folder):
            for file in files:
                file_path = os.path.join(root, file)
                if file.endswith("_logpass.txt"):
                    with open(file_path, 'r', encoding='latin-1') as result_file:
                        for line in result_file:
                            if ":" in line:
                                merged_file.write(line)

    with open(merged_file_path_ulp, 'w', encoding='latin-1') as merged_file_ulp:
        for root, _, files in os.walk(result_folder):
            for file in files:
                file_path = os.path.join(root, file)
                if file.endswith("_ulp.txt"):
                    with open(file_path, 'r', encoding='latin-1') as result_file_ulp:
                        for line in result_file_ulp:
                            if ":" in line:
                                merged_file_ulp.write(line)

    print(f'{Fore.GREEN}[+] Все строки с log:pass успешно объединены в файл: {merged_file_name}{Fore.RESET}\n'
          f'{Fore.GREEN}[+] Все строки с url:log:pass успешно объединены в файл: {merged_file_name_ulp}{Fore.RESET}')
    
    return merged_file_path, merged_file_path_ulp

def archive_results(result_folder):
    zip_file_name = f'{result_folder}.zip'

    if os.path.exists(result_folder):
        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))

        print(f'{Fore.GREEN}[+] Результаты успешно запакованы в архив: {zip_file_name}{Fore.RESET}')
        return zip_file_name
    else:
        print(f'{Fore.RED}[!!!] Папка с результатами не найдена.{Fore.RESET}')
        return None

def send_to_telegram(token, chat_id, file_path, detailed_stats):
    if not file_path:
        return

    api_url = f'https://api.telegram.org/bot{token}/sendDocument'
    
    additional_info = 'Детальная статистика:\n'
    for query_name in detailed_stats.keys():
        additional_info += f"{query_name}: Найдено {detailed_stats[query_name]}\n"

    with open(file_path, 'rb') as f:
        files = {'document': f}
        response = requests.post(api_url, files=files, data={'chat_id': chat_id, 'caption': additional_info})
        if response.status_code == 200:
            print(f'{Fore.GREEN}[+] Результаты успешно отправлены в Telegram бота.{Fore.RESET}')
        else:
            print(f'{Fore.RED}[!!!] Ошибка при отправке результатов в Telegram. \n{response.text}{Fore.RESET}')

    if os.path.exists(file_path):
        os.remove(file_path)

if __name__ == '__main__':
    config = load_config()
    if config is None:
        os.system('pause')
        exit()

    queries = []
    with open('qr.txt', 'r', encoding='latin-1') 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 = f"Results {datetime.now().strftime('%Y-%m-%d %H-%M-%S')}"
    os.makedirs(result_folder, exist_ok=True)

    detailed_stats = {query['name']: 0 for query in queries}

    input_folder = 'input_folder'  # Укажите вашу папку с файлами
    for filename in os.listdir(input_folder):
        if filename.endswith('.txt'):
            full_path = os.path.join(input_folder, filename)
            print(f'Обрабатываю файл: {full_path}')
            results = parse_file(full_path, queries, result_folder)

            for query_name in results.keys():
                base_query_name = query_name.replace('.txt', '')
                if base_query_name in detailed_stats:
                    detailed_stats[base_query_name] += results[query_name]

    merged_file_path, merged_file_path_ulp = merge_results(result_folder)
    zip_file_name = archive_results(result_folder)
    if zip_file_name is not None:
        telegram_token = config.get('telegram_token', '')
        chat_id = config.get('chat_id', '')
        send_to_telegram(telegram_token, chat_id, zip_file_name, detailed_stats)

    os.system('pause')

Сверху