I am new to Windows Registries and I'm currently trying to get a list of profile names from my Windows registries using Python, but I am not sure what I'm doing wrong. My code is the following:
from winreg import *
def get_profiles():
regKey = OpenKey(HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList')
recent = QueryValueEx(regKey,'DisplayName')[0]
recent_list = []
for subkey in recent:
recent_list.append(QueryValueEx(regKey,subkey)[0])
return recent_list
When I try to run the above, I get the following:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-45-6261438d1fdc> in <module>()
----> 1 l = get_profiles()
<ipython-input-44-f572c6ac8843> in get_profiles()
4 regKey = OpenKey(HKEY_LOCAL_MACHINE,
5 r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList')
----> 6 recent = QueryValueEx(regKey,'DisplayName')[0]
7 recent_list = []
8 for subkey in recent:
FileNotFoundError: [WinError 2] The system cannot find the file specified
I have a hunch that the 'DisplayName' part is wrong, how should I correct it?
You can use EnumKey to get the sub keys of an open registry key.
winreg.EnumKey(key, index)
Enumerates subkeys of an open registry key,
returning a string.
key is an already open key, or one of the predefined HKEY_* constants.
index is an integer that identifies the index of the key to retrieve.
from contextlib import suppress
from winreg import \
(OpenKey,
HKEY_LOCAL_MACHINE,
QueryInfoKey,
QueryValueEx,
EnumKey)
PROFILE_REGISTRY = "SOFTWARE\\Microsoft\\WindowsNT\\CurrentVersion\\ProfileList"
def get_profile_attribute(*, attribute):
profile_to_sub_key_map = {}
with OpenKey(HKEY_LOCAL_MACHINE, PROFILE_REGISTRY) as key:
number_of_sub_keys, _, _ = QueryInfoKey(key) # The `QueryInfoKey` Returns information about a key, as a tuple.
# At the index 0 will be An integer giving the number of sub keys
# this key has.
for index in range(number_of_sub_keys):
sub_key_name = EnumKey(key, index)
# Open the sub keys one by one and fetch the attribute.
with OpenKey(HKEY_LOCAL_MACHINE,
f"{PROFILE_REGISTRY}\\{sub_key_name}") as sub_key:
with suppress(FileNotFoundError):
registry_value, _ = QueryValueEx(sub_key, attribute)
profile_to_sub_key_map.update({sub_key_name: registry_value})
return profile_to_sub_key_map
print(get_profile_attribute(attribute='ProfileImagePath'))
Also note that as per the documentation.
The HKEY object implements __enter__() and __exit__() and thus supports the context protocol for the with statement:
with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
... # work with key
will automatically close key when control leaves the with block.
Related
my code has an error in line 14 saying bytes object has no attribute oid. I am not sure why is it giving me this error.
from Crypto.PublicKey import DSA
from Crypto.Signature import DSS
import random
import os
def generate_dsa_key_pair(bits=1024):
"""Generates a DSA key pair with the given number of bits."""
key = DSA.generate(bits)
return key
def sign_text(text, key):
"""Signs the given text using the given DSA private key."""
signer = DSS.new(key, 'fips-186-3')
**signature = signer.sign(text.encode())**
return signature
def create_p2ms_script(n, m):
"""Creates a P2MS script using the given number of public keys and signatures."""
# Generate N DSA key pairs
keys = [generate_dsa_key_pair() for i in range(n)]
# Select M private keys from the N keys
priv_keys = random.sample(keys, m)
# Generate M signatures using the private keys
signatures = [sign_text("help me", priv_key) for priv_key in priv_keys]
# Create scriptPubKey by concatenating the N public keys
scriptPubKey = b''.join([key.publickey().export_key(format='DER') for key in keys])
# Create scriptSig by concatenating the M signatures
scriptSig = b''.join(signatures)
return scriptPubKey, scriptSig
def save_script_to_file(script, filename):
"""Saves the given script to the specified file."""
with open(filename, 'wb') as f:
f.write(script)
def execute_p2ms_script(scriptPubKey, scriptSig):
"""Executes the given P2MS script by verifying the signatures using the public keys."""
# Split scriptPubKey into individual public keys
pub_keys = [DSA.import_key(key) for key in scriptPubKey.split(b'\x00\x02\x81\x81') if key]
# Split scriptSig into individual signatures
signatures = [sig for sig in scriptSig.split(b'\x00\x02\x81\x81') if sig]
# Check if the number of signatures matches the number of public keys
if len(signatures) != len(pub_keys):
return False
# Verify each signature using the corresponding public key
for i, sig in enumerate(signatures):
verifier = DSS.new(pub_keys[i], 'fips-186-3')
if not verifier.verify("help me ".encode(), sig):
return False
return True
if __name__ == '__main__':
n = int(input("Enter the number of public keys (N): "))
m = int(input("Enter the number of signatures (M): "))
# Create P2MS script
scriptPubKey, scriptSig = create_p2ms_script(n, m)
# Save script
I have tried to hash the object but then my code wouldn't work. I have bolded the line, can someone please explain to me?
for context, my code is meant to replicate a P2MS function.
edit: the full traceback is as follows:
Exception has occurred: AttributeError
'bytes' object has no attribute 'oid'
File ", line 14, in sign_text signature = signer.sign(text.encode())
File , line 26, in <listcomp> signatures = [sign_text("help me", priv_key) for priv_key in priv_keys]
File , line 26, in create_p2ms_script signatures = [sign_text("help me", priv_key) for priv_key in priv_keys]
File , line 66, in <module> scriptPubKey, scriptSig = create_p2ms_script(n, m)
AttributeError: 'bytes' object has no attribute 'oid'
The bytes object is what's returned by text.encode(). It's a UTF-8 encoded string and it does not have an attribute oid.
That is not what DSS.sign(msg_hash) expects. It expects a hash object (which conveniently has an attribute oid), see also PyCryptoDome doc on sign. So a Crypto.Hash object has to be created first as described here:
from Crypto.Hash import SHA256
# ... line 14
hash_object = SHA256.new(data=text.encode())
signature = signer.sign(hash_object)
In your question, you said that passing a hash object did not work. However, that's the proper way to do it. You cannot make a wish on an API and expect things to work. See the API as a contract. It specifies what you need to give and what you get in return.
Make your code run without throwing exceptions. Once you're there and you still encounter errors after passing a hash, please post another question. A thorough explanation of expected and actual behavior beyond "would not work" would also be helpful.
This is my code.
from multiprocessing.managers import BaseManager
from threading import Thread
def manager1():
my_dict = {}
my_dict['key'] = "value"
print(my_dict['key']) #this works
class SyncManager(BaseManager): pass
SyncManager.register('get_my_dict', callable=lambda:my_dict)
n = SyncManager(address=('localhost', 50001), authkey=b'secret')
t = n.get_server()
t.serve_forever()
def get_my_dict_from_the_manager():
class SyncManager(BaseManager): pass
SyncManager.register('get_my_dict')
n = SyncManager(address=('localhost', 50001), authkey=b'secret')
n.connect()
my_dict = n.get_my_dict()
return my_dict
thread1 = Thread(target=manager1)
thread1.daemon = True
thread1.start()
my_dict = get_my_dict_from_the_manager()
print(my_dict.keys()) #this works
print(my_dict['key']) #DOES NOT WORK
On the last line of the script, I try to access a value in the dictionary my_dict by subscripting with a key. This throws an error. This is my terminal output:
value
['key']
Traceback (most recent call last):
File "/home/magnus/PycharmProjects/docker-falcon/app/so_test.py", line 31, in <module>
print(my_dict['key'])
TypeError: 'AutoProxy[get_my_dict]' object is not subscriptable
Process finished with exit code 1
It seems the AutoProxy object sort of behaves like the dict it is supposed to proxy, but not quite. Is there a way to make it subscriptable?
The problem is that the AutoProxy object does not expose the __getitem__ method that a dict normally has. An answer to my similar question allows you to access items by their key: simply replace print(my_dict['key']) with print(my_dict.get('key'))
I am trying to retrieve a tags using boto3 but I constantly run into the ListIndex out of range error.
My Code:
rds = boto3.client('rds',region_name='us-east-1')
rdsinstances = rds.describe_db_instances()
for rdsins in rdsinstances['DBInstances']:
rdsname = rdsins['DBInstanceIdentifier']
arn = "arn:aws:rds:%s:%s:db:%s"%(reg,account_id,rdsname)
rdstags = rds.list_tags_for_resource(ResourceName=arn)
if 'MyTag' in rdstags['TagList'][0]['Key']:
print "Tags exist and the value is:%s"%rdstags['TagList'][0]['Value']
The error that I have is:
Traceback (most recent call last):
File "rdstags.py", line 49, in <module>
if 'MyTag' in rdstags['TagList'][0]['Key']:
IndexError: list index out of range
I also tried using the for loop by specifying the range, it didn't seem to work either.
for i in range(0,10):
print rdstags['TagList'][i]['Key']
Any help is appreciated. Thanks!
You should iterate over list of tags first and compare MyTag with each item independently:
something like that:
if 'MyTag' in [tag['Key'] for tag in rdstags['TagList']]:
print "Tags exist and.........."
or better:
for tag in rdstags['TagList']:
if tag['Key'] == 'MyTag':
print "......"
I use function have_tag to find tag in all modul in Boto3
client = boto3.client('rds')
instances = client.describe_db_instances()['DBInstances']
if instances:
for i in instances:
arn = i['DBInstanceArn']
# arn:aws:rds:ap-southeast-1::db:mydbrafalmarguzewicz
tags = client.list_tags_for_resource(ResourceName=arn)['TagList']
print(have_tag('MyTag'))
print(tags)
Function search tags:
def have_tag(self, dictionary: dict, tag_key: str):
"""Search tag key
"""
tags = (tag_key.capitalize(), tag_key.lower())
if dictionary is not None:
dict_with_owner_key = [tag for tag in dictionary if tag["Key"] in tags]
if dict_with_owner_key:
return dict_with_owner_key[0]['Value']
return None
I'm running the following:
for server in server_list:
for item in required_fields:
print item, eval(item)
There is a possibility that some keys may not exist, but worse it's represented on a parent key not the one I'm scanning for.
So I'm scanning the json for the following key:
server['server_management']['server_total_cost_of_ownership']['description']
Which doesn't exist but it's actually the parent that is null:
server['server_management']['server_total_cost_of_ownership']
How do I write my code to account for this? It's not giving a key error. Right now I get the following traceback:
Traceback (most recent call last):
File "C:/projects/blah/scripts/test.py", line 29, in <module>
print item, eval(item)
File "<string>", line 1, in <module>
TypeError: 'NoneType' object has no attribute '__getitem__'
Full code:
import csv
import json
import os
import requests
import sys
required_fields = ["server['server_name']","server['server_info']['asset_type']['display_name']",
"server['asset_status']['display_name']", "server['record_owner']['group_name']",
"server['server_management']['server_total_cost_of_ownership']['description']",
"server['server_management']['primary_business_owner']['name']",
"server['environment']['display_name']", "server['is_virtual']",
"server['managed_by']['display_name']", "server['server_info']['billable_ibm']",
"server['server_info']['billing_sub_type']['display_name']",
"server['server_info']['serial_number']", "server['location']['display_name']",
"server['inception_date']", "server['server_info']['decommission_date']" ]
# Query API for all servers
def get_servers_info():
servers_info = requests.get('url')
return servers_info.json()
def get_server_info(sid):
server_info = requests.get('url')
return server_info.json()
server_list = get_servers_info()
for server in server_list:
for item in required_fields:
print item, eval(item)
In fact you should avoid eval. After the json load since you know the key name, you can use a list to go deeper in the tree.
server['server_management']['primary_business_owner']['name']" => ["server_management', 'primary_business_owner', 'name']
Here a snippet for a json validation against a list of required fields.
data={
"d": {
"p":{
"r":[
"test"
]
}
},
"a": 3
}
def _get_attr(dict_, attrs):
try:
src = attrs[:]
root = attrs.pop(0)
node = dict_[root]
null = object()
for i, attr in enumerate(attrs[:]):
try:
node = node.get(attr, null)
except AttributeError:
node = null
if node is null:
# i+2 pop and last element
raise ValueError("%s not present (level %s)" % (attr, '->'.join(src[: i+2])))
return node
except KeyError:
raise ValueError("%s not present" % root)
# assume list of required field
reqs = [
["d", "p", "r"],
["d"],
["k"],
["d", "p", "r", "e"],
]
for req in reqs:
try:
_get_attr(data, req)
except ValueError as E:
print(E)
# prints
# k not present
# e not present (level d->p->r->e)
Ignoring the context of the code and not understanding the use of eval here, the way to do this is to use .get() and seed it with reasonable defaults.
For example:
server['server_management']['server_total_cost_of_ownership']['description']
Can be:
server.get('server_management', {}).get('server_total_cost_of_ownership', {}).get('description', '')
Then if any of the keys do not exist you will always get back an empty description ''.
Your problem here is totally unrelated to using eval[1]. The exception you get is the same as if the code would have been there directly. What you are running (via eval) is:
a = server['server_management']
b = a['server_total_cost_of_ownership']
c = b['description']
Yet, b is None, so resolving it to c will fail. Like a KeyError, you can also catch a TypeError:
for server in server_list:
for item in required_fields:
try:
print item, eval(item)
except TypeError:
print("Guess you're lucky you didn't include a fork bomb in your own code to eval.")
You may of course alternatively pass, print the offending item, open a browser to some page or do whatever error handling is appropriate given your input data.
[1] While not bickering around, I've made a new answer that works without eval. You can use precisely the same error handling:
for server in server_list:
for item in required_fields:
value = server
for key in parse_fields(field):
try:
value = value[key]
except TypeError:
print("Remember Kiddo: Eval is Evil!")
break
else: # for: else: triggers only if no break was issued
print item, value
I am creating a .png barcode from an alpha numerical value. I am using Python and the pyBarcode module. The problem is that, when I use code39, it adds a random digit to the end. Other barcode formats I tested seems to give the same problem.
Here is my code snippet
unique_filename = uuid.uuid4()
barcode_writer = ImageWriter()
ean = barcode.get('code39', "Testing-One-two-1-2",barcode_writer)
filename = ean.save(BARCODE_DIR +str(unique_filename))
And the created .png:
Non-OP Edit: Link to image is now broken.
Hope someone can assist me.
Thanks
Looking at the source code for pyBarcode init function on line 57 the barcode.get() function calls:
return barcode(code, writer)
So it creates a barcode with the parameters code and writer set.
In the codex.py file on line 52, the code39 class is created with the checksum parameter True by default:
def __init__(self, code, writer=None, add_checksum=True):
And as per lnmx you have to explicitly set the checksum off if you don't want it.
Peter M is right, the extra character is a checksum. You can omit it by specifying add_checksum=False:
ean = barcode.get('code39', "Testing-One-two-1-2", barcode_writer, add_checksum=False)
ref: http://pythonhosted.org/pyBarcode/barcode.html
I tried using the parameter 'add_checksum=False' with 'barcode.get()' and it raised an error:
barcode_writer = ImageWriter()
ean = barcode.get('code39', "Testing-One-two-1-2",barcode_writer, add_checksum=False)
TypeError Traceback (most recent call
last) in ()
1 barcode_writer = ImageWriter()
----> 2 ean = barcode.get('code39', "Testing-One-two-1-2",barcode_writer, add_checksum=False)
TypeError: get() got an unexpected keyword argument 'add_checksum'
So I found on module reference page (https://pythonhosted.org/pyBarcode/codes.html) that you can specify the type of barcode, using it as a class and then you can provide the paramenter 'add_checksum=False'.
barcode_writer = ImageWriter()
ean = barcode.codex.Code39( "Testing-One-two-1-2", barcode_writer, add_checksum=False)
unique_filename = uuid.uuid4()
filename = ean.save(unique_filename)