Home » Create a Python Password Generator

Create a Python Password Generator

by maxguy71

In this code snippet we show you how easy it is to make a password generator using python. Here are a couple of rules

You should try to make sure your passwords are at least 12 characters long and contain letters, numbers, and special characters.
Some people prefer to generate passwords which are 14 or 20 characters in length.
Don’t use any personally identifiable information in your passwords – your name,family names, address, place you live etc
Avoid dictionary words for passwords

Hackers can use tools that can import a list of common dictionary words to then try and execute a dictionary attack. These password lists and dictionaries are freely available online as well as the tools to use them

So we are looking for the following

Generate a random string of a fixed length.
Generate a random string with lower case and upper case characters.
Generate a random alphanumeric string with letters and numbers.
Generate a random string password which contains letters, digits, and also special characters.

Code examples

import random
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^&*()?"
passlength = 16
password = "".join(random.sample(chars,passlength ))
print (password)

save this as passgen.py, open a command prompt and type in python passgen.py and you should see something like this. I ran this a couple of times


You could also prompt the user for the length of password they want rather than hard coding the value, lets see that example


import random

characters ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+}{"
length = int(input("Enter password length "))

for i in range(length+1):
password += random.choice(characters)

Here is another example which uses some built in modules in python

The default is 16 characters but in the code below you can see that you can set the length to other values


import random
import string

def randomPassword(stringLength=16):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))

print ("Random password is ", randomPassword() )
print ("Random password is ", randomPassword(14) )
print ("Random password is ", randomPassword(18) )

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More