Home » Tutorials » How to Create a Wordlist Generator in Python

How to Create a Wordlist Generator in Python

In cybersecurity and ethical hacking, generating and using wordlists is a key skill. Wordlists are essential for tasks like password cracking and security testing. If you’ve read our blog, you might have encountered our articles on How to Crack PDF Files in Python and How to Crack Passwords Through the Dictionary Method in Python. Both of these techniques require a wordlist, which is exactly what we’re going to do in today’s tutorial.

You’ll learn how to create a Wordlist Generator in Python with a graphical user interface (GUI) using tkinter. You’ll be able to set the maximum and minimum lengths and decide whether to generate all possible variations or limit the number of words. We’ll cover generating wordlists with customizable character sets, lengths, and variations, and saving them to a file. We’ll make sure the tool is flexible and easy to use, taking advantage of Python’s powerful features.

Let’s get started!

Table of Contents

Necessary Libraries

Make sure to install the tkinter library via the terminal or your command prompt for the code to function properly:

$ pip install tk

Imports

Before we create our dynamic Wordlist Generator, we need to bring in our building tools by importing the necessary libraries. So, without further ado, let’s begin:

  • os: This allows us to interact with the operating system.
  • product from itertools: This gem helps us generate all possible combinations of characters, giving us the flexibility to create diverse and comprehensive wordlist.
  • tkinter: Our go-to for crafting a graphical user interface (GUI). With tkinter, we can build an intuitive and user-friendly interface. Plus, by importing specific classes and functions, we can make our GUI even more robust and interactive.
  • threading: This ensures our GUI remains smooth and responsive, even while the Wordlist Generator is hard at work.
import os
from itertools import product
from tkinter import Tk, Label, Entry, Button, StringVar, IntVar, filedialog, messagebox, Checkbutton, BooleanVar
from tkinter.ttk import Progressbar
import threading

The Generate Wordlist Function

Now, here you need to pay close attention because this is where the magic happens: creating a wordlist based on the provided parameters. How does it do that? You don’t need to wonder because we will explain it right now:

  • First, this function takes the characters, their minimum and maximum lengths, and the output file provided by the user as inputs. It then uses sum() and range() to calculate the total number of combinations possible within the limit of the provided inputs. Next, it determines how much the progress bar should move up for each generated word (step).
  • After that, it opens the output file, and if it doesn’t exist, it creates one. It then uses product to generate combinations of characters, considering the maximum and minimum lengths of the characters as well as the max word count of the wordlist.
  • Finally, once the wordlist is complete; whether by reaching the word count or finishing all possible combinations (according to the user’s choice), a message box indicating the success of this process is displayed.
def generate_wordlist(chars, min_len, max_len, output_file, max_words, all_variations, progress):
   total_combinations = sum(len(chars) ** length for length in range(min_len, max_len + 1))
   word_count = 0
   step = 100 / total_combinations if all_variations else 100 / max_words


   with open(output_file, 'w') as file:
       for length in range(min_len, max_len + 1):
           for combo in product(chars, repeat=length):
               if not all_variations and word_count >= max_words:
                   messagebox.showinfo("Info", f"Reached the limit of {max_words} words.")
                   return
               word = ''.join(combo)
               file.write(word + '\n')
               word_count += 1
               progress.step(step)
               progress.update_idletasks()


   messagebox.showinfo("Success", f"Wordlist successfully created and saved to {output_file}")

Browse Output File Function

If you’ve been following our blog, you know we’re all about making our programs user-friendly, and this one is no exception. The goal of this function is to make it super easy to choose where to save your wordlist. That’s why we used filedialog, so you or any other user can easily select the save location and even name the file. We also ensured that the output file is a text file by adding a “.txt” extension.

def browse_output_file():
   filename = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text files", "*.txt")])
   output_file.set(filename)

Creating a User-Friendly Interface for Wordlist Generation

Here’s where user input meets functionality. This function takes the user’s input, validates it, and starts the wordlist generation in a separate thread. How does it work? You must be wondering. Well, it uses the get() function to retrieve the input characters. Then, thanks to the try-except block, it ensures that the input max and min lengths are integers. It also checks that the user has entered the characters and the output file path, and ensures that the minimum length of characters is not greater than the maximum.

Additionally, it uses os to check if the output file already exists and presents the user with the choice to overwrite it or not. Finally, it starts a new thread that calls the generate_wordlist() function while also starting the progress bar.

def generate_wordlist_gui():
   chars = characters.get()
   try:
       min_len = int(min_length.get())
       max_len = int(max_length.get())
       max_words = int(max_words_var.get())
   except ValueError:
       messagebox.showerror("Input Error", "Lengths and max words must be integers.")
       return


   if not chars:
       messagebox.showerror("Input Error", "Characters set cannot be empty.")
       return


   if min_len > max_len:
       messagebox.showerror("Input Error", "Minimum length cannot be bigger than the Maximum length.")
       return


   output_filepath = output_file.get()
   if not output_filepath:
       messagebox.showerror("Input Error", "Output file path cannot be empty.")
       return


   if os.path.exists(output_filepath):
       overwrite = messagebox.askyesno("File Exists", f"File {output_filepath} already exists. Overwrite?")
       if not overwrite:
           return


   progress_bar['value'] = 0
   threading.Thread(target=generate_wordlist, args=(
   chars, min_len, max_len, output_filepath, max_words, all_variations.get(), progress_bar)).start()

Main GUI Layout

Lastly, we assemble our digital workshop. This part of the code initializes the main window and sets its title. It uses Tkinter’s special variables (StringVar, IntVar, BooleanVar) to hold the values entered by the user. Next, it creates the labels that prompt the user to enter values, along with the entry boxes where the user can input those values. It also includes a browse button that calls the browse_output_file() function and a “Generate Wordlist” button that calls the generate_wordlist_gui() function.

Additionally, it creates a Checkbutton and a progress bar, placing all of these elements on the main window using the grid layout. Finally, it uses the mainloop() method to start the main event loop, keeping the main window running and responsive to the user.

# Set up the main window
root = Tk()
root.title("Wordlist Generator - The Pycodes")


# Variables
characters = StringVar(value="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
min_length = IntVar(value=4)
max_length = IntVar(value=6)
max_words_var = IntVar(value=1000)
output_file = StringVar()
all_variations = BooleanVar(value=False)


# GUI Layout
Label(root, text="Characters:").grid(row=0, column=0, sticky="e")
Entry(root, textvariable=characters, width=80).grid(row=0, column=1, padx=10, pady=5)


Label(root, text="Min Length:").grid(row=1, column=0, sticky="e")
Entry(root, textvariable=min_length, width=80).grid(row=1, column=1, padx=10, pady=5)


Label(root, text="Max Length:").grid(row=2, column=0, sticky="e")
Entry(root, textvariable=max_length, width=80).grid(row=2, column=1, padx=10, pady=5)


Label(root, text="Max Words:").grid(row=3, column=0, sticky="e")
Entry(root, textvariable=max_words_var, width=80).grid(row=3, column=1, padx=10, pady=5)


Label(root, text="Output File:").grid(row=4, column=0, sticky="e")
Entry(root, textvariable=output_file, width=80).grid(row=4, column=1, padx=10, pady=5)
Button(root, text="Browse", command=browse_output_file).grid(row=4, column=2, padx=10, pady=5)


Checkbutton(root, text="Generate All Variations", variable=all_variations).grid(row=5, column=0, columnspan=2, pady=5)


Button(root, text="Generate Wordlist", command=generate_wordlist_gui).grid(row=6, column=1, pady=10)


progress_bar = Progressbar(root, orient="horizontal", length=300, mode="determinate")
progress_bar.grid(row=7, column=0, columnspan=3, padx=10, pady=20)
Full Code

# Run the main loop
root.mainloop()

Example

I ran this code on Windows System as shown in the images below:

Also on Linux System:

Full Code

import os
from itertools import product
from tkinter import Tk, Label, Entry, Button, StringVar, IntVar, filedialog, messagebox, Checkbutton, BooleanVar
from tkinter.ttk import Progressbar
import threading




def generate_wordlist(chars, min_len, max_len, output_file, max_words, all_variations, progress):
   total_combinations = sum(len(chars) ** length for length in range(min_len, max_len + 1))
   word_count = 0
   step = 100 / total_combinations if all_variations else 100 / max_words


   with open(output_file, 'w') as file:
       for length in range(min_len, max_len + 1):
           for combo in product(chars, repeat=length):
               if not all_variations and word_count >= max_words:
                   messagebox.showinfo("Info", f"Reached the limit of {max_words} words.")
                   return
               word = ''.join(combo)
               file.write(word + '\n')
               word_count += 1
               progress.step(step)
               progress.update_idletasks()


   messagebox.showinfo("Success", f"Wordlist successfully created and saved to {output_file}")




def browse_output_file():
   filename = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text files", "*.txt")])
   output_file.set(filename)




def generate_wordlist_gui():
   chars = characters.get()
   try:
       min_len = int(min_length.get())
       max_len = int(max_length.get())
       max_words = int(max_words_var.get())
   except ValueError:
       messagebox.showerror("Input Error", "Lengths and max words must be integers.")
       return


   if not chars:
       messagebox.showerror("Input Error", "Characters set cannot be empty.")
       return


   if min_len > max_len:
       messagebox.showerror("Input Error", "Minimum length cannot be bigger than the Maximum length.")
       return


   output_filepath = output_file.get()
   if not output_filepath:
       messagebox.showerror("Input Error", "Output file path cannot be empty.")
       return


   if os.path.exists(output_filepath):
       overwrite = messagebox.askyesno("File Exists", f"File {output_filepath} already exists. Overwrite?")
       if not overwrite:
           return


   progress_bar['value'] = 0
   threading.Thread(target=generate_wordlist, args=(
   chars, min_len, max_len, output_filepath, max_words, all_variations.get(), progress_bar)).start()




# Set up the main window
root = Tk()
root.title("Wordlist Generator - The Pycodes")


# Variables
characters = StringVar(value="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
min_length = IntVar(value=4)
max_length = IntVar(value=6)
max_words_var = IntVar(value=1000)
output_file = StringVar()
all_variations = BooleanVar(value=False)


# GUI Layout
Label(root, text="Characters:").grid(row=0, column=0, sticky="e")
Entry(root, textvariable=characters, width=80).grid(row=0, column=1, padx=10, pady=5)


Label(root, text="Min Length:").grid(row=1, column=0, sticky="e")
Entry(root, textvariable=min_length, width=80).grid(row=1, column=1, padx=10, pady=5)


Label(root, text="Max Length:").grid(row=2, column=0, sticky="e")
Entry(root, textvariable=max_length, width=80).grid(row=2, column=1, padx=10, pady=5)


Label(root, text="Max Words:").grid(row=3, column=0, sticky="e")
Entry(root, textvariable=max_words_var, width=80).grid(row=3, column=1, padx=10, pady=5)


Label(root, text="Output File:").grid(row=4, column=0, sticky="e")
Entry(root, textvariable=output_file, width=80).grid(row=4, column=1, padx=10, pady=5)
Button(root, text="Browse", command=browse_output_file).grid(row=4, column=2, padx=10, pady=5)


Checkbutton(root, text="Generate All Variations", variable=all_variations).grid(row=5, column=0, columnspan=2, pady=5)


Button(root, text="Generate Wordlist", command=generate_wordlist_gui).grid(row=6, column=1, pady=10)


progress_bar = Progressbar(root, orient="horizontal", length=300, mode="determinate")
progress_bar.grid(row=7, column=0, columnspan=3, padx=10, pady=20)


# Run the main loop
root.mainloop()

Happy Coding!

Subscribe for Top Free Python Tutorials!

Receive the best directly.  Elevate Your Coding Journey!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
×