Excel password recovery in Python - 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.

Related

Python login program using textfiles

Im new to python and I'm trying to code a python login program. Instead of printing out "Welcome to the database" when the username provided is correct, it printed out both "Welcome to the database" and "Username invalid. Please try again.". May I know which part of my code needs to be corrected?
def login():
while True:
name = input("Name: ")
with open('username.txt', "r")as name_file:
for line in name_file.readlines():
if name == line.strip():
print("welcome to database")
else:
print("Username invalid. Please try again")
You are looping through all the users in the text file and for each of them printing to the console. The thing you probably want could be done like this:
def login():
while True:
loginSucessful = False
name = input("Name: ")
with open('username.txt', "r")as name_file:
for line in name_file.readlines():
if name == line.strip():
loginSucessful = True
break
if loginSucessful:
print("welcome to database")
else:
print("Username invalid. Please try again")
You could use a boolean variable to keep track of successful logins like #Michalor did. Or you can use Python's for/else loop to do the same thing without adding a new variable. If the login is successful and you break out of the loop, the "else" statement isn't executed. Using "break" also has the advantage that you don't need to test all of the other users after you have found a successful login.
def login():
while True:
name = input("Name: ")
with open('username.txt', "r")as name_file:
for line in name_file.readlines():
if name == line.strip():
print("welcome to database")
break
else:
print("Username invalid. Please try again")
Of course, this kind of function doesn't provide much security, as you can keep guessing the names in the text file until you find a valid one, or if you can get your hands on the text file itself you can just look the names up. For actual login code, it's probably best to use some kind of login library that handles the security details for you.

Simple Python Excel password crack - Brute Force

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.

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

if not working for nth line in document

I wanted to make a simple login system with python 3.5. what it does is opens a document with usernames and passwords inside it. the document has a username on the first line, and the password for that user on the second line. this continues through the document, resulting in usernames on every odd line, and passwords on every even line. the loop goes through all 20 lines (for 10 users) and takes every odd line as a username, and every even line as a password. it goes through, and checks if the username and password are correct. for some reason, it does not work, it just asks to input username, and input password, and doesnt return anything. it is opening the document fine, as it works when i print out the usernames and passwords.
username = input('please enter your username')
password = input('please unter your password')
for i in range(0,20,2):
text_file = open('users.txt','r')
database = text_file.readlines()
if username == database[i] and password == database[i+1]:
print('login accepted')
else:
if username == database[i] and password != database[i+1]:
print('incorrect password')
text_file.close()
The likely problem has more to do with string stripping than anything. Chances are you have a text file like:
myusername
mypassword
otherusername
otherpassword
and when you're reading it you get:
["myusername\n", "mypassword\n", ... ]
You can most likely fix this just by using str.strip on each line read from the file.
However you have a couple more logic errors than this. Here's one:
for i in range(0, 20, 2):
text_file = open(...)
database = text_file.readlines()
# you really want to open the file and read from it EVERY SINGLE LOOP??
and also:
if username == database[i] or password == database[i+1]:
# log in if your password is ANYONE'S password, or if your username
# is ANYONE'S username.
In the grand scheme of things, you should be pre-processing the text file to create a dictionary of key-value pairs.
database = {} # empty dict
with open('path/to/textfile.txt') as inf:
while True:
try:
username = next(inf)
password = next(inf)
except StopIteration:
break
else:
database[username.strip()] = password.strip()
username_in = input("What's your username? ")
password_in = input("What's your password? ")
if database[username_in] == password_in:
# login successful
But REALLY, you should never ever ever ever be storing passwords in plain text for any reason whatsoever. Good lord, man, do some research on password storage! :)
Answer by Adam Smith is great.
I can only add that the line
if database[username_in] == password_in:
might cause a KeyError if there is no such username in your database. You might want to either check if username exists in database before checking passwords or wrap password check in the try except block or use dict.get(key, default) method to get the password from your database
Here some code:
# Pre check
if username_in in database.keys():
if database[username_in] == password_in:
# ...
else:
# No such username in database
# try .. except
try:
if database[username_in] == password_in:
# ...
except KeyError:
# No such username in database
# get with default
# if no default is specified, default is None
if database.get(username_in) == password_in:

Categories

Resources