Skip to content

Instantly share code, notes, and snippets.

@sunapi386
Last active January 24, 2018 07:21
Show Gist options
  • Select an option

  • Save sunapi386/2681229bd6f09caaab22f7b2566efaa9 to your computer and use it in GitHub Desktop.

Select an option

Save sunapi386/2681229bd6f09caaab22f7b2566efaa9 to your computer and use it in GitHub Desktop.
Sets a windows registry `key` in `path` every `duration` seconds to `value`.
# Jason Sun [email protected]
# Jan 22, 2018.
# Sets a registry `key` in `path` every `duration` seconds to `value`.
# E.g. Add/update a registry DWORD entry, set NC_ShowSharedAccessUI = 1
# Can be compiled to exe with:
# pyinstaller --onefile register_moniter.py
# See reference https://pythonhosted.org/PyInstaller/usage.html
from time import sleep
import winreg
import ctypes
import os
from sys import exit
def getAllValues(key):
vals = []
try:
i = 0
while True:
name, value, type = winreg.EnumValue(key, i)
vals.append({
'name':name,
'value':value,
'type':type})
i += 1
except WindowsError:
return vals
def has_admin_rights():
try:
is_admin = os.getuid() == 0
except AttributeError:
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
return is_admin
if not has_admin_rights():
print("Not running as admin, this script likely won't work.")
sleep(1)
target = r"SOFTWARE\Policies\Microsoft\Windows\Network Connections"
target_name = "NC_ShowSharedAccessUI"
target_val = 1
lm = winreg.HKEY_LOCAL_MACHINE
key_read = winreg.OpenKey(lm, target, 0, winreg.KEY_READ)
print('All keys in path ' + target + ':')
for t in getAllValues(key_read):
print(t)
print("Will try to set " + target + '\\' + target_name)
try:
key_write = winreg.OpenKey(lm, target, 0, winreg.KEY_SET_VALUE)
print('Setting ' + target + ' ' + target_name + '=' + str(target_val))
winreg.SetValueEx(key_write, target_name, 0, winreg.REG_DWORD, target_val)
except PermissionError as e:
print(e)
print('Failed to open target for writing, goodbye (in 10s).')
print('Try right click this program and run as admin, if possible.')
sleep(10)
exit(-1)
while True:
winreg.SetValueEx(key_write, target_name, 0, winreg.REG_DWORD, target_val)
print('Sleeping 15s, will set again. Ctrl-C to exit.')
sleep(15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment