Как сделать генератор случайных паролей в python
Перейти к содержимому

Как сделать генератор случайных паролей в python

  • автор:

Python Random Passwords

For the first item in our beginner series we’d like to talk about random password generating. This will allow us to see how to import modules, use functions, and generate some arguments for our script. All common things we’d like to use when creating then distributing the script to others and allow a fluid option in the script.

To begin, what we need:

  • random
  • string

We start by import the modules we need.

I want to build our code that will create our password into a function. To do so we define our function with def and then the name like so:

Next we need to create our password character string. The string module gives us the ability to get a collection of the letters, numbers and punctuation.

This variable puts all the possible characters we will use together in one variable. Next we will need to return our function for the final output.

We start with a blank string and join it with random.choice to choose our password characters for the length of our password defined by length. Lets add this variable to our function so we can pass this value along later dynamically in a way. At our randPass() function lets add length to the function like so:

Our full randPass.py script so far should look like so:

Now we just need to call our function outside of the def and we can get a random string which we can use for a password. By setting length=8 in our function we are giving it a default value. Now we can run our function like so

Adding some command line arguments

So what is all the code and what does this line mean?

If the script is called directly we will run some additional code and run our main process. For now we want to import argparse and setup some arguments. In doing so we’ll also need to update our main randPass() function.

With the addition of the arguments, we added command line arguments for length, numbers, alpha, punctuation, and how many passwords to create.

We will print some pretty lines to the console too

Next we need to handle the number of passwords the user wants.

Once completed we can now run our script in the console. With no arguments we will create a random string with 14 characters as in our default length argument and the characters would be all possible string options.

How to use the arguments

By default Argparse generates a great -h or help command.

With the arguments in the script we can create a password with the characters, numbers, punctuation, and the number of passwords to make.

Lets create 5 passwords with a length of 20 and use alpha characters and numbers.

Full source code is on our Github account

Categories: examples

Updated: April 28, 2020

Share on
You may also enjoy

Python Environments & Modules

By default when you install Python and install modules you are installing these globally so you can use those modules in any script located anywhere on the s.

Python Getting Started

So you want to start learning Python and developing programs and coding in general. There is no better time or place to start.

Upcoming action items

While being a moderator for the Facebook Group we see a lot of the same questions on repeat.

Welcome to Python Clan

less than 1 minute read

Welcome to the website made with Minimal Mistakes. I hope this is an easy way for us to make pages and posts related to our group as well.

Creating a Random Password Generator Using Python

I am just 5 days in to Dr. Angela Yu’s #100DaysOfCode python course. So far it’s been a great refresher for what I learned to pass Python Institute’s PCEP (Python Entry-Level Programmer) certification. Dr. Yu’s course is way more hands on and practical than the PCEP prep course I took and I highly recommend it for anyone looking to learn Python.

The final project for day 5 is a password generator which allows for practice with importing modules, using for loops, creating and editing lists, and randomization in Python.

In Angela’s example she creates the random password based on the following letters, numbers, and symbols lists and asks for input from the user for how many of each type they want in their password. Then the number of each character type is added to a new list (password_list) and shuffled:

While this works, I thought that this might not fulfill all of the minimum password requirements for many applications. So I decided to edit her random password generator to better fit what I find to be standard password requirements.

The standard requirements I have typically seen are:

  1. At least one upper case letter
  2. At least one lower case letter
  3. At least one symbol
  4. At least one number
  5. Password length requirements vary from app to app

It is possible that Angela’s password generator could omit either an uppercase or lowercase letter from the final password, which would not be a valid password for some websites or applications. It also requires the user to determine how many of each character type they want in the password to ensure that the password is at least the minimum required length. Some of my thoughts for how to improve the password generator are as follows:

Instead of asking the user to input how many of each character type they want the password to contain, I’d like the user to be prompted to input the minimum and maximum number of characters their password can be. Different websites/apps have different ranges for password length, so I figured it would be best to allow the user to provide that depending on which website/app they are creating the password for.

I set up the code so that at least one of each character type is included in the final password in order to fulfill the standard password requirements. After the 4 character types are included, the code will fill the rest of the password length with any random character. I thought this would help to randomize the password even further.

Now let’s get to the code.

First, I’ll update the lists so that the upper case and lower case letters are in separate lists.

Then I added a new list that combines all of the character types so that after one of each character type are included the rest of the password length will be populated randomly with any character type.

Then prompt the user for the password length.

Randomly select a password length between the min and max number of characters by setting a new variable.

Create a blank list to generate the password into.

Now that we have the list created, let’s populate the list with the characters of the password. First we’ll account for one random character from each character type.

Then we’ll add in random characters from each type to populate the remainder of the password using a for loop. The code will append a new random character from the all_keys list to the password list until the password list length is equal to the random password_length variable.

Once the for loop is complete, shuffle the password list to randomize it.

Concatenate the individual characters in the password list into a string with the join function. The single quotes before the join function is where to put a delimiter, which is a character to separate the fields in our list. In this case, we don’t want any delimiter because we want our password list to merge into one single password. In other cases, we could add a space or a comma if we wanted our list to print out with a space or character between each item in the list.

Finally, let’s print the password.

Below is an example of the password generator in action. The site we are creating a password for has a min password length of 8 characters and a max of 16. The password comes out to R9ZtKceb*ru#&Vqj which seems like a pretty strong password!

Thanks for reading how I updated Angela Yu’s random password generator. Let me know if you have any thoughts of how to improve it.

Как сделать генератор случайных паролей в python

In this article, we will see how to create a random password generator using Python.

Passwords are a means by which a user proves that they are authorized to use a device. It is important that passwords must be long and complex. It should contain at least more than ten characters with a combination of characters such as percent (%), commas(,), and parentheses, as well as lower-case and upper-case alphabets and numbers. Here we will create a random password using Python code.

Example of a weak password : password123

Example of a strong password : &gj5hj&*178a1

Modules needed

string – For accessing string constants. The ones we would need are –

    : ASCII is a system that is used to represent characters digitally, every ASCII character has its own unique code. string.ascii_letters is a string constant which contains all the letters in ASCII ranging from A to Z and a to z. Its value is non-locale dependent and it is just a concatenation of ascii_uppercase and ascii_lowercase. Thus it provides us the whole letter set as a string that can be used as desired. : This is a pre-initialized string that contains all the digits in the Arabic numeral system i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. It should be kept in mind that even though these are digits, the type is still a string constant, and all digits are concatenated like this – “0123456789”. If we want to access specific numbers then we can do so using slicing. : Apart from letters and digits, python also provides us all the special characters in a pre-initialized string constant. These include various kinds of braces, logical operators, comparison operators, arithmetical operators as well as punctuation marks like commas, inverted commas, periods, exclamations marks, and question marks. The whole string is – !”#$%&'()*+, -./:;<=>?@[\]^_`

random – The python random module helps a user to generate pseudo-random numbers. Inside the module, there are various functions that just depend on the function “random()”. This function generates a random float uniformly in the semi-open range [0.0, 1.0) i.e. it generates a decimal number greater than or equal to 0 and strictly less than one. Other functions use this number in their own ways. These functions can be used for bytes, integers, and sequences. for our task, we are interested in sequences. There are functions random. choices that take in a sequence as its argument and return a random element from that sequence.

Code Implementation:

First, take the length of the password as input. Then we can display a prompt about the possible list of characters that a user wants to include in the password –

Name already in use

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Created a random password generator in Python.

We know that passwords are a real security threat. To keep your account safe and prevent your password from being hacked you have to make your password hard enough that nobody can guess. The Password generator tool creates a random and customized password for users that helps them to create a strong password which provides greater security.

The objective of this project is to create a password generator using python. The password generator project will be build using python modules like Tkinter, random, string, pyperclip.

In this project, the user has to select the password length and then click on the “Generate Password” button. It will show the generated password below. If the user clicks on the “Copy To Clipboard” button, then it will copy the password automatically.

To build this project we will use the basic concept of python and libraries – Tkinter, pyperclip, random, string.

  • Tkinter is a standard GUI library and is one of the easiest ways to build a GUI application.
  • pyperclip module allows us to copy and paste text to and from the clipboard to your computer
  • The random module can generate random numbers
  • string module contains a number of functions to process the standard python string. To install the libraries we can use pip installer from the command line:

Steps to create random password generator

1. Import Libraries

The first step is to import libraries

2. Initialize Window

  • Tk() initialized tkinter which means window created
  • geometry() set the width and height of the window
  • resizable(0,0) set the fixed size of the window
  • title() set the title of the window

3. Select Password Length

  • pass_len is an integer type variable that stores the length of a password.
  • To select the password length we use Spinbox() widget.
  • Spinbox() widget is used to select from a fixed number of values. Here the value from 8 to 32

4. Function to Generate Password

  • pass_str is a string type variable that stores the generated password
  • password = “” is the empty string
  • First loop will generate a string of length 4 which is a combination of an uppercase letter, a lowercase letter, digits, and a special symbol and that string will store in password variable.
  • The second loop will generate a random string of length entered by the user – 4 and add to the password variable. Here we minus 4 to the length of the user because we already generate the string of length 4.

We have done this because we want a password which must contain an uppercase, a lowercase, a digit, and a special symbol.

Now the password is set to the pass_str() variable.

5. Function to Copy Password

pyperclip.copy() used to copy the text to clipboard

Python Password Generator Output

Capture

With these steps, we have successfully created a random password generator project using python. We used popular tkinter library to rendering graphics in our display window and we also learned about pyperclip and random library.

We learned how to create buttons, input textfield, labels, and spinbox. In this way, we successfully created our password generator python project. Hope you enjoyed it.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *