Zip file cracker python 3 - Proof of concept - python

How would i expand upon my existing function in order to get it to try the password on a locked zip file
chars = "abcdefghijklmnopqrstuvwxyz"
password = "hello"
def brute_force(x, y):
#Where x stands for chars(list to check in) and y stands for password variable to check against
for length in range(1, 100):
to_attempt = product(x, repeat=length)
for attempt in to_attempt:
i = i + 1
if ''.join(attempt) == y:
print('Password: ' + ''.join(attempt))
return

I won't completely re-write your function for you, but to test each attempt you would do (import zipfile at the top):
f = zipfile.ZipFile('path/to/file')
for attempt in attempts:
try:
f.extractall(pwd=attempt)
except RuntimeError:
continue
else:
return attempt

def brute_force(x, y):
#since you already have the password just return it
return y
ok ok that probably wasnt the answer you are looking for ...
but really the only way I know of(assuming you dont know an exploit to decode whatever encryption this might be) is to brute force it...
of coarse many systems have vunerabilities you can exploit to gain access without necessarilly "guessing " the password
if you are asking how can you not include y and instead test it against a real file try the zipfile module , which includes a password option for most methods

using zipfile module
import zipfile
z = zipfile.Zipfile('your_zip_file')
def searching(z,x):
try:
z.extractall(pwd=x)
print "\n[+]Password found: " + x
exit
except:
pass
# loop over you combination call searching
searching(z,pwd)
This might will help you. you can use concept of threading to make it faster

Related

How to import external python file to another python file?

I would like to import one python file into another and then compile the main file. How can I do this?
MWE: Suppose I would like to calculate factorial of a positive integer. It can be done successfully by the following way:
n=5
fact = 1
if n < 0:
print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,n + 1):
fact = fact*i
print "%d!=%d"%(n,fact)
But I would like to create a secondary file say "auxfile.py" containing:
fact = 1
if n < 0:
print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,n + 1):
fact = fact*i
print "%d!=%d"%(n,fact)
And another main file say "main.py" containing:
print "Required factorial is given below:"
for n in range(30):
import auxfile.py
How can I do this?
Note: I know defining a function the whole process can be done in a single file. But I have to do a large program where I would like to apply this process.
Simple, just use the import method. To make your life easier simply copy the .py file you would like to import to the same folder that the file you want to import the other code file into is in.
E.g if you wanted to import happy.py to sad.py simply do:
import happy
This would give the following traceback (look at example below):
Hello
Although, this will instantly run everything outside of any def loops in the .py file. Therefore, if you wanted to run a single def loop in the file, then use the following code:
Example contents of happy.py:
print("Hello")
def okay():
print("okay")
If you did:
happy.okay()
This would give you the following traceback:
Hello
okay
TIP FOR YOUR CODE IN MAIN.PY:
You did:
print "Required factorial is given below:"
whereas you forgot the brackets. You should use: print("Required factorial is given below:") This will avoid future errors!
Hope this helps!
you can do it like this:
auxfile.py
def factorial(n):
fact = 1
if n < 0:
print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,n + 1):
fact = fact*i
print "%d!=%d"%(n,fact)
in your main.py :
from auxfile import factorial
print "Required factorial is given below:"
for n in range(30):
factorial(n)
If you're trying to avoid using a function--maybe you could wrap your entire code in the for loop? If it is not as simple as a for-loop, maybe you could copy your main code into the other file above it.
For example:
Before:
file1: "Your main code that wants to call the code below"
file2: "Your code that is too cumbersome to convert to a function"
After:
file1:
"Your main code that wants to call the code below"
for n in range(30):
"Your code that is too cumbersome to convert to a function"
There's still quite an ugly solution, which is to use the exec built-in function.
First of all, you read the code from your file:
with open("auxiliary.py", 'r') as f:
content = f.readlines()
Then you filter out the lines you don't want, so that content is a string containing your Python code, that is:
# The following evaluates to True
content == 'fact = 1\nif n < 0:\n print("Sorry, factorial does not exist for negative numbers")\nelif n == 0:\n print("The factorial of 0 is 1")\nelse:\n for i in range(1,n + 1):\n fact = fact*i\n print "%d!=%d"%(n,fact)'
Then you can just call the exec function, which will act as if the lines were included in lieu of the call of the function:
exec content # Or exec(content), both seems to work in Python 2.7
See here for a further explanation.
Note that you will have access to fact and every other variables, just as if you had written these lines in your main file.
Be aware that this might get dangerous: if you don't formally identify which lines to execute (like, put a comment as an identifier, or if the auxiliary file never changes), you may end up running some code from your auxiliary file you dont want to.

Self Limiting Repition Function

I'm writing a program that is basically a study guide/ practice test for the current section of my A&P class (it keeps me more engaged than just rereading notes over and over). The test works without any problems, but I have an issue where some of my questions use an "enterbox" input, I can have the question loop if the answer is incorrect, but I can't get it to break without a correct answer.
I figured out a way to make it work by putting the entire function back into the initial "else" tree, so that right or wrong you advance to the next question but it looks incredibly ugly and I can't believe there isn't a better way.
So my "solution" looks like such:
def question82():
x = "which type of metabolism provides the maximum amount of ATP needed for contraction?"
ques82 = enterbox(msg = x, title = version)
#version is a variable defined earlier
if ques82.lower() in ["aerobic"]:
add() #a function that is explained in the example further below
question83()
else:
loss() #again its a housecleaning function shown below
ques82b = enterbox(msg = x, title = version)
if ques82b.lower() in ["aerobic"]:
add()
question83()
else:
loss()
question83()
Okay so it worked, but using a nested if tree for each "enterbox" question looks kinda sloppy. I'm self taught so it may be the only solution but if there is something better I would love to learn about it.
So here is a complete section from my program:
from easygui import *
import sys
version = 'A&P EXAM 3 REVIEW'
points = 0
def add():
global points
msgbox("Correct", title = version)
points = points + 1
def loss():
global points
msgbox("Try Again", title = version)
points = points - 1
def question81():
x = "What chemical is stored by muscle as a source of readily available energy for muscle contractions"
ques81 = enterbox(msg = x, title = version)
if ques81.lower() in ["creatine"]:
add()
question82()
else:
loss()
question81()
It works as is so any errors from what's provided are probably my fault from copy and pasting.
Also I'm running it in python 2.7rc1 if that helps.
Thanks for any help in advance.
I don't know if there is a way to combine "enterbox" that has a button for "skip" as that would also be a solution.
Consider the following approach:
We define a list of question and answer pairs. We do this in one place so it's easy to maintain and we don't have to search all over the file to make changes or re-use this code for a different questionset.
We create an ask_question function that we can call for all of our questions. This way, if we want to make a change about how we implement our question logic, we only have to make it in one spot (and not in each of the questionXX functions).
We compare user input to our answer using == and not in (in will do something else, not what you expect).
We create an object to keep track of our answer results. Here, it's an instance of ResultsStore, but it can be anything really, let's just try to get away from global variables.
Use a loop when prompting for answers. The loop will repeat if the answer given was incorrect (and if retry_on_fail is False).
Allow for the user to enter some "skip" keyword to skip the question.
Display the results once the "test" is complete. Here, we do that by defining and calling the store.display_results() method.
So, what about:
from easygui import enterbox
question_answer_pairs = [
("1 + 1 = ?", "2"),
("2 * 3 = ?", "6"),
("which type of metabolism provides the maximum amount of ATP needed for contraction?", "aerobic")
]
VERSION = 'A&P EXAM 3 REVIEW'
class ResultStore:
def __init__(self):
self.num_correct = 0
self.num_skipped = 0
self.num_wrong = 0
def show_results(self):
print("Results:")
print(" Correct:", self.num_correct)
print(" Skipped:", self.num_skipped)
print(" Wrong: ", self.num_wrong)
def ask_question(q, a, rs, retry_on_fail=True):
while True:
resp = enterbox(msg=q, title=VERSION)
# Force resp to be a string if nothing is entered (so .lower() doesn't throw)
if resp is None: resp = ''
if resp.lower() == a.lower():
rs.num_correct += 1
return True
if resp.lower() == "skip":
rs.num_skipped += 1
return None
# If we get here, we haven't returned (so the answer was neither correct nor
# "skip"). Increment num_wrong and check whether we should repeat.
rs.num_wrong += 1
if retry_on_fail is False:
return False
# Create a ResultsStore object to keep track of how we did
store = ResultStore()
# Ask questions
for (q,a) in question_answer_pairs:
ask_question(q, a, store)
# Display results (calling the .show_results() method on the ResultsStore object)
store.show_results()
Now, the return value currently doesn't do anything, but it could!
RES_MAP = {
True: "Correct!",
None: "(skipped)",
False: "Incorrect" # Will only be shown if retry_on_fail is False
}
for (q,a) in question_answer_pairs:
res = ask_question(q, a, store)
print(RES_MAP[res])
Quick and dirty solution could be using the default value "skip" for the answer:
def question81():
x = "What chemical is stored by muscle as a source of readily available energy for muscle contractions"
ques81 = enterbox(msg = x, title = version, default = "skip")
if ques81.lower() == 'creatine':
add()
question82()
elif ques81 == 'skip':
# Do something
else:
loss()
question81()
But you should really study the answer given by jedwards. There's a lot to learn about
program design. He's not giving you the fish, he's teaching you to fish.

Caesar substituion -function not returning results

I have the following python code which is supposed to use brute force to decrypt secret message. The encryption technique is Ceasarean subsitution i.e. every letter in the alphabet is moved by a certain number of places. My main function is supposed to return the decrypted message with the letters moved by all 26 possible number of places (I hope it makes sense but its basically like ROT13 but we don't know the number. It could be ROT13, ROT5, ROT20 etc.)
The problem is my main function doesn't print out the result from the caesarBreak function.
Thanks in advance!
import sys
def caesarBreak(cipheredMsg):
alphabet = "abcdefghijklmnopqrstuvwxyz "
shift = 1
plainText = ""
for ch in cipheredMsg:
idx = alphabet.find(ch) - shift
plainText = plainText + alphabet[idx]
shift = shift + 1
return plainText
def main():
print("We will now try to break the msg: 'we ovugpzghugpu lylz pungwyvnyhttpungshunahnl'\n\n")
secretmsg = 'we ovugpzghugpu lylz pungwyvnyhttpungshunahnl'
caesarBreak(secretmsg)
main()
Because you didn't ask your main function to print it.
print(caesarBreak(secretmsg))
it did return the result, if you find a place to store it then later you could print it out or do whatever you want with it.
result = caesarBreak(secretmsg)
print(result)
Agree with Yunkai Xiao, you have to use print() to print out your result.
print(#your function here)
Also, there might be other error for you to check just a fyi.

Python - how do i save a itertools.product loop and resume where it left off

I am writing a python script to basically check every possible url and log it if it responds to a request.
I found a post on StackOverflow that suggested a method of generating the strings for the urls which works well.
for n in range(1, 4 + 1):
for comb in product(chars, repeat=n):
url = ("http://" + ''.join(comb) + ".com")
currentUrl = url
checkUrl(url)
As you can imagine there is way to many urls and it is going to take a very long time so I am trying to make a way to save my script and resume from were it left off.
My question is how can I have the loop start from a specific place, or does anyone have a working piece of code that does the same thing and will allow me to specify at starting point.
This is my script soo far..
import urllib.request
from string import digits, ascii_uppercase, ascii_lowercase
from itertools import product
goodUrls = "Valid_urls.txt"
saveFile = "save.txt"
currentUrl = ''
def checkUrl(url):
print("Trying - "+url)
try:
urllib.request.urlopen(url)
except Exception as e:
None
else:
log = open(goodUrls, 'a')
log.write(url + '\n')
chars = digits + ascii_lowercase
try:
while True:
for n in range(1, 4 + 1):
for comb in product(chars, repeat=n):
url = ("http://" + ''.join(comb) + ".com")
currentUrl = url
checkUrl(url)
except KeyboardInterrupt:
print("Saving and Exiting")
open(saveFile,'w').write(currentUrl)
The return value of itertools.product is a generator object. As such all you'll have to do is:
products = product(...)
for foo in products:
if bar(foo):
spam(foo)
break
# other stuff
for foo in products:
# starts where you left off.
In your case the time taken to iterate through the possibilities is pretty small, at least compared to the time it'll take to make all those network requests. You could either save all the possibilities to disk and dump a list of what's left after every run of the program, or you could just save which number you're on. Since product has deterministic output, that should do it.
try:
with open("progress.txt") as f:
first_up = int(f.read().strip())
except FileNotFoundError:
first_up = 0
try:
for i, foo in enumerate(products):
if i <= first_up:
continue # skip this iteration
# do stuff down here
except KeyboardInterrupt:
# this is really rude to do, by the by....
print("Saving and exiting"
with open("progress.txt", "w") as f:
f.write(str(i))
If there's some reason you need a human-readable "progress" file, you can save your last password as you did above and do:
for foo in itertools.dropwhile(products, lambda p != saved_password):
# do stuff
Although the attempt to find all the URLs by this method is ridiculous, the general question posed is a very good one. The short answer is that you cannot pickle an iterator in a straightforward way, because the pickle mechanism can't save the iterator's internal state. However, you can pickle an object that implements both __iter__ and __next__. So if you create a class that has the desired functionality and also works as an iterator (by implementing those two functions), it can be pickled and reloaded. The reloaded object, when you make an iterator from it, will continue from where it left off.
#! python3.6
import pickle
class AllStrings:
CHARS = "abcdefghijklmnopqrstuvwxyz0123456789"
def __init__(self):
self.indices = [0]
def __iter__(self):
return self
def __next__(self):
s = ''.join([self.CHARS[n] for n in self.indices])
for m in range(len(self.indices)):
self.indices[m] += 1
if self.indices[m] < len(self.CHARS):
break
self.indices[m] = 0
else:
self.indices.append(0)
return s
try:
with open("bookmark.txt", "rb") as f:
all_strings = pickle.load(f)
except IOError:
all_strings = AllStrings()
try:
for s in iter(all_strings):
print(s)
except KeyboardInterrupt:
with open("bookmark.txt", "wb") as f:
pickle.dump(all_strings, f)
This solution also removes the limitation on the length of the string. The iterator will run forever, eventually generating all possible strings. Of course at some point the application will stop due to the increasing entropy of the universe.

Python define and call function - method behavior changing upon processing user input

I defined a method, like so:
class MyDatastructure(object):
# init method here
def appending(self, elem):
self.data.append(elem)
if self.count >= self.size:
print "popping " + str(self.data[0])
print "inserting " + str(elem)
self.data.pop(0)
elif self.count < self.size:
self.count += 1
print "count after end of method " + str(self.count)
I tested it out, and it worked as supposed to.
Underneath this definition, I wanted to process some user input and use this method. However, it doesn't enter the if case anymore! Any idea why?
# in the same file
def process_input():
while True:
# getting user input
x = raw_input()
ds = MyDatastructure(x) # creating data structure of size, which was taken from user input, count initially 0
ds.appending(1)
ds.appending(2)
ds.appending(3)
# Still appending and NOT popping, even though the if in appending doesn't allow it!
# This functionality works if I test it without user input!
The problem is with this line:
x = raw_input()
Calling raw_input will return a string. If I type in the number 3, that means that the data structure will assign the string "3" to the size.
Attempting to compare a string to a number is considered undefined behavior, and will do weird things -- see this StackOverflow answer. Note that Python 3 fixes this piece of weirdness -- attempting to compare a string to an int will cause a TypeError exception to occur.
Instead, you want to convert it into an int so you can do your size comparison properly.
x = int(raw_input())

Categories

Resources