Python Generate Secure Password


How to come up with a randomly generated password or key is a common problem or challenge when programming, or just in security. On top of just randomly generating a password, there are some custom criteria pieces that are also challenges:

  • Password Length
  • Certain number of uppercase letters
  • Certain number of lowercase letters
  • Certain number of numbers
  • Certain number of special characters
  • Finally, a restriction to only a fixed set of special characters. Some special characters can be very unfriendly to different operation systems or platforms.
    • For example, on Cisco IOS or NXOS, you cannot easily use a question mark as it will signal the OS to display the current help.

Required Modules

All of the modules used in this code, are included with Python 2.7.5+.

  • random
  • string

What the Code Does

By default the code will:

  • Generate a password length of 25 Characters
  • 35% of that password length will be lowercase
  • 35% of that password length will be uppercase
  • 25% of the password length will be numbers
  • to make the password the full length of 25 characters, it will add the special characters !@#$ randomly until the length is 25
  • the code will then randomly shuffle the 25 characters
    • random.shuffle(pWcharList)

Example of the run

>> python 

The Code

import random
import string

def generatePw():
    pWcharList = []
    special = '!@#$'
    pWlen = 25
    # 35 percent will be lowercase
    for x in range(int(pWlen * .35)):
    # 35 percent will be uppercase
    for x in range(int(pWlen * .35)):
    # 25 percent will be numbers
    for x in range(int(pWlen * .25)):
    # Add the remaining length of the string with special characters
    for x in range(pWlen - len(pWcharList)):

    newPw = ''.join(pWcharList)
    return newPw

if __name__ == '__main__':

About Daniel Fredrick

Technology enthusiast, Programmer, Network Engineer CCIE# 17094

View all posts by Daniel Fredrick →

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.