Simple password generator in Python

There could be a situation when you need to create a password quickly, and do not want to bother too much about it. In this case password generators are very useful, but most of them require too many actions to do. In this article I am going to show how to create a simple utility that works from command line and just displays a line with the automatically generated password (and of course it can be used in many administrative automated tasks too).

First, I create a prototype in Python shell and then write the utility itself. I recommend to use IPython shell ( - it is superior to a standard Python shell in many ways. In the example below ipython3 (particularly, IPython 4.2.1 for Python 3.5.2) is used.
  1. Import 'random' module:
    In [1]: import random
  2. Check the generation of a random number in the required range (from 32 - space symbol to 126 - symbol '~'):
    In [2]: random.randrange(32, 126)
    Out [2]: 109
  3. Check the conversion a number to a character:
    In [3]: chr(random.randrange(32, 126))
    Out [3]: 'c'
  4. Check the generation of a list of characters:
    In [4]: [chr(random.randrange(32, 126)) for __ in range(8)]
    Out[4]: ['0', "'", 'A', '\\', 'o', 'D', 'R', 'M']
  5. Check joining a list to a string:
    In [5]: ''.join([chr(random.randrange(32, 126)) for __ in range(8)])
    Out[5]: 'mqLs2_ma'
That's all. Password generation is ready!
Now I put this code to a script and add one feature - the password generation with the specified length. For this I use 'argparse' module. The full script:

Now we put this script to the place where the OS can easily find it (for example, ~/bin) and voilà - we've got the password generator at a fingertip.


Popular posts from this blog

DIY: Business cards in LaTeX

Python vs JS vs PHP for embedded systems

Shellcode detection using libemu