Skip to content

Instantly share code, notes, and snippets.

@kubinka0505
Created May 12, 2023 15:52
Show Gist options
  • Save kubinka0505/7c25c8c1f222a227e560f27c72a0a33e to your computer and use it in GitHub Desktop.
Save kubinka0505/7c25c8c1f222a227e560f27c72a0a33e to your computer and use it in GitHub Desktop.
Script that allows batch values setting into the Windows Registry editor with administrator privileges.
__doc__ = """Registry Setter
Script that allows batch values setting into the
Windows Registry editor with administrator privileges.
Can be used as standalone `Registry_Set` function
(with modules) or as an ArgumentParser one.
---
Warning:
Requires "pyuac" module! (`pip install pyuac`)
"""
import sys
import pyuac
import ctypes
import winreg
from os import *
from argparse import ArgumentParser, HelpFormatter, SUPPRESS
del open
#-=-=-=-=-=-=-=-=-=-=-#
__name__ = open(__file__).readlines()[0].strip('"').strip("\n")
__author__ = "kubinka0505"
__credits__ = __author__
__version__ = "1.0"
__date__ = "12.05.2023"
#-=-=-=-=-=-=-=-=-=-=-#
# Non-NT OS handling
if name != "nt":
msgbox.showerror("Error", "Windows Only!")
exit()
# Run as Admin
if not pyuac.isUserAdmin():
pyuac.runAsAdmin()
#-=-=-=-=-=-=-=-=-=-=-#
# Main Class
class Registry:
Values = {
"Keys": {
"HKCR": "HKEY_CLASSES_ROOT",
"HKCU": "HKEY_CURRENT_USER",
"HKLM": "HKEY_LOCAL_MACHINE",
"HKU": "HKEY_USERS",
"HKCC": "HKEY_CURRENT_CONFIG"
},
"Types": [
"SZ", "Multi SZ", "Expand SZ",
"Binary", "DWord", "QWord",
]
}
def __init__(self, Path: str):
Main_Key = Path.replace("/", sep).split(sep)
for Short, Extended in self.__class__.Values["Keys"].items():
Main_Key[0] = Main_Key[0].upper().replace(Short, Extended)
self.DisplayKey = sep.join(Main_Key)
self.Key = getattr(winreg, Main_Key[0]), sep.join(Main_Key[1:])
def set(self, Name: str = None, Value: str = None, Type: str = "SZ") -> tuple:
"""Set the value. """
__DefaultType = "SZ"
if not Type:
Type = __DefaultType
for Value_Types in self.__class__.Values["Types"]:
Type = Type.upper().strip().replace(" ", "_").lstrip("REG_")
Value_Types = Value_Types.upper().replace(" ", "_")
if Type == Value_Types:
DisplayType = "REG_" + Type
Type = getattr(winreg, DisplayType)
break
if not isinstance(Type, int):
Type = __DefaultType
#-=-=-=-#
winreg.CreateKey(*(self.Key))
with winreg.OpenKey(*self.Key, 0, winreg.KEY_WRITE) as Registry_Key:
winreg.SetValueEx(Registry_Key, Name, 0, Type, Value)
return self.DisplayKey, Name, Value, DisplayType
#-=-=-=-=-=-=-=-=-=-=-#
# Argument Parser
Parser = ArgumentParser(
prog = '{0} "{1}.{2}"'.format(
path.basename(sys.executable).split(".")[0],
*(path.basename(__file__).split("."))
),
description = __doc__.split("\n\n")[1].replace("\n", " "),
add_help = 0,
allow_abbrev = 0,
formatter_class = \
lambda prog, size = 999: \
HelpFormatter(
prog, width = size,
max_help_position = size
)
)
Required = Parser.add_argument_group("Required arguments")
Optional = Parser.add_argument_group("Optional arguments")
#-=-=-=-=-=-#
Required.add_argument("-i", "--path", metavar = '"Path"', type = str, help = 'Full path of the desired registry key')
Required.add_argument("-a", "--name", metavar = '"Name"', type = str, help = 'Registry key name')
Required.add_argument("-b", "--value", metavar = '"Value"', help = 'Registry key value')
Optional.add_argument("-t", "--type", metavar = '"REG_Type"', type = str, help = 'Value type. Default is "REG_SZ"')
Optional.add_argument("-h", "--help", action = "help", help = "Shows this message")
#-=-=-=-#
for Argument in Parser._actions:
if not Argument.help.endswith((SUPPRESS, "!")):
Argument.help += "."
args = Parser.parse_args()
#-=-=-=-=-=-=-=-=-=-=-#
## Standalone Usage (Comment lines: 30, 139, 140)
# Registry_Key = Registry("HKEY_CLASSES_ROOT/*/!_Foo")
# _ = Registry_Key.set("Foo", "Bas", "SZ")
## ArgParse Usage (Admin in shell required!!!)
Registry_Key = Registry(args.path)
_ = Registry_Key.set(args.name, args.value, args.type)
#-=-=-=-#
Key, Name, Value, Type = _
print(f'Successfully set the "{Name}" key value to "{Value}" as "{Type}" type in the "{Key}" path!\a')
if len(sys.argv) < 2:
print()
system("pause")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment