I need to crack a zip file and i know the first part of the password but I don't know the last 3 letters. This is what i've written but it doesn't work. I have no idea why. can anyone spot my mistake?
T
import zipfile
import itertools
import time
# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
try:
zip_file.extractall(pwd=password)
return True
except KeyboardInterrupt:
exit(0)
except Exception, e:
pass
# Main code starts here...
# The file name of the zip file.
zipfilename = 'data.zip'
# The first part of the password.
first_half_password = 'Cola'
# We don't know what characters they add afterwards...
# This is case sensitive!
alphabet = 'abcdefghijklmnopqrstuvwxyz'
zip_file = zipfile.ZipFile(zipfilename)
# We know they always have 3 characters after the first half of the password
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
# Slowing it down on purpose to improve performance in web terminal.
# Remove this line at your peril
time.sleep(0.001)
# Add the three letters to the first half of the password.
password = first_half_password+''.join(c)
# Try to extract the file.
print "Trying: %s" % password
# If the file was extracted, you found the right password.
if extractFile(zip_file, password):
print '*' * 20
print 'Password found: %s' % password
print 'Files extracted...'
exit(0)
# If no password was found by the end, let us know!
print 'Password not found.'
Related
import re
import logging
x = input("enter number of bad car")
if re.match('/^[A-ZА-Я]{1}[0-9]{3}[A-ZА-Я]{2}([0-9]{0,3})?$/', x):
logging.debug("found match" + x)
with open("some.txt" , 'w') as f:
f.write(x + '\n')
else:
logging.debug("does not match")
However, nothing is written in the file some.txt
I got a logging file which wrote away 'does not match' with the following changes:
import re
import logging
logging.basicConfig(filename = ( "loggingfile.log"), level = logging.DEBUG, format = '%(message)s')
x = input("enter number of bad car")
if re.match('/^[A-ZА-Я]{1}[0-9]{3}[A-ZА-Я]{2}([0-9]{0,3})?$/', x):
logging.debug("found match" + x)
with open("some.txt" , 'w') as f:
needed = str(x + '\n')
logging.info(needed)
else:
logging.info("does not match")
So, I added:
logging.basicConfig, which set some basic configuration stuff
for your logging file (name, path, format...)
I created needed up front, which has all the needed data in it, and then wrote it away to the logging file using logging.info()
I think that that is all that I changed, hope I helped out!
I got output like this from 'logging.log' with input (the random number) 56184615:
does not match
Your regex cannot match. `/^' means a slash, followed by the start of the string. Try to remove the two slashes in the regex.
This code is verbatim from a book titled 'Violent Python'. It is meant to be a simple script that iterates through a .txt file and tries each entry as the password to a locked .zip file.
The script runs and no errors are thrown but no output is given until I
add a count variable that proves each entry is being checked. Although the correct password is in the file the 'if guess:' statement is never run.
Any help will be greatly appreciated!
import zipfile
def extractFile(zfile,password):
try:
zFile.extractall(pwd=password)
return password
except:
return
def main():
count = 0 #added for debugging
zFile = zipfile.ZipFile('secure.zip')
passFile = open('dictionary.txt')
for line in passFile.readlines():
count = count + 1 #added for debugging
password = line.strip('\n')
guess = extractFile(zFile, password)
print count #added for debugging
if guess:
print "[+] Password = " + password + "\n"
exit(0)
if __name__=='__main__':
main()
I am new to python and have probably started with something a little complicated. Nevertheless I am nearly there.
My problem is I am having a bit of difficulty understanding how to group, or sequence a group of statements in my code (my syntax is probably wrong as well) using try and except or if, elsif and else. I really just need someone to say I should be using this instead of that and I can figure it out from there.
Here is a diagram of what I am trying to accomplish:
https://drive.google.com/file/d/0BxtxgkV8mylgSFRuMnZtaEpXLVE/view?usp=sharing
And here is my code so far (please note this is my FIRST python program - actually first program of any sort - so I would appreciate it if you would not tear me apart too badly for any formatting or syntax errors - updated to include Johns fix)
import ldap
import os
import subprocess
import uuid
from pwd import getpwnam
# Lookup all the users in the cloud group
path='dc=saao'
l=ldap.open('ldap1.cape')
l.protocol_version = ldap.VERSION3
l.simple_bind('dc=cape')
a=l.search_s(path,ldap.SCOPE_SUBTREE,'cn=cloudcape')
# Add members to uids
uids=a[0][1]['memberUid']
# Check if a bindmount already exists or it not, that each cloud group user has the required directory i.e. /home/USER/cloud and /var/www/owncloud/data/USER/files
for uid in uids:
cloudfiledir="/var/www/owncloud/data/"+uid+"/files"
clouddir="/home/"+uid+"/cloud"
try:
subprocess.check_output(["mountpoint", cloudfiledir])
# If the output is all good, their bind mount is setup and mounted
break
except:
print uid+" has not logged into ownCloud yet - please ask them to do so and then try again"
break
# Now check if they have the required directories
try:
if os.path.isdir(cloudfiledir):
print "user "+ uid +" has a data directory in the owncloud data directory- this is good."
if os.path.isdir("/home/"+uid+"/cloud"):
print "user "+ uid +" has a cloud dir in their home directory - this is good."
else:
# They don't have a cloud directory, creating one
print uid+" does not have a cloud folder in their home directory, creating it"
if not os.path.exists("/home/"+uid+"/cloud"):
os.makedirs("/home/"+uid+"/cloud")
# Now set permissions ("+uid+":Domain Users) - os.chown(path, uid, gid)
os.chown("/home/"+uid+"/cloud", "+uid+", "Domain Users")
else:
break
# Now make sure the cloufilesdir is empty
if not os.listdir(cloudfiledir):
print "Empty"
break
except:
print "rename and recreate the folder"
os.rename(clouddir, clouddir + str(uuid.uuid4()))
os.makedirs(clouddir)
os.chown(clouddir, 33, 33)
print "Now let's bind mount the directories"
# Bind each users home dir to their cloud dir
# Eg: bindfs -M www-data --create-for-user=1168 --create-for-group=513 /home/simon/cloud /var/www/owncloud/data/simon/files
# Still figuring this bit out
for user in a[0][1]['memberUid']:
filt = "(uid=" + user + ")"
u=l.search_s(path, ldap.SCOPE_SUBTREE, filt, ['uidNumber'])
print "\t", user, "filter: ", filt, u, "or"
uid = u[0][1]['uidNumber'][0]
print "\t\t", user, filt, uid
command = 'bindfs -M www-data --create-for-user=' + uid + ' --create-for-group=513 ' + '/home/' + user + '/cloud' + ' /var/www/owncloud/data/' + user + '/files'
print "BINGO: ", command, "\n"
John's advice fixed my except syntax, not I need to try and understand why the program only runs for the first UID and not the rest of them (there are 5 in the ldap group at the moment, 2 of which I have manually mounted so I would expect 3 bind mounts to happen).
I would appreciate any guidance as I continue to try and figure this out by trial and error.
Thanks in advance.
Simon
So, much reading and asking some wise colleagues later, I much a much better understanding of how for loops work, what break does and how useful continue can be.
Here is my final piece of code:
#!/usr/bin/python
import ldap
import os
import subprocess
import uuid
from pwd import getpwnam
# Lookup all the users in the cloudcape group
path='dc=cape'
l=ldap.open('ldap1.cape')
l.protocol_version = ldap.VERSION3
l.simple_bind('dc=cape')
a=l.search_s(path,ldap.SCOPE_SUBTREE,'cn=cloudcape')
# Add members to uids
uids=a[0][1]['memberUid']
# Check if a bindmount already exists or it not, that each cloud group user has the required directory i.e.home/USER/cloud and /var/www/owncloud/data/USER/files
for uid in uids:
# Define the directory paths
cloudfiledir="/var/www/owncloud/data/"+uid+"/files"
clouddir="/home/"+uid+"/cloud"
try:
subprocess.check_output(["mountpoint", cloudfiledir])
# If the output is all good, their bind mount is setup and mounted, if not carry on
except subprocess.CalledProcessError:
print uid+" does not have a mountpoint"
else:
continue
# Check if they have /var/www/owncloud/data/UID
if not os.path.isdir(cloudfiledir):
print uid+" does not have a owncloud directory structure in /var/www/owncloud, creating it"
os.makedirs("/var/www/owncloud/data/"+uid+"")
os.makedirs("/var/www/owncloud/data/"+uid+"/files")
os.makedirs("/var/www/owncloud/data/"+uid+"/cache")
# Now set permissions ("+uid+":Domain Users) - os.chown(path, uid, gid)
os.chown("/var/www/owncloud/data/"+uid+"", 33, 33)
os.chown("/var/www/owncloud/data/"+uid+"/files", 33, 33)
os.chown("/var/www/owncloud/data/"+uid+"/cache/", 33, 33)
# Now check if the have /home/UID/cloud
if not os.path.isdir(clouddir):
# They don't have a cloud directory, creating one
print uid+" does not have a cloud folder in their home directory, creating it"
os.makedirs(clouddir)
# Now set permissions ("+uid+":Domain Users) - os.chown(path, uid, gid)
os.chown(clouddir, "+uid+", "Domain Users")
# Now make sure the cloudfilesdir is empty
try:
if not os.listdir(cloudfiledir) == []:
print "The mount point is not empty"
os.rename(cloudfiledir, cloudfiledir + str(uuid.uuid4()))
os.makedirs(cloudfiledir)
os.chown(cloudfiledir, 33, 33)
except:
print "The mount point is empty, moving on"
print "Now let's bind mount the directories"
# Bind each users home dir to their cloud dir
filt = "(uid=" + uid + ")"
userid=l.search_s(path, ldap.SCOPE_SUBTREE, filt, ['uidNumber'])
print "\t", uid, "filter: ", filt, userid, "or"
numuid = userid[0][1]['uidNumber'][0]
print "\t\t", uid, filt, uid
os.system('bindfs -M www-data --create-for-user=' + numuid + ' --create-for-group=513 ' + '/home/' + uid + '/cloud' + ' /var/www/owncloud/data/' + uid + '/files')
I have no doubt there are simpler and more efficient ways to do this but for now, the code does what I want it to do. I still need to build some fault tolerance into it, I already spotted one area where it might fail if a certain directory exists but that is next weeks problem.
I have a module that i want to write into. I'm having several problems. One of which locating a string within the file. Currently I open the file, then use a for line in (filename), then do an if to determine if it finds a string, and all of that works. However before (it is commented out now) i tried to determine what position it was at using tell(). However this gave me an incorrect position, giving me 1118 i believe, instead of 660 something. So i determined the position manually to use seek.
However the second problem was, if i write to this file at the position in the file, it just overwrites all the data from thereon. I would want to insert the data instead of overwriting it.
Unless i insert a string equal in character length where i want the write to happen, it will just override most of the if statements and things like that below.
Is there any way to naively do this?
Here is the file i want to write into
# Filename: neo_usercurves.py
# Created By: Gregory Smith
# Description: A script containing a library of user created curves
# Purpose: A library to store names of all the user curves, and deletes curves
# if specified to do so
import os
import maya.cmds as mc
import module_locator
my_path = module_locator.module_path()
def usercurve_lib(fbxfile=None, remove=None):
"""All control/curve objects created by user
Keyword Arguments:
fbxfile -- (string) name of fbx file to import
remove -- (boolean) will remove an entry from the library and delete the
associated fbx file
"""
curves_dict = {
#crvstart
#crvend
}
if remove is None:
return curves_dict
elif not remove:
try:
name = mc.file(curves_dict[fbxfile], typ='FBX', i=1,
iv=True, pmt=False)
return name[0]
except RuntimeError:
return None
else:
try:
os.remove('%s\%s.fbx' %(my_path, fbxfile))
return '%s.fbx' %(fbxfile)
except OSError:
print 'File %s does not exist.' %(fbxfile)
return None
This is the code below that i'm running in a module called neo_curves.py (this is not the complete code, and 'my_path' is just the path of the current directory neo_curves.py is being run in)
def create_entry(self, crv):
"""Exports user curve to user data directory and adds entry into
neo_usercurves.py
Keyword Arguments:
crv -- (PyNode) the object to export
"""
# set settings
mel.eval('FBXExportFileVersion "FBX201400"')
mel.eval('FBXExportInputConnections -v 0')
select(crv)
mc.file('%s\userdat\%s.fbx' %(my_path, str(crv)), force=True, options='',
typ='FBX export', pr=True, es=True)
with open('%s\userdat\\neo_usercurves.py' %(my_path), 'r+') as usercrvs:
for line in usercrvs:
if line.strip() == '#crvstart':
#linepos = usercrvs.tell()
#linepos = int(linepos)
#usercrvs.seek(linepos, 0)
usercrvs.seek(665, 0)
usercrvs.write("\n "+str(crv)+" : '%s\%s' %(my_path, '"+
str(crv)+".fbx')")
break
This will give me this result below:
# Filename: neo_usercurves.py
# Created By: Gregory Smith
# Description: A script containing a library of user created curves
# Purpose: A library to store names of all the user curves, and deletes curves
# if specified to do so
import os
import maya.cmds as mc
import module_locator
my_path = module_locator.module_path()
def usercurve_lib(fbxfile=None, remove=None):
"""All control/curve objects created by user
Keyword Arguments:
fbxfile -- (string) name of fbx file to import
remove -- (boolean) will remove an entry from the library and delete the
associated fbx file
"""
curves_dict = {
#crvstart
loop_crv : '%s\%s' %(my_path, 'loop_crv.fbx') return curves_dict
elif not remove:
try:
name = mc.file(curves_dict[fbxfile], typ='FBX', i=1,
iv=True, pmt=False)
return name[0]
except RuntimeError:
return None
else:
try:
os.remove('%s\%s.fbx' %(my_path, fbxfile))
return '%s.fbx' %(fbxfile)
except OSError:
print 'File %s does not exist.' %(fbxfile)
return None
In short: on most operating systems you can not insert into files without rewriting if the lengths are not the same.
Have a look at a long discussion here: Why can we not insert into files without the additional writes? (I neither mean append, nor over-write)
I'm having an issue with an OpenCourseWare project I'm trying to implement. I'm creating a hangman game and everything seems to be okay until I attempt to run the actual function for playing the game.
I'm receiving the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "Game of Hangman/hangman.py", line 118, in play_hangman
print(print_guessed())
File "Game of Hangman/hangman.py", line 92, in print_guessed
if letter in letters_guessed == True:
TypeError: argument of type 'NoneType' is not iterable
I can't seem to understand why the list is evaluating to a NoneType even though it is declared as an empty list. I've used the console to attempt to find the answer and says the type is NoneType. Could someone help me please? I've provided the code as a reference.
# Name:
# Section:
# 6.189 Project 1: Hangman template
# hangman_template.py
# Import statements: DO NOT delete these! DO NOT write code above this!
from random import randrange
from string import *
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
# Import hangman words
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = split(line)
print " ", len(wordlist), "words loaded."
print 'Enter play_hangman() to play a game of hangman!'
return wordlist
# actually load the dictionary of words and point to it with
# the words_dict variable so that it can be accessed from anywhere
# in the program
words_dict = load_words()
# Run get_word() within your program to generate a random secret word
# by using a line like this within your program:
# secret_word = get_word()
def get_word():
"""
Returns a random word from the word list
"""
word=words_dict[randrange(0,len(words_dict))]
return word
# end of helper code
# -----------------------------------
# CONSTANTS
MAX_GUESSES = 6
# GLOBAL VARIABLES
secret_word = get_word()
letters_guessed = []
# From part 3b:
def word_guessed():
'''
Returns True if the player has successfully guessed the word,
and False otherwise.
'''
global secret_word
global letters_guessed
wordGuessed = False
####### YOUR CODE HERE ######
for letter in secret_word:
if letter in letters_guessed:
wordGuessed = True
else:
wordGuessed = False
break
return wordGuessed
def print_guessed():
'''
Prints out the characters you have guessed in the secret word so far
'''
global secret_word
global letters_guessed
printedWord = []
####### YOUR CODE HERE ######
for letter in secret_word:
if letter in letters_guessed:
printedWord.append(letter)
else:
printedWord.append("-")
return printedWord
def play_hangman():
# Actually play the hangman game
global secret_word
global letters_guessed
# Put the mistakes_made variable here, since you'll only use it in this function
mistakes_made = 0
# Update secret_word. Don't uncomment this line until you get to Step 8.
secret_word = get_word()
####### YOUR CODE HERE ######
while mistakes_made < MAX_GUESSES or word_guessed() == False:
print("WORD:")
userGuess = raw_input("What is your guess?\n").lower()
if userGuess in secret_word:
letters_guessed = letters_guessed.append(userGuess)
else:
letters_guessed = letters_guessed.append(userGuess)
mistakes_made += 1
print(print_guessed())
if word_guessed() == False:
print("Sorry but you've run out of guesses...")
else:
print("You've correctly guessed the secret word!")
print("Secret Word: " + secret_word)
Just as a disclaimer, this isn't an assignment in the sense I'm not enrolled in school. I'm just a guy trying to get back in to programming and found some assignments to play with.
Looks like I've found my answer. The problem appeared to be with the assignment I was doing with the letters_guessed variable.
Instead of doing:
letters_guessed = letters_guessed.append(userGuess)
I should have done:
letters_guessed.append(userGuess)