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()
Related
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.'
I'm new to python and i'm trying to make a password manager.
the problem is that my program works fine when i run it through IDLE or Pycharm
but it stops running when i run it directly from windows when it reaches the line where I import the file where i store the password.
import time
user = raw_input("Username: ")
pw = raw_input("Password: ")
if user == "PrOoOg" and pw == "aka443":
def add_acc_func(acc, user, pw):
database.write("\nAccount: ")
database.write(acc)
database.write(" Username: ")
database.write(user)
database.write(" Password: ")
database.write(pw)
database.close()
def print_database_func():
for lines in database.readlines():
print lines.strip('\n')
database.close()
user_input = raw_input('Press "A" to add a new account\nPress "M" to modify and existing account\n'
'Press "D" to delete and existing account\nPress "S" to show all accounts and passwords\n')
user_choice = user_input.lower()
if user_choice == "a":
database = open("source.txt", "a") #Everything worked fine when i deleted this line
acc_to_add = raw_input("Write the name of the site or service: ").lower()
acc_to_add_user = raw_input("Write the username or email you want to set for that account: ")
acc_to_add_pw = raw_input("Write the password you want to set to that account: ")
add_acc_func(acc_to_add, acc_to_add_user, acc_to_add_pw)
print "Account added"
if user_choice == "s":
database = open("source.txt", "r") #Everything worked fine when i deleted this line
print_database_func()
raw_input("Press Enter to quit")
else:
print ("Wrong username or password")
time.sleep(3)
I tried to delete the lines where I import the text file and it worked.
i don't know why the code can't open the file when opened from windows and can open it when opened from IDLE or Pycharm
"it's just crashes when i run it from windows (rightclick ==> open with ==> python.exe)"
When you do this the working directory is C:\Windows\system32. Most likely you don't have write permissions to this directory. When running the script using the other methods the working directory is most likely the one containing the script. You need to change to a directory which you have write permissions for.
Here is an example to use the current user's Documents folder:
import os
dir = os.path.expanduser('~/Documents')
os.chdir(dir)
this is just part of the long python script. there is a file called aqfile and it has many parameters. I would like to extract what is next to "OWNER" and "NS".
Note:
OWNER = text
NS = numbers
i could extract what is next to OWNER, because they were just text and i could extract.
for line in aqfile.readlines():
if string.find(line,"OWNER")>0:
print line
m=re.search('<(.*)>',line)
owner=incorp(m.group(1))
break
but when i try to modify the script to extract the numbers
for line in aqfile.readlines():
if string.find(line,"NS")>0:
print line
m=re.search('<(.*)>',line)
ns=incorp(m.group(1))
break
it doesnt work any more.
Can anyone help me?
this is the whole script
#Make a CSV file of datasetnames. pulseprog and, if avaible, (part of) the title
#Note: the whole file tree is read into memory!!! Do not start too high in the tree!!!
import os
import os.path
import fnmatch
import re
import string
max=20000
outfiledesc=0
def incorp(c):
#Vervang " door """ ,CRLF door blankos
c=c.replace('"','"""')
c=c.replace("\r"," ")
c=c.replace("\n"," ")
return "\"%s\"" % (c)
def process(arg,root,files):
global max
global outfiledesc
#Get name,expno,procno from the root
if "proc" in files:
procno = incorp(os.path.basename(root))
oneup = os.path.dirname(root)
oneup = os.path.dirname(oneup)
aqdir=oneup
expno = incorp(os.path.basename(oneup))
oneup = os.path.dirname(oneup)
dsname = incorp(os.path.basename(oneup))
#Read the titlefile, if any
if (os.path.isfile(root + "/title")):
f=open(root+"/title","r")
title=incorp(f.read(max))
f.close()
else:
title=""
#Grab the pulse program name from the acqus parameter
aqfile=open(aqdir+"/acqus")
for line in aqfile.readlines():
if string.find(line,"PULPROG")>0:
print line
m=re.search('<(.*)>',line)
pulprog=incorp(m.group(1))
break
towrite= "%s;%s;%s;%s;%s\n" % (dsname,expno,procno,pulprog,title)
outfiledesc.write(towrite)
#Main program
dialogline1="Starting point of the search"
dialogline2="Maximum length of the title"
dialogline3="output CSV file"
def1="/opt/topspin3.2/data/nmrafd/nmr"
def2="20000"
def3="/home/nmrafd/filelist.csv"
result = INPUT_DIALOG("CSV file creator","Create a CSV list",[dialogline1,dialogline2,dialogline3],[def1,def2,def3])
start=result[0]
tlength=int(result[1])
outfile=result[2]
#Search for procs files. They should be in any dataset.
outfiledesc = open(outfile,"w")
print start
os.path.walk(start,process,"")
outfiledesc.close()
I am processing certain output binary files using sloginfo on QNX, I have used ftp/telnet/vmware to get to a point where I upload the binary from my machine to the vmware instance and then run the sloginfo command.
The issue is that binary files which need to be processed are of inconsistent size (ranging from 50mb to 200mb), and the time needed to process each of these files is different, thus making it impossible to determine the wait/sleep time required.
I need to know if sloginfo returns a value which can be used as a flag. I tried using tn.read_until(), without getting desired results.
#
import os, sys, telnetlib, time
from ftplib import FTP
def upload(ftp, filed):
ext = os.path.splitext(filed)[1]
if ext in (".txt", ".htm", ".html"):
ftp.storlines("STOR " + filed, open(filed))
else:
ftp.storbinary("STOR " + filed, open(filed, "rb"), 1024)
def gettext(ftp, filename, outfile=None):
# fetch a text file
if outfile is None:
outfile = sys.stdout
# use a lambda to add newlines to the lines read from the server
ftp.retrlines("RETR " + filename, lambda s, w=outfile.write: w(s+"\n"))
if __name__ == '__main__':
dbfile = "LOG1"
nonpassive = False
remotesite = '192.168.0.128'
ftp_port = '21'
tel_port = '23'
password = 'root'
ftp = FTP()
ftp.connect(remotesite, ftp_port)
ftp.login('root','root')
print 'Uploading the Log file... Please wait...'
upload (ftp, dbfile)
print 'File Uploaded Successfully...'
tn = telnetlib.Telnet(remotesite, tel_port)
tn.read_until("login: ")
tn.write('root' + "\n")
if password:
tn.write(password + "\n")
tn.write("sloginfo LOG1 >> LOG1.txt\n")
**#need to get more control on this sleep time**
time.sleep(300)
print 'Downloading text file...'
gettext(ftp, "LOG1.txt", open(r'LOG1.txt','wb'))
ftp.close()
tn.close()
tn.write("sloginfo LOG1 >> LOG1.txt\n") modified the above comment with tn.write ('sloginfo '+ strdbfile + '>> ' + strdbfiletxt+ '; echo Done!\n') and this has resolved the issue
I've been struggling with this for a few hours. I want to send a text file generated by Django to another server. For that I use scp and subprocess.call(). Everything goes well and I got a return_code == 0, but scp sends 0 bytes. The file created on the server side is empty.
I printed the exact command executed, the path is right, and if I put in in a shell it works perfectly.
Here is the code:
form = SubmitForm(request.POST or None)
context['form'] = form
if request.method == 'POST':
if form.is_valid():
# write file in ~/hipercic/apps/dcor/jobs/
params_file = open('apps/dcor/jobs/job_' + datetime.today().strftime("%Y%m%d_%H%M%S") + '_params.txt', 'wb')
for key, val in form.cleaned_data.iteritems():
params_file.write(str(val) + ' \n')
params_file.close
cmd = 'scp /home/guillet/hipercic/' + params_file.name + ' guillet#helios.public.stolaf.edu:'
context['cmd'] = cmd
return_code = subprocess.call(cmd, shell=True)
context['return_code'] = return_code
return render(request, 'base_pending.html', context)
I thought about a possible race condition, the file not having time to be completely written before being send, but nothing changes with a time.sleep(3).
Also, something really weird and the heart of the issue, if I tried to reopen and read the file right after closing it, the file is empty:
with open('/home/guillet/hipercic/' + params_file.name, 'rb') as f:
print f.read() # prints nothing!!
you have done params_file.close instead of params_file.close()
Closing the file properly will flush the data to the file you want to write to
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes.