Simple Python Excel password crack - Brute Force - python

For a demonstration I want to crack an excel file (named 'xl') password. I use the following code but (1) it fails to open excel and (2) it does not stop running when the password is cracked.
import itertools
import string
from win32com.client import Dispatch
file = input('Path: ')
chars = string.ascii_lowercase + string.digits
for password_length in range(1, 2):
for password in itertools.product(chars, repeat=password_length):
password = ''.join(password)
print ('Testing password: '+ password)
instance = Dispatch ('Excel.Application')
try:
instance.Workbooks.Open(file, False, True, None, password)
print ('Password Cracked: ' + password)
#break
except:
pass
I set the excel password as 'p' and the code just runs through 1 character combinations for simplicity. Moreover, when you run the code it requires as input the path of the excel file.
I can't figure out my mistake and I would appreciate some help. Also if doing this for a word document is easier please let me know.

Loop does not stop because you have #break commented out.

Related

Excel password recovery in Python

Below I have been working on a Excel password recovery tool for work as we have had a few occasions where project managers have password protected excels and then forgot the password and they have lost weeks of work because of this.
The below code seems to be running but doesn't get past the first word in the wordlist and then paste that the password has been found.
Example of output:
in cmd
C:\Users\eldri\OneDrive\Desktop>python xlcrka.py
[+] Excel to attack: C:\Users\eldri\OneDrive\Desktop\target.xlsx
[+] Wordlist: C:\Users\eldri\OneDrive\Desktop\Wordlists\rockyou.txt
[-] Password attempt: 123456
[+] Password Found: 123456
in Pycharm Terminal
C:\Users\eldri\PycharmProjects\CAPTCHA\venv\Scripts\python.exe "C:/Users/eldri/PycharmProjects/Bad codes/xlcrka.py"
[+] Excel to attack: C:\Users\eldri\OneDrive\Desktop\target.xlsx
[+] Wordlist: C:\Users\eldri\OneDrive\Desktop\Wordlists\rockyou.txt
[-] Password attempt: 123456
[+] Password Found: 123456
Below is the code I have got so far:
from pip._vendor.distlib.compat import raw_input
from win32com.client import Dispatch
file = raw_input('[+] Excel to attack: ')
wordlist = raw_input('[+] Wordlist: ')
word = open(wordlist, 'r', encoding='utf8', errors='ignore')
allpass = word.readlines()
word.close()
for password in allpass:
password = password.strip()
print ("[-] Password attempt: "+password)
instance = Dispatch('Excel.Application')
try:
instance.Workbooks.Open(file, False, True, None, password)
print ("[+] Password Found: "+password)
break
except:
pass
The outcome I want to achieve:
Learn why this is not working.
see whether anyone has any ideas on how to improve
Output for the code:
To go through the wordlist and find the correct password and print the password
I found what you where missing, you needed a else: break in the try except statement so that once the password was found the loop will break and did not carry on printing incorrect password found statements. You also needed instance.Quit() to prevent the program from continuing the print incorrect password found statements if you re-ran the code. I moved instance from the loop as you don't need to open a new instance every time (that might have caused some issues thinking about it)
from win32com.client import Dispatch
from pywintypes import com_error
file = input('[+] Excel to attack: ')
wordlist = input('[+] Wordlist: ')
instance = Dispatch('Excel.Application')
word = open(wordlist, 'r', encoding='utf8', errors='ignore')
allpass = word.readlines()
word.close()
for password in allpass:
password = password.rstrip()
print("[-] Password attempt: " + password)
try:
instance.Workbooks.Open(file, False, True, None, password)
print("[+] Password Found: " + password)
except com_error:
instance.Workbooks.Close()
else:
instance.Workbooks.Close()
instance.Quit()
break
I also imported com_error from pywintypes for the exception handling, you should try to avoid a bare except statement as that could cause issues and is not good practice.
Your break after print ("[+] Password Found: "+password) ends the loop. So as long as Workbooks.Open doesn't raise you will never try any other password.
I don't know how Workbooks.Open works but you might want to check for its return value to know if you've found the right password.
Also a try/except like that will mute any error so you can't know if anything wrong happened, at least replace it with:
import traceback
...
except Exception as ecx:
traceback.print_exc()
# or
print(exc)
In order to find out what's going on, remove the try-block from the code.
Your code is structured in such a way that
instance.Workbooks.Open(file, False, True, None, password)
is supposed to raise some general error which you do not specify. In your sample case it does not and hence it continues and ends.
Remove the 'try-block' and try to access any method on the open workbook and see what happens.

How to save output in python to .txt file

So basically i bought a book that teaches the basics of python and how to create a random number generator so I decided to go one step further and make a random password generator I found a tutorial online that gave me a good example of why and what is used to make a password generator but i want the output to be saved to a .txt file I do not know what i need to implement to get the result i want this is what i have i'm using python3.
import random
chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, #,#$%^&*.'
number = input('Number of passwords - ')
number = int(number)
length = input('password length? - ')
length = int(length)
answer = input
for P in range(number):
password = ''
for C in range(length):
password += random.choice(chars)
print(password)
password = open("passlist.txt", "a")
password.write(password)
password.close()
file = open('passlist', 'w')
file.write(password)
file.close()
this is what i get in shell
Traceback (most recent call last):
File "C:\User\Desktop\passgen.py", line 21, in <module>
password.write(password)
TypeError: write() argument must be str, not _io.TextIOWrapper
When you open a new file and set it equal to a variable, you are actually creating an _io.TextIOWrapper object. So in this line of code, you are creating this object and storing it in password, getting rid of the password generated in the previous lines of code.
password = open("passlist.txt", "a")
You are then trying to write to the passlist.txt file with this line:
password.write(password)
You are telling password, now an _io.TextIOWrapper object, to write to the passfile.txt the _io.TextIOWrapper object, not the password generated beforehand. This function is expecting a string, and you are now passing an _io.TextIOWrapper object. Since password is no longer a string, that is why you are running into the error.
To fix this, I would suggest creating a new variable:
txtFileWriter = open("passlist.txt", "a")
txtFileWriter.write(password)
txtFileWriter.close()
You may find that after fixing this, only one value is being stored inside your text file. I would recommend properly nesting your for loops:
for P in range(number):
password = ''
for C in range(length):
password += random.choice(chars)
print(password)
The meaning of these for loops can be translated as:
For each password, set the password = ' ' and for each character, add one random character to password.
The problem with this is that you will only have one password after the for loops are complete. You are setting the password value to ' ' each time you run through the outer loop. The only password that will be saved, will be the last value. In order to fix this, I recommend using a list.
I recommend reading through this documentation
I don't want to spoon feed the answers since I realize you are learning python, so I will leave it here. You will want to create a list and then append a value to that list each time you generate a password. After some reading, hopefully this will make sense.
filename = 'passlist.txt'
with open (filename, 'a') as file_object:
file_object.write(password)
Using with will close the file once access is no longer needed.
You also need a list to append your passwords ;)
The error originates from password being re-assigned in password = open("passlist.txt", "a"). This causes and error in the next line as you are attempting to pass password as parameter to itself in password.write(password).
Some farther assistance
You have the right idea but you forgot to indent. All the lines below for P in range(number): should be indented because the program must generate and write a new password until it has satisfied the required amount of passwords.
The password = open("passlist.txt", "a")
password.write(password)
password.close() lines are unnecessary as you are overriding the generated password and assigning that password variable to something that is not a string; that is why you are getting that error.
Here is the code with the adjustments.
import random
chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, #,#$%^&*.'
number = input('Number of passwords - ')
number = int(number)
length = input('password length? - ')
length = int(length)
answer = input
for P in range(number):
password = ''
for C in range(length):
password += random.choice(chars)
print(password)
password += "\n" # writes the password in a new line
file = open('passlist.tx', "a")
file.write(password)
file.close()

Can't compare input variables to those from a file

I am making a login system for my project, and I have the usernames and passwords stored in a text file, with usernames in the first column and passwords in the second column, and then separating each login/password with a new line and using : as a barrier between the username/password.
Upon entering the correct username and password, I always get incorrect login, however if I only compare the username to the file it functions properly. Even if I print the password and username straight from the file and then print it next to the username/password I entered, it is still the exact same yet still say incorrect login!
def login():
file=open("user.txt","r")
user=input("enter usename")
password=input("enter password")
Check=False
for line in file:
correct=line.split(":")
if user==correct[0] and password==correct[1]:
Check=True
break
if Check==True:
print("succesffuly logged in")
file.close()
mainMenu()
else:
print("incorrect log in")
file.close()
login()
I suspect you have a \n at the end of each user / password string. I suspect line looks like user:pass\n after being read in. Use line.strip().split(':') to remove the newline, which is causing password==correct[1] to fail.
Replace:
for line in file:
correct=line.split(":")
With:
for line in file:
correct=line.strip().split(":")
For why, see https://docs.python.org/2/library/string.html#string.strip
string.strip(s[, chars])
Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.
We can just check using in
def login():
file = open("user.txt", "r")
user = input("enter usename ")
password = input("enter password ")
if ('{0}:{1}'.format(user, password)) in file:
print('yay')
else:
print('Boo !! User not found')
login()
if you wanted to use the for loop I would suggest:
def login():
file = open("user.txt", "r")
user = input("enter usename ")
password = input("enter password ")
for line in file:
temp_user, temp_password = line.strip().split(':')
if temp_user == user and temp_password == password.strip():
print('yay')
else:
print('boo username and password not found!')
login()
Really important, WARNING!
Please take necessary security measurements as this code does not provide any, there are a lot of vulnerabilities that could be exploited. No hashing function and Python itself does not provide a lot of security, I would suggest using getpass.getpass explanation HERE

Open Password Protected zip file with python

I am trying to open a protected zip file I know for a fact that the first 5 characters are Super and the password is eight characters long with no numbers or symbols I am using this code in python to help me but it is not working can anyone help?
code:
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 as e:
pass
# The file name of the zip file.
zipfilename = 'planz.zip'
# The first part of the password.
first_half_password = 'Super'
# We don't know what characters they add afterwards...
alphabet = 'abcdefghijklmnopqrstuvwxyz'
zip_file = zipfile.ZipFile(zipfilename)
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
# 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.')
Hy man! Basically, you can just append the alphabet variable to include the uppercase letters, the password is a play on superman, If I remember correctly
The problem is, that
if extractFile(zip_file, password):
is also true for wrong passwords in many cases. (see:https://bugs.python.org/issue18134) It then leaves an "unziiped file" with length 0 or some bytes.
You have to check if the output file is the right size.
for example by finding out the size of the first file in zip
zip_file = zipfile.ZipFile(zipfilename)
firstmember=zip_file.namelist()[0]
firstmembersize=zip_file.getinfo(firstmember).file_size
and later
if os.path.getsize(firstmember) == firstmembersize:
and dont forget to delete the wrong sized file after checking to give way for the next try ...

txt file to dictionary and login implementation Python 3

I am attempting to create a login script. I have the usernames and passwords in a text file that I want python to read and check through to find usernames and passwords.
The biggest problem I am having is "attaching" the password to a username. I can currently only scan the whole of the document for both but not necessarily attached to each other.
#-------------------------------------------------------------------------------
# Name: LogIn
# Purpose: Logging In
#
# Author: Dark Ariel7
#
# Created: 19/02/2013
# Copyright: (c) Dark Ariel7 2013
# Licence: I take no responsability for anything.
#-------------------------------------------------------------------------------
from getpass import getpass
from time import sleep
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
Username = ("")
Password = ()
def LogIn():
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
Data = (Database.read())
Username = ("")
Password = ()
Username = input("Username: ")
Password = getpass(str("Password: "))
LogIn= ",".join((Username,Password))
if LogIn in Data:
print("Welcome, " + Username)
sleep(3)
pass
else:
print("Failed, Sucker!")
sleep(5)
exit()
LogIn()
If you guys could help me figure out what exactly .join part is for that would be great. Should i make a dictionary and use the index for a login sheet? I also want some general feedback on how to make the code better.
This is the txt file that it will be reading:
[Dark Ariel7,123456]
[Poop,Anko]
*Edit Sorry guys I forgot to mention that I am using python 3 not 2. Thanks so far. Very quick replies. Also after the last else instead of exit what do I put so that the function loops until I get the right username password combo?
The ".join" part joins the username and password that the user types in with a comma between them (i.e. Poop,Anko) because that's the format in which it's stored in the database, so you can search for it that way.
Here's your code, edited up a bit, with some comments about functionality and style.
from getpass import getpass
from time import sleep
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
# These next two lines aren't necessary - these variables are never used; you may want to read up about namespaces: http://bytebaker.com/2008/07/30/python-namespaces/
#Username = ("")
#Password = ()
def LogIn():
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
# Removed the parentheses; they have no effect here. Putting parens around lone statements doesn't have any effect in python.
Data = Database.read()
# These next two lines are pointless, because you subsequently overwrite the values you give these variables. It looks like you're trying to "declare" variables, as you would in Java, but this isn't necessary in python.
# Username = ("")
# Password = ()
# Changed this from "input" to "raw_input" because input does something else that you don't want.
Username = raw_input("Username: ")
Password = getpass(str("Password: "))
LogIn= ",".join((Username,Password))
if LogIn in Data:
print("Welcome, " + Username)
# Not sure why you want the script to sleep, but I assume you have your reasons?
sleep(3)
# no need to pass
# pass
else:
print("Failed, Sucker!")
sleep(5)
# exit() isn't necessary - the function will end by itself.
# exit()
LogIn()
The basic problem you have is that your file has [ ] surrounding the username and password combination, but you fail to account for this.
There are some other stylistic issues with your code, here is an edited version:
import getpass
from time import sleep
password_file = r'C:\....\Database.txt'
def login(user,passwd):
''' Checks the credentials of a user '''
with open(password_file) as f:
for line in f:
if line.strip(): # skips blank lines
username,password = line.split(',') # this gets the individual parts
username = username[1:] # gets rid of the [
password = password[:-1] # the same for the password
if user == username and password == passwd:
return True
return False
if __name__ == '__main__':
username = input('Please enter the username: ')
passwd = getpass('Please enter the password: ')
if login(user,passwd):
print('Welcome {1}'.format(user))
sleep(3)
else:
print('Failed! Mwahahaha!!')
sleep(5)
To start off with, you don't need () to "initialize" variables; more to the point in Python you don't need to initialize variables at all. This is because Python doesn't have variables; but rather names that point to things.
Next, the python style guide says that variable names should be lowercase, along with method names.
Now - the main part of the code:
>>> username, password = '[username,sekret]'.split(',')
>>> username
'[username'
>>> password
'sekret]'
I used split() to break up the line into the username and password parts; but as you see there is still the [ messing things up. Next I did this:
>>> username[1:]
'username'
>>> password[:-1]
'sekret'
This uses the slice notation to strip of the leading and ending characters, getting rid of the [ ].
These lines:
with open(password_file) as f: # 1
for line in f: # 2
if line.strip(): # skips blank lines
Do the following:
Opens the file and assigns it to the variable f (see more on the with statement)
This for loop steps through each line in f and assigns the name line to each line from the file.
The third part makes sure we skip blank lines. strip() will remove all non-printable characters; so if there are no characters left, the line is blank and will have a 0 length. Since if loops only work when the condition is true, and 0 is a false value - in effect what happens is we only operate on non-blank lines.
The final part of the code is another if statement. This is a check to make sure that the file will run when you execute it from the command prompt.

Categories

Resources