How can I add try / except functions in this code?

I am still creating this code where, through a dictionary attack, I find the password inserted by the user. However, I would introduce some controls into the input file of the source (for example, when I type the source of a file that does not exist), and when I open the file, but there is no word inside that matches the password entered by the user. My mind tells me that I can use istructions like "If, Else, Elif", but other programmers tell me that I can use try other than 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)
+4
source share
1 answer

" ", , , if, , - :

"""
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)
+2

Source: https://habr.com/ru/post/1664308/


All Articles