Python script is unable find registry keys value in HKEY_LOCAL_MACHINE - python

I am continuously facing a problem that my python script is not working on (HKLM: HKEY_LOCAL_MACHINE), i have written a small script in python to search windows registry key values. when i perform searching through CMD it shows the key value that i want, i also noticed that my script works properly on older windows registry vales entries in HKLM but for the new ones it doesn't shows anything.
That's my script written in python to check windows registry values.
from winreg import *
key_to_read = input("Enter Path:") #Path: Software\AbcKey
key = input("HKLM or HKCU:") #Hive Name: HKLM\HKCU
if key == 'HKLM':
a = -2147483646
else:
a = -2147483647
try:
aReg = ConnectRegistry(None, a)
k = OpenKey(aReg, key_to_read)
print("Registry key value found.")
except:
print("Nothing found on the given path.")

If you need to write keys and values to HKLM hive, then you either have to use a completely different language other than Python, or you have to use some other API other than "winreg", as winreg has a major defect that severely limits what you can do in the Registry, that most other languages have no problem with.
It just fails to make them. It also throws a WinError 5, "access denied", but that is misleading and will only lead you down a dark alley. You can even configure your account not only as local admin, but full-on "god mode", elevating your account further to system level access, run as part of the operating system, etc., and still no love.
IF it is "permissions", then it is solely in the calls internally to winreg, and / or security flag options that must be passed in -- NOT your actual account permissions or any special environment configuration settings. However, I have tried every combination (winreg.REG_WRITE / winreg.WIN_ALL_ACCESS / winreg.WIN64, etc), but nothing works when pointed to HKLM hive. Writing to HKCU is just fine. Meanwhile, I can manually modify Registy settings in HKLM, or do it with C# and .NET Framework classes, OR C# with dark, unmanaged C# with direct access to Win32 (advapi32.dll), no problem.
I guess Microsoft just happens to be more friendly with their own languages :)

Related

Win32com interfacing with Reflection Desktop

I run a number of python scripts and programs to aggregate and edit data in Attachmate Extra. My company was on an old version of Attachmate Extra until recently. I'm testing the new version (Reflection Desktop v. 16.2) and my scripts no longer work. I built them with the aid of the helpful advice on this link. I would like to be able to control (scrape, write, etc) screens on the new version.
Here's where I currently am. Running this code creates the a new window:
system = win32com.client.Dispatch("ReflectionIBM.Session")
system.Visible = True
...but then from there I cannot do any of the commands I previously used. Running this, for example
system.MoveCursor(11, 65)
creates a new tab in the emulator that doesn't connect to a session.
I've looked all around the Reflection documentation for an answer. This page led me to believe the old session method is no longer necessary but I'm not sure. I think I'm wrapping the correct object, and the documentation says that legacy commands still work, but I haven't figured out how to link them.
For reference, here are the lines I was using previously to connect to Attachmate:
system = win32com.client.Dispatch("EXTRA.System")
sess0 = system.ActiveSession
Screen = sess0.Screen
Any help is appreciated. I've been scouring the win32com browser for a list commands and looking through the registry to find available classes but I don't know what to look for. Thank you!
EDIT:
I previously used a couple of functions to read, write, and move the cursor around within Attachmate. Example:
def write(screen,row,col,text):
screen.row = row
screen.col = col
screen.SendKeys(text)
write(screen, 10, 65, "test")
Is there a way to get this working again in Reflection?
I still do not know why this works the way it does. In VBA the GetObject method works on "Reflection Workspace" but in python that did not produce any usable attributes that I could find. For python, to get the active session object I had to use EXTRA.System:
from win32com.client.gencache import EnsureDispatch
screen = EnsureDispatch("EXTRA.System").ActiveSession.Screen
From there the code seems generally the same as VBA with
screen.GetString(row, col, len)
screen.PutString(data, row, col)
screen.SendKeys('<PF1>')
for interacting with the host.
After more documentation reading and more trial and error I solved it. "EXTRA.System" is kept for legacy reasons so technically will still work. However, to connect to an active session of Reflection this worked:
system = win32com.client.GetObject('Reflection Workspace')
then to get the active view:
screen = system.GetObject("Frame").SelectedView.Control.Screen
or a specific numbered view:
screen = system.GetObject("Frame").view(1).Control.Screen
The code for interacting with Reflection also has changed and now looks like:
screen.GetText(row, col, len)
screen.PutText2(data, row, col)
screen.SendControlKey(ControlKeyCode)
The documentation for ControlKeyCode does not seem to provide the codes for the control keys. However, you can find the definitions in the Visual Basic Object Browser that comes with Reflection. In Reflection, on the macros tab, click Visual Basic, then press F2 and search for ControlKeyCode. A list of them should show up. For example, mine shows ControlKey_F1=10.
screen.SendKeys("N")
can still be used to send individual key strokes such as the N key but SendControlKey seems to have replaced the command keys such as Enter, Page Up, and the Function keys.
Have launched python package py_reflection in this regards,
How to start:
Install the package via pip:
py -m pip install py_reflection
Run the package (Run the commands below in terminal):
python
>>>from py_reflection import app
>>>app.run()
Api Endpoint and their description: ** All of the endpoints have a common parameter view_idx(integer, optional). Use this parameter to toggle between session in emulator.
/send_keys: Use this endpoint to press keys in the emulator. Parameters to pass: text(string), x(integer), y(integer)
/get_text: Use this endpoint to get text from a specific coordinate. Parameters to pass: x(integer), y(integer)
/press_key: Use this endpoint to press special control keys: Parameters to pass: control_key(string all in caps). Available control keys: 'F1','F2','F3','F4','F5','F6','F7','F8','F9','F10','F11','F12','F13','F14','F15','F16','F17','F18','F19','TAB','DELETE','LEFT','DOWN','UP','RIGHT','PAGEUP','PAGEDOWN','CLEAR','END','ENTER'
/get_text_coordinates: Use this endpoint to get coordinates of text present in emulator screen. Parameters to pass: text(string), total_row_count(integer, optional), total_column_count(integer, optional)
/check_text_present: Use this endpoint to check if given text present in emulator screen. Parameters to pass: text(string), total_row_count(integer, optional), total_column_count(integer, optional)
/move_cursor: Use this endpoint to move cursor to specified coordinate. Parameters to pass: x(integer), y(integer)
/get_view_count: Use this endpoint to get number of sessions opened in emulator.
More info at pypi.org

Would allowing user input to python's __import__ be a security risk?

Say I create a simple web server using Flask, and allowing people to query certain things that I modulated in different python files, using the __import__ statement, would doing this with user supplied information be considered a security risk?
Example:
from flask import Flask
app = Flask(__name__)
#app.route("/<author>/<book>/<chapter>")
def index(author, book, chapter):
return getattr(__import__(author), book)(chapter)
# OR
return getattr(__import__("books." + author), book)(chapter)
I've seen a case like this recently when reviewing code, however it didn't feel right to me.
It is entirely insecure, and your system is wide open to attack. Your first return line doesn't limit what kind of names can be imported, which means the user can execute any arbitrary callable in any importable Python module.
That includes:
/pickle/loads/<url-encoded pickle data>
A pickle is a stack language that lets you execute arbitrary Python code, and the attacker can take full control of your server.
Even a prefixed __import__ would be insecure if an attacker can also place a file on your file system in the PYTHONPATH; all they need is a books directory earlier in the path. They can then use this route to have the file executed in your Flask process, again letting them take full control.
I would not use __import__ at all here. Just import those modules at the start and use a dictionary mapping author to the already imported module. You can use __import__ still to discover those modules on start-up, but you now remove the option to load arbitrary code from the filesystem.
Allowing untrusted data to direct calling arbitrary objects in modules should also be avoided (including getattr()). Again, an attacker that has limited access to the system could exploit this path to widen the crack considerably. Always limit the input to a whitelist of possible options (like the modules you loaded at the start, and per module, what objects can actually be called within).
More than being a security risk, it is a bad idea e.g. I could easily crash your web app by visiting the url:
/sys/exit/anything
translating to:
...
getattr(__import__('sys'), 'exit')('anything')
Don't give the possibility to import/execute just about anything to your users. Restrict the possibilities by using say a dictionary of permissible imports, as #MartijnPieters as clearly pointed out.

Python, remove password from memory

Im storing some user raw_input as a variable in Python 2.7, the issue is that this is sensitive as it is the encryption passphrase for a cryptocurrency wallet.
Therefore I want to ensure that once the Python script is completed, there is no trace of the passphase left anywhere on the system.
Where passphrase is the variable, is this at the end of the program:
del passphrase
good to utterly remove all traces?
No del xxx or implicit deletion (leaving the current scope) may not be enough to hide the previously stored value. Note that this may crucially depend on your OS and your Python implementation.
However I would advise not to roll your own security systems unless you really, really know what you're doing but rather search an already existing solution for whatever it is you want to do and use that. For example I'm not sure if either raw_input or input are suitable for cryptographical needs.
You may get additional help in Information Security StackExchange.

DAO connection to Access .accdb database using Python

I’m having an issue with one of my Python apps that has been working fine with an older .mdb Access Databases. After converting to Access 2010 and the file being converted to the new .accdb format nothing seems to be working. I do have the 32 bit Access version loaded on a new 64 bit Win 7 OS. I believe my problem is with the first two lines of my code. I believe I need to update them to reference the "Microsoft Office 14.0 Access Database Engine Object" but I’m unclear how to do this. Can I get some help on this one? I have searched high and low for DAO info regarding this scenario but to avail.
import win32com.client
engine = win32com.client.Dispatch("DAO.DBEngine.36")
db=engine.OpenDatabase(r"c:\temp\Tracker.accdb")
table = db.OpenRecordset("select * from Event_Log")
print table.RecordCount
An answer probably too late for the OP, but in case anyone else stumbles in here looking for an answers in the area of DAO with Python:
The OP is correct that the immediate issue lies with the string used in the Dispatch method. Office 2010 (Office 14?) installs "DAO.DBEngine.120", which is I think the earliest version that works with .accdb files. In general, one can research this issue by using RegEdit to search the registry for the substring "DAO.DBEngine", and see what components have been registered that add a version number to that string.
It should also be noted that the 32/64 bitness of the version of python to be used needs to match the 32/64 bitness of the DAO version, which in turn matches the 32/64 bitness of Office that installed it.
A further note: If you are using an IDE and make use of autocomplete, it's useful to generate and import a module corresponding to the DAO API. This can be done by running the MakePy utility (in the PythonWin program) on the Library in question, here "Microsoft Office 14.0 Access Database Engine Object Library". This produces a module file in site-packages\win32com\gen_py\, with a long GUID name... you can rename it to "DAO_120-64.py" or somesuch. Then add the gen_py directory to the Python path (or add a .pth file in sitepackages), so that import can find the new module.
Once imported, you can do whatever your IDE recognizes to associate a type with variables for DAO.Database, DAO.Recordset, and so on.
Additionally, the generated DAO module is a useful reference for what objects, methods, properties and constants are available. Possibly a more helpful reference is to simply open an Excel/Word/Access VBA project, Reference (import) this same library, and use the VBA Object browser on it.
In general, any tutorials or articles about using DAO in Access (in VBA or VB) will describe the objects, methods and properties involved in common operations, which can be transcribed almost verbatim into python. The main difference is that in the python version, some of the COM "default method" mechanisms don't work. So, for example, the VBA
MyRecordset("SomeColumn") = "NewValue"
... corresponds in python to:
MyRecordset.Fields("SomeColumn").Value = "NewValue"
Hope that helps.

Writing/Reading arrays of Data in Open Office using Python. Anyone have any example code?

So I have written a class that makes it extremely easy to interface with either Excel or Gnumeric using Python, and would like to extend the class to include Open Office as well. I could do this in 30 minutes if I just had the ability to do the following:
Set a single value on an arbitrary
sheet and workbook
Get a single value
on an arbitrary sheet and workbook
If these are slow/there is a way to do the following, I also need to be able to:
set/get an array '''
set/get a matrix '''
ALSO, the ability to create and rename sheets would be great.
This is a shoutout if anyone has worked on this before. If they give me the information, I will reference them at the top of the file
My project can be found here: https://sourceforge.net/projects/pyworkbooks/ and I encourage you to check it out.
As a matter of fact, to acess OpenOffice or LibreOffice via Python one has to go through an absolutely opaque amount of boiler plate inherited from the StarOffice times - never properly documented (one feels) or simplified since then.
I had once lectured on this subject, and I took almot 40 minutes, just to retrieve the parts of my lecture to set up the example bellow.
On the other hand it just worked with the latest LibreOffice version - 3.3 - I am confident it works for OpenOffice as well (but I would not advice anyone to stick to OpenOffice, it is an Oracle dead end at this point)
The example bellow use the slow method of connecting to a running LibreOffice instance from the "outside". This is extremely slow - you will have to refer to the documentation on how to make it work as a macro from "within" the program, for better performance. (it is really slow in this way).
However, this method allows you to explore the methods available to developers using a Python terminal and introspection.
The first poorly documented part is that you have to start Open/LibreOffice with:
soffice "-accept=socket,host=0,port=2002;urp;"
For connections to be accepted. Then, create a new spreadsheet through its interface
and with the python interpreter that comes with the Office Suite run the following code
(either interactively or as a script):
import uno
import socket # only needed on win32-OOo3.0.0
# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()
# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext )
# connect to the running office
ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
smgr = ctx.ServiceManager
# get the central desktop object
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
# access the current writer document
model = desktop.getCurrentComponent()
try:
sheets = model.getSheets()
except Exception:
raise TypeError("Model retrived was not a spreadsheet")
sheet1 = getattr(sheets, sheets.ElementNames[0])
# At this point, you can use "dir" to check the methods and
# attributes available for the sheet
# the methots "getCellByPosition, to retrieve a cell object,
# which has "getFormula" and "setFormula"
# methods.
for i in xrange(10):
for j in xrange(10):
cell = sheet1.getCellByPosition(i, j)
cell.setFormula(str(i * j))
c1 = sheet1.getCellByPosition(1,1)
As you can see, the connecting part of this is boilerplate I got somewhere else years ago, and I doubt any living person could find any rationale in such stuff.
Once you get down to the "sheets" object, though, the attributes and methods on the object start to make sense.
There is a complete developer manual online, that even could allow one to understand the connection part:
http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide
The inter-process API for connecting to LibreOffice (and also OpenOffice and StarOffice) is called UNO. It is documented at the LibreOffice API documentation site.
As jsbueno says, it expects that a daemon is running to communicate with. The command-line arguments to the ‘soffice’ command starting the daemon determine what host and port values you need to supply in your UNO calls.
You could also try ezodf This was the best python odf library I found
You can use pyoo. Here is my answer to similar question https://stackoverflow.com/a/27082610/886607

Categories