Python Password Prigram - python

I am creating a password program for my programming class, the requirements are:
8 Characters/1 letter/1 Digit/Alphanumeric only
The problem is the .isalpha or .isdigit cancel each other out because they require all of the string to be letters or numbers.
Is there anyways I can make it check if atleast 1 character is a number or letter
###############################
# PROLOG SECTION
# new_password.py
# Program to check a user's proposed
# password.
# (today's date goes here)
# (programmer names go here)
# (tester names go here)
# Possible future enhancements:
# Unresolved bugs:
###############################
###############################
# PROCESSING INITIALIZATION SECTION
###############################
# code goes here
minlength = 8
valid = False
###############################
# PROCESSING SECTION
# Branching code:
# Looping code:
###############################
# code goes here
# get the user input
password = str(input("Type in your password: "))
# test the password length
if len(password) >= minlength:
# test for all alphanumeric
if password.isalnum():
if password.isalpha():
if password.isdigit():
# if the password meets BOTH conditions, set valid to true
valid = True
else:
#otherwise, give the user a meaningful error message
print("Error, password does not contain a number.")
else:
#otherwise, give the user a meaningful error message
print("Error, password does not contain a letter.")
else:
# otherwise, give the user a meaningful error message
print("Error, password is not alphanumeric.")
else:
# otherwise, give the user a meaningful error message
print("Error, password is less than",minlength,"characters.")
###############################
# CLEANUP, TERMINATION, and EXIT
# SECTION
###############################
# code goes here
# print informational messages
# if the password meets the condition (at least 8 characters)
if valid == True:
# print the "successful" message
print("Your new password is valid.")
else:
# otherwise, print the "unsuccessful" message
print("Your new password is not valid.")

Use any():
valid = any(c.isalpha() for c in password) and any(c.isdigit() for c in password)
This will satisfy the requirement that there is at least 1 alpha character and 1 digit. Combine that with password.isalnum() and the length check and you should be able to vet your passwords.

There are several (innumerable?) ways to accomplish this.
Looking at the code you have, you've taken care of testing the length and making sure you have only alphanumeric characters. So consider some candidate password which has cleared these two hurdles. You want to let through any candidate that contains at least one letter and at least one digit.
So figure out what you want to stop (there are basically two 'bad' cases), and how you could identify these with .isalpha and .isdigit. (i.e. once you know what the 'bad' candidates look like, what would they give you for each of those methods?)

Use Regex. OR
If you only want to check if at least 1 char is number or a letter. Then use this:
#To check for at least 1 digit
>>> str="yogi123yogi"
>>> [chr.isdigit() for chr in str]
[False, False, False, False, True, True, True, False, False, False, False]
any() comes in handy here:
>>> any([chr.isalpha() for chr in str])
True
Similarly check of 1 alphabet also:
>>> any([chr.isalpha() for chr in str])
True
Note: Well you can process the above information from isdigit() and isalpha to figure out the total count and match with the password length.
Total num of digits + Total num of alphabets == Password Length
Else don't accept the password.

Related

BRUTE FORCE password hacker- How to add a minimum length to the brute force guesses?

I am trying to write code for an ethical hacking challenge. So far I have the following (see below). To speed it up I would like to set a minimum password length that it guesses based on the idea the hacker could seek the information from the website. How do I add this? I have made a start but I'm lost as to how to put it in the while guess function.
I have limited the characters it the code is working with whilst trialing aspects to speed it up.
import random
character = "0123456789abcdefgABCDEFG!?£#" #option to add capital letters and special characters ##only partial use of characters available to allow for speed when testing
character_list = list(character)
#website_pwd_length = "xxxx"
#min_length = len(website_pwd_length)
password= input('Enter password (Must contain 4 or more characters): ')
hack = ''
attempts = 0
while (hack != password):
hack = random.choices(character_list,k=len(password))
attempts += 1
hack = "".join(hack)
print("Success! The password is {}. \nThis was found in {} attempts.".format(hack, attempts))
I have commented out some of my initial attempts at establishing the length variable
To add a minimum password length to your password guessing program, you can modify the while loop to only generate passwords that are at least a certain length. Here's one way to do it:
import random
# Define the characters that can be used in the password
character = "0123456789abcdefgABCDEFG!?£#"
character_list = list(character)
# Get the target password from the user
password = input('Enter password (must contain 4 or more characters): ')
# Define the minimum password length
min_length = 6
# Keep generating passwords until the correct one is found
hack = ''
attempts = 0
while (hack != password):
# Generate a new password of at least min_length characters
hack = random.choices(character_list, k=random.randint(min_length, len(password)))
attempts += 1
hack = "".join(hack)
print("Success! The password is {}. \nThis was found in {} attempts.".format(hack, attempts))
In this modified code, we've added a min_length variable that specifies the minimum length of the generated passwords. Inside the while loop, we generate a new password by choosing characters at random from character_list using the random.choices() function, and we use random.randint() to determine the length of the password (which is at least min_length but no longer than the length of the target password password).
With this modification, the program will only generate passwords that meet the minimum length requirement, which should speed up the password guessing process. Feel free to adjust the min_length value to suit your needs.

While loop never meets condition

So, for context I am trying to write a script that checks a text input fulfils all of the necessary requirements for a username.
However, the section I wrote to repeat the function if the conditions are not met always repeats after the first attempt even if the conditions are met. The first attempt works as intended.
This is the section that uses a list of conditions not met to establish whether or not to repeat the function, however even when the username is correct it repeats if after the first attempt.
if error_stack != []:
repeat = True
else:
repeat = False
return repeat
repeat = username_input(input("Please enter a username with only numbers and letters, which is above 2 characters and below 15 characters. If the username is taken you will be asked to pick a new one. \n|:"))
print(repeat) #please help its always true.....
while repeat == True:
repeat = username_input(input("Please enter a username with only numbers and letters, which is above 2 characters and below 15 characters. If the username is taken you will be asked to pick a new one. \n|:"))
print(repeat) #please help its always true.....
if __name__ == "__main__":
main()
In this screenshot I input 1 username which should result in the control var being set to True and the loop repeating, then I input 1 username which should result in the control var being set to False and the loop not repeating.
2 inputs 1 works other doesnt
In this screenshot I input 1 user name which should result in the control var being set to False and the loop not repeating. It then works as intended.
1 input works
Can someone please explain to me why the condition only functions as it should (as far as I'm aware it should check if the condition is met every time the loop ends after the first time) the first time, then after refuses to exit?
Edit: Full code of section
import os
STANDARD_CHARS = list("abcdefghijklmnopqrstuvwxyz1234567890 ")
ERROR_DICT = {
"NonStandardCharacterError":"Your username should only have letters and numbers in it, please pick another.",
"CurrentUserError":"Your username has already been taken, please pick another.",
"LengthError":"Your username should be more than 2 characters in length, and fewer than 15 characters in length, please pick another.",
}
def main():
printed_errors = []
error_stack = []
current_users = []
def username_input(word_input):
for char in list(word_input.lower()):
if char not in STANDARD_CHARS:
error_stack.append("NonStandardCharacterError")
if word_input.lower() in current_users:
error_stack.append("CurrentUserError")
if len(word_input) > 15 or len(word_input) < 3:
error_stack.append("LengthError")
for error in error_stack:
try:
if error not in printed_errors:
print(ERROR_DICT[error])
printed_errors.append(error)
except KeyError:
print("Your username has thrown an unknown error , please try again later or pick another username.")
if error_stack != []:
repeat = True
else:
repeat = False
return repeat
repeat = username_input(input("Please enter a username with only numbers and letters, which is above 2 characters and below 15 characters. If the username is taken you will be asked to pick a new one. \n|:"))
print(repeat)
while repeat == True:
repeat = username_input(input("Please enter a username with only numbers and letters, which is above 2 characters and below 15 characters. If the username is taken you will be asked to pick a new one. \n|:"))
print(repeat)
if __name__ == "__main__":
main()
You initialize error_stack to [] in main, and append to it in username_input. But after its initial creation, you never reset it back to the empty list. So error_stack grows and grows, retaining old errors even when the user enters valid input.
Try creating error_stack inside username_input instead of inside main. Then it will be set to the empty list for every new user input prompt.
def main():
printed_errors = []
current_users = []
def username_input(word_input):
error_stack = []
for char in list(word_input.lower()):
#...
If, for some reason, it is necessary to keep error_stack in the higher scope, you can instead clear it with the clear method.
def main():
printed_errors = []
error_stack = []
current_users = []
def username_input(word_input):
error_stack.clear()
for char in list(word_input.lower()):
#...

Program in Python that will prompt the user to enter an account number consists of 7 digits?

I'm taking an intro Python course and a little stuck on an assignment. Any advice or resources would be greatly appreciated!
Here's the problem:
Write a program in Python that will prompt the user to enter an account number consists of 7 digits.
After getting that account number from user, verify if the account is valid or not. You should have a list called current_accts that hold all valid accounts.
Current valid accounts are shown below and you must use them in your program.
5679034 8232322 2134988 6541234 3984591 1298345 7849123 8723217
Verifying the account number entered should be done in a function called check_account() that will accept the account entered by the user and also the list current_accts. This function should return a 1 if account is valid otherwise return 0 if account is not valid.
Here's what I've written so far, but I'm stuck and also receiving syntax errors for indentation in lines 6-15. I'm also receiving error messages saying that variable 'current_accts' is not defined.
prompt = "Please, enter the 8 digit account number: "
current_accts = current_accts[1:]
current_accts [-1] = "valid"
while True:
try:
userinput = current_accts(prompt)
if len(userinput ) > 8:
raise ValueError()
userinput = int(userinput)
except ValueError:
print('The value must be an 8 digit integer. Try again')
else:
break
userinput = str(userinput)
a =int(userinput[7])+int(userinput[5])+int(userinput[3])+int(userinput[1])
b1 = str(int(userinput[6])*20)
b2 = str(int(userinput[4])*20)
b3 = str(int(userinput[2])*20)
b4 = str(int(userinput[0])*20)
y = int(b1[0])+int(b1[1])+int(b2[0])+int(b2[1])+int(b3[0])+int(b3[1])+int(b4[0])+int(b4[1])
x = (a+y)
if x % 10 == 0:
print('The account number you entered is valid!')
else:
print('The account number you entered is invalid!')
NOTE: If you are looking for cooked up code then please do not read the answer.
I can tell you the logic, I guess you are doing that wrong.
Logic:
Check whether the account number is 7 digit or not.
if condition 1 is true then Check if it is in the list of given accounts or not.
You can check condition 1 by checking is the condition 1000000<= user_input <10000000.
You can check the condition 2 by looping through the list.
You really have to go back and learn some of the basic syntax of python, because there are many problems with your code. Just google for python tutorials, or google specific issues, like how to get a user's input in python.
Anyway, I don't mean to insult, just to teach, so here's my solution to your problem (normally i wouldn't solve all of it, but clearly you made some effort):
current_accts = ['5679034', '8232322', '2134988', '6541234', '3984591', '1298345', '7849123', '8723217']
user_input = input("Please, enter the 7 digit account number: ")
if user_input in current_accts:
print('The account number you entered is valid!')
else:
print('The account number you entered is invalid!')
I didn't place it in a function that returns 0 or 1 like your question demanded, I suggest you adapt this code to make that happen yourself

Taking Mutiple line input in python using basic python

I am trying to solve some problems in CodeAbbey using Python.I have run into a wall trying to take input for these programs.I have spent so much time analyzing how to take the input data without even solving the question.Hope someone explains how to take input.
Problem:I have to input the following numbers in One go. I have tried using 'input()' but it takes only one line. Is there any work around to do it in a simple way? i wasted so much time trying to analyse various options
632765 235464
985085 255238
621913 476248
312397 751031
894568 239825
702556 754421
474681 144592
You can find the exact question here: http://www.codeabbey.com/index/task_view/sums-in-loop
You can just repeat input() until you get all your data, e.g.:
try:
input = raw_input # fix for Python 2.x compatibility
except NameError:
pass
def input_pairs(count):
pairs = [] # list to populate with user input
print("Please input {} number pairs separated by space on each new line:".format(count))
while count > 0: # repeat until we get the `count` number of pairs
success = True # marks if the input was successful or not
try:
candidate = input() # get the input from user
if candidate: # if there was some input...
# split the input by whitespace (default for `split()`) and convert
# the pairs to integers. If you need floats you can use float(x) instead
current_pair = [int(x) for x in candidate.split()]
if len(current_pair) == 2: # if the input is a valid pair
pairs.append(current_pair) # add the pair to our `pairs` list
else:
success = False # input wasn't a pair, mark it as unsuccessful
else:
success = False # there wasn't any input, mark it as unsuccessful
except (EOFError, ValueError, TypeError): # if any of the conversions above fail
success = False # mark the input as unsuccessful
if success: # if the input was successful...
count -= 1 # reduce the count of inputs by one
else: # otherwise...
print("Invalid input, try again.") # print error
return pairs # return our populated list of pairs
Then you can call it whenever you need number pairs like:
my_pairs = input_pairs(7) # gets you a list of pairs (lists) entered by user
My first attempt would be to try a typing like "632765 235464\n985085 255238[...]" so you could read it as one line. This would be pretty hacky and not a good idea if its real userinput.
The other idea: Why not taking the input line by line and putting these lines in a list / appending them to a string?
EDIT:
I found some Code on SO, but its python2.7 i guess. ->Here
The Python3.X style would be:
#!/usr/bin/python
input_list = []
while True: # Infinite loop, left by userinput
input_str = input(">") #The beginning of each line.
if input_str == ".": #Userinput ends with the . as input
break # Leave the infinite loop
else:
input_list.append(input_str) #userinput added to list
for line in input_list: #print the input to stdout
print(line)
Hope this will help :)

Python if statement: less than

Ok, can someone tell me how to make an if else statement with a character limit
i wrote a quick code to make you see what am trying to tell you
pass1 = input("What is you'r password: ")
pass2 = input("Rewrite you'r password: ")
what i tried:
if pass1 == <5:
print ("password is greater than 5")
else:
print ("password is lower than 5")
basically am trying to make a limit like in real website when you register (when you register there's a character limit example it cant be lower than 5 characters).
You need to test the length of the string with len function:
if len(pass1) < 5:
Perhaps you may have some confusion also with if statements and arithmetic operators. Check them here:
Control Flow
Comparissons

Categories

Resources