RarFile Python Module - python

I am trying to make a simple bruteforcer for rar files. My code is...
import rarfile
file = input("Password List Directory: ")
rarFile = input("Rar File: ")
passwordList = open(file,"r")
for i in passwordList:
try :
rarfile.read(rarFile, psw=i)
print('[+] Password Found: '+i)
except Exception as e:
print('[-] '+i+' is not a password ')
passwordList.close()
I think this has to do with my use of the module, because when I input a password list that I am 10000% sure contains the password to the rarFile, it prints the exception.

The real problem here is that you are catching all exceptions, not just the one you want. So use except rarfile.PasswordRequired: That will show you that the error is not a missing password. Instead there is no function read in the rarfile module.
Have a look at some Documentation. Rar encryption is per file, not per archive.
You need to create a object from the RarFile class and try the password on each file in the archive. (or just the first if you know that is encrypted)
import rarfile
file = input("Password List Directory: ")
rarFilename = input("Rar File: ")
rf = rarfile.RarFile(rarFilename)
passwordList = open(file,"r")
first_file = next(rf.infolist)
for i in passwordList:
password = i.rstrip()
try:
rf.open(first_file, psw=password)
print(password, "found")
except rarfile.PasswordRequired:
print(password,"is not a password")
When you open and read lines from a file, the "new line" character is kept
at the end of the line. This needs to be stripped from each line.
for i in passwordList:
password = i.rstrip()
try :
rarfile.read(rarFile, psw=password)
print('[+] Password Found: '+password)

Related

Why can't I write to a file despite using "append" mode?

I'm trying to create a basic login system with Python that only includes a username. Here is a snippet of what I'm having issues with.
I added a few usernames to the .txt file and it can find conflicts or login properly but it can't actually register a username. I've done some research and am opening the file in "append" mode and using the write command.
def register():
file1 = open("C:/test/User_Dat.txt", "a")
global username
username = str(input("Please enter a username \n")).lower()
readfile = file1.read()
if username in readfile:
print('The user', username, 'has already been created.')
welcome()
else:
print('The user', username, 'has been created!')
file1.write(username)
file1.write("\n")
file1.close()
login()
But I still get an error like this:
io.UnsupportedOperation: not writable
Why is the file not writable?
EDITED:
You are opening file in reading mode. Fix this line as follows:
file1 = open("C:/test/User_Dat.txt", "r+")
Documentation:
https://docs.python.org/3/library/functions.html#open

Python Zipfile compression method is not supported

The times when this worked were when I used ZIPCrypto compression. It's with AES-256 that it fails. How to get around this please?
I previously had success using the following Python code to open a password protected .zip file created with 7-Zip:
import zipfile
zip_file = zipfile.ZipFile('crack_me.zip')
output_verbose = 1 # increase that for long password list
with open('passwords.txt', 'rb') as password_list:
for index, line in enumerate(password_list):
try:
pwd = line.strip(b'\r\n')
zip_file.extractall(pwd=pwd)
except RuntimeError as e:
print(e)
if index % output_verbose == 0:
print('{}. The {} word not matched.'.format(index + 1, pwd))
else:
print('{}. Wow ! found the password: {}'.format(index + 1, pwd))
break
zip_file.close()
However, for no understandable reason, it has only worked a couple of times out of many attempts. Most times is gives "That compression method is not supported" for the exception.
I've tried deleting, renaming, re-creating the .zip file but no success. It makes no sense to me that it works occasionally.
I tried to simplify the issue as below:
import zipfile
zip_file = zipfile.ZipFile('crack_me.zip')
try:
zip_file.extractall(pwd=b"password")
print('Opened')
except RuntimeError as e:
print(e)
But I get the same exception. I've tried variations of pwd such as bytes("password", "utf-8) and others.
The provided password opens the .zip file when opening with 7-Zip.
What is going on here please?
Try using pyzipper. Here is a sample script:
import pyzipper
password = 'abc'
with pyzipper.AESZipFile('yourdocument.zip', 'r', compression=pyzipper.ZIP_DEFLATED, encryption=pyzipper.WZ_AES) as extracted_zip:
extracted_zip.extractall(pwd=str.encode(password))
In order for the zipfile library to work on a password protected zip you need to have ticked the "Zip legacy encryption" option when setting up the password.

When i try to make python write user input to a txt file, it doesn't

i am learning python, and i wanted to create a little login and register program, that writes the username and the password to a txt file (so that it can be later used), i am currently working on the register function, when i try to write to the txt files it does nothing, i tried doing a with loop, a .flush() and .close() but neither of them saves the info.
Here's my code:
username.write = input ('username > ')
password = open("password.txt", "w")
password.write = input ('password > ')
print('Welcome.')
username.close()
password.close()
What am i missing?
Edit.
Neither 3 of the solutions to the suggested question work for me...
Get your input and store them in two variables and then write them to files:
username = input ('username > ')
password = input ('password > ')
with open('usernames.txt', 'w') as userFile:
userFile.write(username)
with open('passwords.txt', 'w') as passFile:
passFile.write(password)
yourfile.open(filename,'w')
username = input()
password = input()
yourfile.write(username)
yourfile.write(password)
yourfile.close()

Changing a variable when an error occurs without terminating the program

This is my basic code:
fname = input("What is the name of the file to be opened")
file = open(fname+".txt", "r")
message = str(file.read())
file.close()
What I want to do is essentially make sure the file the program is attempting to open exists and I was wondering if it was possible to write code that tries to open the file and when it discovers the file doesn't exist tells the user to enter a valid file name rather then terminating the program showing an error.
I was thinking whether there was something that checked if the code returned an error and if it did maybe made an variable equal to invalid which an if statement then reads telling the user the issue before asking the user to enter another file name.
Pseudocode:
fname = input("What is the name of the file to be opened")
file = open(fname+".txt", "r")
message = str(file.read())
file.close()
if fname returns an error:
Valid = invalid
while valid == invalid:
print("Please enter a valid file name")
fname = input("What is the name of the file to be opened")
if fname returns an error:
Valid = invalid
etc.
I guess the idea is that you want to loop through until your user enters a valid file name. Try this:
import os
def get_file_name():
fname = input('Please enter a file name: ')
if not os.path.isfile(fname+".txt"):
print('Sorry ', fname, '.txt is not a valid filename')
get_file_name()
else:
return fname
file_name = get_file_name()
Going by the rule Asking for forgiveness is better then permission
And using context-manager and while loop
Code :
while True: #Creates an infinite loop
try:
fname = input("What is the name of the file to be opened")
with open(fname+".txt", "r") as file_in:
message = str(file_in.read())
break #This will exist the infinite loop
except (OSError, IOError) as e:
print "{} not_available Try Again ".format(fname)

Am I using pickle correctly?-Python

I am a beginner in Python and therefore am not sure why I am receiving the following error:
TypeError: invalid file: []
for this line of code:
usernamelist=open(user_names,'w')
I am trying to get an input of a username and password, write them to files, and then read them.
Here is the rest of my code:
user_names=[]
passwords=[]
username=input('Please enter a username')
password=input('Please enter a password')
usernamelist=open(user_names,'w')
pickle.dump(userName,usernamelist)
usernamelist.close()
usernamelist=open(user_names,'r')
loadusernames=pickle.load(usernamelist)
passwordlist=open(passwords,'w')
pickle.dump(password,passwordlist)
passwordlist.close()
passwordlist=open(passwords,'r')
loadpasswords=pickle.load(passwordlist)
All answers would be appreciated. Thanks.
Based on your script, this may help. It creates a 'username.txt' and 'password.txt' to store input username and password.
I use python2.7, input behaves differently between in python2.7 and python3.x.
"""
opf: output file
inf: input file
use with instead of .open .close: http://effbot.org/zone/python-with-statement.htm
for naming rules and coding style in Python: https://www.python.org/dev/peps/pep-0008/
"""
import pickle
username = raw_input('Please enter a username:\n')
password = raw_input('Please enter a password:\n')
with open('username.txt', 'wb') as opf:
pickle.dump(username, opf)
with open('username.txt') as inf:
load_usernames = pickle.load(inf)
print load_usernames
with open('password.txt', 'wb') as opf:
pickle.dump(password, opf)
with open('password.txt') as inf:
load_passwords = pickle.load(inf)
print load_passwords

Categories