How can i add the functions try/except in this code?

90 views Asked by At

I'm still creating this code where via a dictionary attack i find a password, inserted by the user. However I would insert some controls in the input of the file's source (ex. when I type the source of a file that doesn't exist) and when I open a file but inside there isn't a word that match with the password typed by the user. My mind tell me that I can use istructions as "If, Else, Elif" but other programmers tell me that i could use the try except instructions.

This is the code:

"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.

"""


def dictionary_attack(pass_to_be_hacked, source_file):

    try:


        txt_file = open(source_file , "r")

        for line in txt_file:

            new_line = line.strip('\n')


            if new_line == pass_to_be_hacked:

                print "\nThe password that you typed is : " + new_line + "\n"

    except(







print "Please, type a password: "

password_target = raw_input()


print "\nGood, now type the source of the file containing the words used for the attack: "

source_file = raw_input("\n")


dictionary_attack(password_target, source_file)
1

There are 1 answers

0
Taufiq Rahman On

You can put this as your "File does not exist" exception and after you open the existing file you can but an if statement to check if anything exist inside the file in your way:

"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.

"""
def dictionary_attack(pass_to_be_hacked, source_file):
    try:
        txt_file = open(source_file , "r")
        if os.stat( txt_file).st_size > 0: #check if file is empty
            for line in txt_file:
                new_line = line.strip('\n')
                if new_line == pass_to_be_hacked:
                    print("\nThe password that you typed is : " + new_line + "\n")
        else:
            print "Empty file!"

    except IOError:
        print "Error: File not found!"

print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)