Cracking a PDF File using Python 3 - python

I'm currently completing an assignment which requires me to create a script to crack a password from a PDF file, I already have a list which contains the password within, I am having issues when prompt to enter the path to the file and met with an Name not define error, please mind I am a novice to coding.
file = raw_input('Path: ')
wordlist = 'wordlist.txt'
word =open(wordlist, 'r')
allpass = word.readlines()
word.close()
for password in allpass:
password = password.strip()
print ("Testing password: "+password)
instance = dispatch('pdf.Application')
try:
instance.Workbooks.Open(file, False, True, None, password)
print ("Password Cracked: "+password)
break
except:
pass
When the program is running, it attempts the first password from the list then proceeds to crash.
python Comsec.py
Path: /home/hall/Desktop/comsec121/examAnswers.pdf
Testing password: 123456
Traceback (most recent call last):
File "Comsec.py", line 11, in <module>
instance = dispatch(&apos;pdf.Application&apos;)
NameError: name &apos;dispatch&apos; is not defined
Please excuse my formatting on this website, I am trying my best to help you understand my issue!
Thanks in advance!

This error means that inside your Python script there is no object or function with the name dispatch. You would get that same error if you tried:
instance = this_is_a_function_that_has_not_been_defined('pdf.Application')
Typically, this function should be defined in a Python module. To access it, at the top of your code you should have some import statement like this:
from aBeautifulModuleForPDFs import dispatch
That module will be providing you the missing dispatch function. Checking in Google, I suggest you to try with module pywin32. Install it (run pip install pywin32 in a terminal) and add this line at the beginning of the code:
from win32com.client import Dispatch as dispatch

Related

Bad Request at Authorization Code Flow Spotify

I am trying to built a script that creates a playlist on a user's spotify profile. To learn spotipy I decided to try the examples they have on the documentation page.
The code I run is:
import sys
import spotipy
import spotipy.util as util
token = util.prompt_for_user_token('idxxx',
'user-library-read',
client_id='axxx',
client_secret='Bxxx',
redirect_uri='http://localhost')
scope = 'user-library-read'
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print("Usage: %s username" % (sys.argv[0],))
sys.exit()
token = util.prompt_for_user_token(username, scope)
if token:
sp = spotipy.Spotify(auth=token)
results = sp.current_user_saved_tracks()
for item in results['items']:
track = item['track']
print(track['name'] + ' - ' + track['artists'][0]['name'])
else:
print("Can't get token for", username)
The problem occurs when i run the code. I get redirected on my redirect uri and after i paste it back on the terminal i get this:
Traceback (most recent call last):
File "spot01.py", line 9, in <module>
redirect_uri='http://localhost')
File "/home/user/.local/lib/python3.6/site-packages/spotipy/util.py", line 92, in prompt_for_user_token
token = sp_oauth.get_access_token(code, as_dict=False)
File "/home/user/.local/lib/python3.6/site-packages/spotipy/oauth2.py", line 434, in get_access_token
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
I tried to access the oauth2.py from the File Manager and the terminal but it says that this repository does not exist. Also i tried to install spotipy through the github page they have where the neccessary files exist but still nothing.
Any ideas?
Thanks a lot.
I solved the problem by downloading the required files from here https://github.com/plamere/spotipy/tree/master/spotipy
Then I changed some things inside of each .py file and i run every code I wanted to inside there. It must be another more fancy solution but this one worked for me.
Oh before running any command I typed this set of commands on the terminal:
$ bash
$ export SPOTIPY_CLIENT_ID='xxx'
$ export SPOTIPY_CLIENT_SECRET='xxx'
$ export SPOTIPY_REDIRECT_URI='http://localhost/'
where xxx you put your credentials and at the refirect uri your localhost or your github profile link.

Python in ArcGIS

I wrote the following code, which results in an error and I don't know how to fix it to work.
The code is:
# Name: ClipGDBtoNewGDB.py
# Description: Take an input GDB, create a list, iterate through each
feature class, clipping it and writing it to a new GDB.
# Author: tuilbox
# Import system modules
import arcpy, os
from arcpy import env
# Set workspace
env.workspace = arcpy.GetParameterAsText(0)
arcpy.env.overwriteOutput=True
# Set local variables
fclist = arcpy.ListFeatureClasses()
clip_features = arcpy.GetParameterAsText(1)
output_directory=arcpy.GetParameterAsText(2)
xy_tolerance = ""
outgdb=os.path.join(output_directory, arcpy.GetParameterAsText(3))
if not arcpy.Exists(outgdb):
arcpy.CreateFileGDB_management(output_directory,
arcpy.GetParameterAsText(3))
# Execute Clip within for loop
for fc in fclist:
arcpy.Clip_analysis(fc, clip_features, os.path.join(outgdb, fc))
The error is: Traceback (most recent call last):
File "F:/GIS_Joseph/Lab10_Joseph/ClipGDBtoNewGDB.py", line 17, in <module>
arcpy.CreateFileGDB_management(output_directory, arcpy.GetParameterAsText(3))
File "C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py", line 18878, in CreateFileGDB
raise e
ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000735: File GDB Location: Value is required
ERROR 000735: File GDB Name: Value is required
Failed to execute (CreateFileGDB).
Any help would be appreciated. Thank you.
With this type of question it would be helpful to let us know what parameters you are passing into your script. Have you passed a valid parameter in position 3? Use arcpy.AddMessage to double check what value you are attempting to pass to arcpy.CreateFileGDB_management.

Dictionary reference keeps throwing an unsolved reference

I am building a mock terminal-like program using python, and am trying to build a login system for it.
My directory setup, after going through multiple revisions, eventually came out to look like this:
pythonapp-harlker/
__init__.py
loginCheck.py
main.py
userlist.py
__init__.py is empty, and main.py's main code chunk looks like this:
from loginCheck import *
loginFunc = Login()
loginFunc.login()
if loginFunc.login().checkPass == True:
print("Welcome %s!" % (username))
Importing loginCheck returns no error, so naturally, I looked at loginCheck.py.
import sys, platform, importlib
import hashlib
from userlist import *
class Login:
def login(self):
username = input("Username: ")
password = input("Password: ")
password = str.encode(password)
password = str(hashlib.md5(password).hexdigest())
if username in users:
userPassAndIndex = users.get(username)
if password == userPassAndIndex[0]:
checkPass = True
value = userPassAndIndex[1]
else:
self.login()
else:
self.login()
Looking at a debugger, it keeps telling me that loginCheck.py is unable to import a dictionary from userlist.py.
userlist.py
users = {
'localAdmin10': ["086e717a4524329da24ab80e0a9255e2", 0],
'orlovm': ["505ec2b430fa182974ae44ede95ca180", 1],
'testUser10': ["90e611f269e75ec5c86694f900e7c594", 2],
'torradiRemote': ["0b841ebf6393adac25950a215aecc3d1", 3],
}
Additionally, while running the python code (from main.py), the code seems unable to detect if the input username and passwords are correct.
I've looked at tons of stackOverflow pages and external sources but I'm at a kind of "programmer's block" now.
Your code runs fine on Python 3+, and breaks on Python 2.7, let me explain why:
the input function you want to use with Python 2.7 is raw_input, not input. The input function in Python 2.7, evaluates the user input as a Python expression, so in your case, can't find it and send an exception
raw_input was renamed input starting Python 3.0
So to sum it up, you just have to pick the right function depending on which version of Python you'd like to use. raw_inputfor Python 2.7, input for Python 3.

Error when running on python idle

Update: I deleted the .dat file where everything is saved and now it works again. I would like some input on what might have caused it anything will help. I just want to know how to prevent it in the future.
Everything work perfectly yesterday using python idle.
Today I edited my program in pycharm to add a delete account feature. Everything runs on pycharm I can receive accounts, delete accounts, and create them. I decided to test it on idle because most computers I work on I can't download pycharm and I keep getting this error:
Traceback (most recent call last):
File "E:\Passwords\password.py", line 140, in ?
program_start()
File "E:\Passwords\password.py", line 137, in program_start
all_accounts()
File "E:\Passwords\password.py", line 93, in all_accounts
klist = f.keys()
File "C:\Python24\lib\shelve.py", line 98, in keys
return self.dict.keys()
File "C:\Python24\lib\bsddb\__init__.py", line 244, in keys
return self.db.keys()
DBRunRecoveryError: (-30978, 'DB_RUNRECOVERY: Fatal error, run database recovery -- accounts.dat: pgin failed for page 1')
I decided to run on pycharm again and against all odds it still ran perfectly no errors. What does this error mean? How can I fix it? And what causes it?
Also I have tried to run it on multiple computers to see if python idle would run it and none of them would.
Did the delete function ruin it?
def delete_account():
"""Deletes an account"""
print'\n'
account = raw_input("What account do you want to delete?: ")
f = shelve.open("accounts.dat")
if account in f:
confirm_deletion = raw_input("Are you sure you want to delete " + account + "?: ")
if confirm_deletion.lower() in ('yes', 'y'):
del f[account]
print "This account has been deleted."
else:
print "Canceled... "
else:
print "I'm sorry we could not find any account related to " + account
print '\n'
f.close
Or did pycharm cause this error?
Check your python version
It could be pycharm is using a different version of python as compared to the idle you have installed.

Junos PyEZ Entering Passwords from Python

Hi I am currently learning PyEZ to configure JunOS devices from Python. But I am stuck at a certain problem. I want to be able to create new users through Python but I can't figure out how to enter passwords with python. I have tried many different things but can't seem to make it work. Any advice would be appriciated
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
dev = Device(host='192.168.56.2', user='root', password='Juniper1')
dev.open()
cu=Config(dev)
new_User='set system login user Read class read-only authentication plain-text-password'
pass_New='Read1234'
pass_Repeat='Read1234'
cu.load(new_User, format='set')
cu.load(pass_New,format='set')
cu.load(pass_Repeat,format='set')
And Here is the Error
Traceback (most recent call last):
File "/home/oscar/PycharmProjects/Junos/HelloWorld.py", line 18, in <module>
cu.load(pass_New,format='set')
File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/utils/config.py", line 377, in load
return try_load(rpc_contents, rpc_xattrs)
File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/utils/config.py", line 343, in try_load
raise ConfigLoadError(cmd=err.cmd, rsp=err.rsp, errs=err.errs)
jnpr.junos.exception.ConfigLoadError: ConfigLoadError(severity: error, bad_element: Read1234, message: unknown command)
When you're using PyEZ to apply configuration, the module is expecting atomic configuration blobs; it is not just a replacement for the interactive CLI shell.
The error you are seeing is because you're sending pass_New 'Read1234' when Junos is expecting a specific set command.
To achieve your goal, you'll have to provide the hashed version of the password in your code, and send that as part of the new_User command.
To do this you'll need a hashing module - I use passlib, because crypt() function in OSX spits out hashes that are not compatible with Junos even though they are both BSD variants - go figure.
#!/usr/bin/python
from passlib.hash import md5_crypt
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
username = 'Read'
plaintext = 'toomanysecrets'
dev = Device(host='192.168.56.2', user='root',passwd='Juniper1')
dev.open()
cu=Config(dev)
hashedpassword = md5_crypt.encrypt(plaintext)
set_command = 'set system login user '+username+' class read-only authentication encrypted-password '+hashedpassword
cu.load(set_command, format='set')
dev.commit()
dev.close()
Also to add why we can't do
new_User='set system login user Read class read-only authentication plain-text-password'
pass_New='Read1234'
pass_Repeat='Read1234'
cu.load(new_User, format='set')
cu.load(pass_New,format='set')
cu.load(pass_Repeat,format='set')
I can notice you are trying to type/retupe password using load which is not how load function works. PyEZ in background work on netconf, it's not a screen scrapping. Hence we should not try simulating that.
When we call load it tries to load the config via load-configuration rpc.

Categories

Resources