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
Password:
L3o2zOV5vzHqM
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

#!/usr/bin/python

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

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


import random

PASSWORD_LENGTH = 14
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()
    else:
        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
qE@hw7vzWvsmmu
boby@hon-pc-01:~ $

Install from GitHub

mkdir ~/bin && cd ~/bin && wget https://github.com/HostOnNet/pwgen/raw/master/pwgen && chmod 755 pwgen

Source code available at

https://github.com/HostOnNet/pwgen

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.