Python Bruteforcing zip file cannot assign to function call - python

I am learning how to access a zip file with python BruteForcing. but I am facing a problem when I do that in the zipF in line 11
that is the exception: cannot assign to function call.
import zipfile
zipF = zipfile.ZipFile
zipName = input("File path : ")
passwordFile = open("14MillionPass.txt","r")
for passw in passwordFile.readlines():
ps = str(int(passw))
ps = ps.encode()
try:
with zipF.ZipFile(zipName) as myzip(): #the error is here
myzip.extractAll(pwd = ps)
print("Password found \n -> {0} is {1} password".format(ps,zipName))
break
except:
print("password not found")
Thanks in advance

You can't use a break inside a try-catch statement. also, you try to assign a function to the file handler. You can use exit(0) instead of break
try:
with zipfile.ZipFile(zipName) as myzip:
myzip.extractAll(pwd = ps)
print("Password found \n -> {0} is {1} password".format(ps,zipName))
exit(0) # successful exit
except:
print("password not found")
And you have broken indentation in your program, maybe this is want you want
import zipfile
zipName = input("File path : ")
passwordFile = open("14MillionPass.txt","r")
for passw in passwordFile.readlines():
ps = str(int(passw))
ps = ps.encode()
try:
with zipfile.ZipFile(zipName) as myzip:
myzip.extractAll(pwd = ps)
print("Password found \n -> {0} is {1} password".format(ps,zipName))
break
except:
print("password not found")

Related

using open() to read file and then using specific lines in if statement python

I'm working on a login system in python atm.
I got so far that I can register a user and create a .txt file with the username and password in two different lines.
textfile
But when it comes to the login system I've run into a problem. I can read the textfile, but when I'm using these two different lines in an if statement using:
try:
#usr is the username given in the login process by the user(the name of the
#created file is always the name of the user)
data = open(usr + ".txt", "r")
l = data.readlines()
#l[0] is reading the first line of code and the iam comparing
#them to the username and password given by the user
if l[0] == usr and l[1] == pss:
print('LOGED IN')
else:
print('WRONG')
except Exception as e:
print('Error reading file')
I am using the latest version of python and I am running on LinuxPopOs
my whole code:
import time
print("LOGIN -> 1")
print("Register -> 2")
print("")
select_ = input("")
if select_ == '2':
print("Username:")
usernamee = input()
print("Password:")
passworde = input()
print("Type ""y"" to register or ""n"" to cancel")
forward = input("")
if forward == 'y':
#creating database
data = open(usernamee + ".txt", "w")
data.write(usernamee + "\n")
data.write(passworde)
data.close()
else:
print('closing...')
time.sleep(2)
exit(0)
elif select_ == '1':
print("LOGIN:")
usr = input("Username:")
pss = input("Password:")
try:
#usr is the username given in the login process by the user
data = open(usr + ".txt", "r")
l = data.readlines()
#l[0] is reading the first line of code and the iam comparing
#them to the username and password given by the user
if l[0] == usr and l[1] == pss:
print('LOGED IN')
else:
print('WRONG')
except Exception as e:
print('Error reading file')
else:
print(select_ + "is not valid")
Thanks
The problem appears to be that white space and/or newline characters aren't being stripped from the strings read by readline. Changing the if statement to strip trailing characters should rectify that, e.g. if l[0].rstrip() == usr and l[1].rstrip() == pss:

Why my script doesn't print the found password? instead, it just keeps trying other passwords

I'm trying to code a zip password cracker in Python 3, I want the program to print "Found password: password" when it finds the password. My problem here is that it doesn't print "found password: password" when it hits the right password, it just keeps trying other words on the list "Trying Password: password"
from zipfile import ZipFile
import zipfile
import threading
import sys
filename = input("Enter File to crack: ")
wordlist = input("Enter wordlist: ")
def crackzip(filename, password):
try:
zipname.extractall(pwd=password)
print ('Found password: {}'.format(password.encode('utf-8')))
sys.exit(0)
except:
print ("Trying Password: {}".format(password))
def principio():
try:
zipname = zipfile.ZipFile(filename)
except zipfile.BadZipfile:
print ("File doesn't exist!")
except FileNotFoundError:
print ("No such file or directory")
try:
with open(wordlist, 'r') as f:
passlist = f.readlines()
except IOError:
print ("File NOT found!")
for passwords in passlist:
password = passwords.strip(b'\n')
t = threading.Thread(target=crackzip, args=(filename, password))
t.start()
if __name__ == "__main__":
principio()
Where is your zipname declared inside the crackzip function?
The try statement is always evaluating to an error like this.
import threading
import sys
filename = input("Enter File to crack: ")
wordlist = input("Enter wordlist: ")
def crackzip(zipname, password):
try:
zipname.extractall(pwd=password)
print ('Found password: {}'.format(password.encode('utf-8')))
sys.exit(0)
except:
print ("Trying Password: {}".format(password))
def principio():
try:
zipname = zipfile.ZipFile(filename)
except zipfile.BadZipfile:
print ("File doesn't exist!")
except FileNotFoundError:
print ("No such file or directory")
passlist = []
try:
with open(wordlist, 'r') as f:
passlist = f.readlines()
except IOError:
print ("File NOT found!")
for passwords in passlist:
password = passwords.strip(b'\n')
t = threading.Thread(target=crackzip, args=(zipname, password))
t.start()
if __name__ == "__main__":
principio()

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

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

Cannot stop program from crashing with wrong file entered by user

I am creating a program which asks the user to choose a file to run within the program but I can't stop the program from crashing when a file name that does not exist is entered. I have tried try statements and for loops but they have all given an error. The code I have for choosing the file is below:
data = []
print "Welcome to the program!"
chosen = raw_input("Please choose a file name to use with the program:")
for line in open(chosen):
our_data = line.split(",")
data.append(our_data)
Add an exception:
data = []
print "Welcome to the program!"
chosen = raw_input("Please choose a file name to use with the program:")
try:
for line in open(chosen):
our_data = line.split(",")
data.append(our_data)
except IOError:
print('File does not exist!')
Without using an exception you can simply check if the file exists and if not ask for it again.
import os.path
data = []
print "Welcome to the program!"
chosen='not-a-file'
while not os.path.isfile(chosen):
if chosen != 'not-a-file':
print("File does not exist!")
chosen = raw_input("Please choose a file name to use with the program:")
for line in open(chosen):
our_data = line.split(",")
data.append(our_data)
RTM
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise

Getting Unexpected EOF while parsing

trying to make a file that opens an existing text file and looks for a line number in that file. If the line number is not there I want it to print out a message that says that it is not in there.
This is what i have so far. And i am getting the Unexpected EOF error message. Where am I missing the problem?
# Get Input from user
file_name = input("Name of file to open please: ")
try:
in_file=open(file_name)
while True:
find_line = input("Which line number are you looking for? ")
try:
line_num=int(find_line)
line_count=1
for line_num in in_file:
if line_count== find_line:
print("Line number {} of the file {}, reads: {}".format(find_line,file_name,line_num))
break
line_count+=1
else:
print("Line number {} in file {} seems to be missing".format(find_line,file_name))
in_file.close()
in_file.open(file_name)
continue
break
except ValueError:
print("The Line Number you entered",find_line,"is not a correct line number")
in_file.close()
except IOError:
print ("Not sure how to break this to you, but the file your requested",file_str,"well, it's just not there")
print ("end of program")
That is to be expected. Your first try block doesn't have an except block.
try:
# Your code goes here
except:
print("Error")

Categories

Resources