2016-12-20 5 views
4

나는 사전 공격을 통해 사용자가 삽입 한 암호를 찾는이 코드를 여전히 만들고 있습니다. 그러나 (예 : 존재하지 않는 파일의 원본을 입력 할 때) 파일 소스의 입력에 일부 컨트롤을 삽입하고 파일을 열었을 때 입력 한 암호와 일치하는 단어가없는 경우 사용자가 내 마음은 "If, Else, Elif"와 같은 구문을 사용할 수 있다고하지만 다른 프로그래머는 지침을 제외하고 try를 사용할 수 있다고 말합니다. 이 코드에서 try/except 함수를 어떻게 추가합니까?

코드입니다 :

""" 
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

코드를 포맷해야합니다. – MYGz

+0

그리고 실제 질문이 있습니까? 당신이 정말로 말하는 것은 "나는 X를하고 있지만, 어떤 사람들은 내가 Y를 대신 할 수 있다고 말하고있다." – twalberg

답변

2

당신은 당신의 "파일이 존재하지 않는"예외로 당신은 당신이 할 수있는 기존 파일을 열 아무것도하지만 파일 내부에 존재하는 경우 문을 확인하는 경우 이후에이를 넣을 수 있습니다 당신 방식으로 :

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