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.
All of the modules used in this code, are included with Python 2.7.5+.
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
Example of the run
>> python gen.py pIB4L#!E0muq8Wpx4XI#l4R6v
import random import string def generatePw(): pWcharList =  special = '!@#$' pWlen = 25 # 35 percent will be lowercase for x in range(int(pWlen * .35)): pWcharList.append(random.choice(string.ascii_lowercase)) # 35 percent will be uppercase for x in range(int(pWlen * .35)): pWcharList.append(random.choice(string.ascii_uppercase)) # 25 percent will be numbers for x in range(int(pWlen * .25)): pWcharList.append(random.choice(string.digits)) # Add the remaining length of the string with special characters for x in range(pWlen - len(pWcharList)): pWcharList.append(random.choice(special)) random.shuffle(pWcharList) newPw = ''.join(pWcharList) return newPw if __name__ == '__main__': print(generatePw())