gpt4 book ai didi

python - 如何在此代码中添加函数 try/except?

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:53 24 4
gpt4 key购买 nike

我仍在创建这段代码,通过字典攻击我找到了一个由用户插入的密码。但是我会在文件源的输入中插入一些控件(例如,当我键入一个不存在的文件的源时)以及当我打开一个文件但里面没有与输入的密码匹配的单词时由用户。我的想法告诉我,我可以使用“If、Else、Elif”等指令,但其他程序员告诉我,我可以使用 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)

最佳答案

您可以将其作为“文件不存在”异常,在打开现有文件后,您可以使用 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)

关于python - 如何在此代码中添加函数 try/except?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41244446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com