HostOnNet Blog

Secure Password Generator in Python

Looking for Linux Server Admin or WordPress Expert? We can help.

On ubuntu, i was using mkpasswd tool to generate password. It did generate secure passwords. But many sites require more secure password with number and special chars.

boby@hon-pc-01:~ $ mkpasswd
boby@hon-pc-01:~ $

I created a python program, so we it can be run on any Ubuntu PC (we use Ubuntu on desktop) with out installing any programs as python is is part of almost all linux distros.

Create a file

vi ~/bin/pwgen

With following code


"""pwgen: Generate secure password."""

__author__      = ""
__email__       = "[email protected]"
__copyright__   = "Copyright 2016,"

import random

password_chars = "abcdefghjkmnpqrstuvwxyz"

def update_password(password, char):
    replace_index = random.randrange(len(password))
    if (replace_index == 0):
        replace_index = 1;
    return password[0:replace_index] + str(char) + password[replace_index+1:]

my_password = ""

for i in range(PASSWORD_LENGTH):
    next_index = random.randrange(len(password_chars))
    if (random.randrange(10) > 5):
        my_password = my_password + password_chars[next_index].upper()
        my_password = my_password + password_chars[next_index]

my_password = update_password(my_password, "@")
my_password = update_password(my_password, random.randrange(0,9))

print my_password

Save the file. Now you need to make the file executable

chmod 755 ~/bin/pwgen

If you have no bin directory, you need to create it in your home folder. First time, you need a reboot, then only Ubuntu add bin folder to PATH.

Now to generate secure password, run

boby@hon-pc-01:~ $ pwgen
boby@hon-pc-01:~ $

Install from GitHub

mkdir ~/bin && cd ~/bin && wget && chmod 755 pwgen

Source code available at

Posted in Python

Leave a Reply

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

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