hkey_product_properties = OpenKey( hkey_products, product_guid + r'\InstallProperties', 0, KEY_ALL_ACCESS) try: value = QueryValueEx(hkey_product_properties, 'DisplayName')[0] except WindowsError, exception: if exception.winerror != 2: raise value = '<unknown>' CloseKey(hkey_product_properties) products[product_guid] = value product_index += 1 except WindowsError, exceptione: if exceptione.winerror != 259: print exceptione.strerror + '.', 'error', exceptione.winerror CloseKey(hkey_products) print 'Installed products:' for product_key in sorted(products.keys()): print transpose_guid(product_key), '=', products[product_key] print return products def get_missing_products(hkey_components): """ Detect references to missing products. """ products = get_installed_products()
def extract_info(key): try: h = OpenKey(HKEY_USERS, key) except WindowsError: return {} alias = key.split('\\')[-1] info = {} if '@' in alias: user, alias = alias.split('@', 1) info['user'] = user if ':' in alias: maybe_alias, maybe_port = alias.rsplit(':', 1) try: maybe_port = int(maybe_port) if maybe_port > 0 and maybe_port < 65536: alias = maybe_alias info['port'] = maybe_port except ValueError: pass info['hostname'] = alias elif alias == 'Default%20Settings': alias = '*' try: idx = 0 while True: try: name, value, _ = EnumValue(h, idx) except WindowsError: break if type(value) in (str, unicode): new_value = unquote(value) if new_value != value: if type(new_value) == unicode: try: new_value = new_value.encode('latin1') value = bin_decode(new_value) except UnicodeEncodeError: value = new_value name = name.lower() if name in PROPERTIES_MAPPING: if name == 'publickeyfile': info[PROPERTIES_MAPPING[name]] = [value] else: info[PROPERTIES_MAPPING[name]] = value idx += 1 finally: CloseKey(h) if info and (alias == '*' or info.get('hostname')): return {alias: info} return {}
return (value, type) def open_and_query(key, path, subkey, what): try: read_key = OpenKey(key, path, 0, KEY_QUERY_VALUE) except WindowsError, e: if e.winerror == 2: # not found return None raise DistutilsSetupError( "I could not read %s from the registry because I could not open " "the parent key.\n%r" % (what, e)) try: return query(read_key, subkey, what) finally: CloseKey(read_key) def update(key_name_path, subkey, desired_value, desired_type, goal, what): (key, name, path) = key_name_path (old_value, old_type) = open_and_query(key, path, subkey, what) or (None, None) if (old_value, old_type) == (desired_value, desired_type): print "Already done: %s." % (goal, ) return False try: update_key = OpenKey(key, path, 0, KEY_SET_VALUE | KEY_QUERY_VALUE) except WindowsError, e: if e.winerror != 2: raise DistutilsSetupError(
def set_env(name, value): key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS) SetValueEx(key, name, 0, REG_EXPAND_SZ, value) CloseKey(key) SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
def get_proxies(wpad_timeout=600): global last_wpad if sys.platform == "win32": #TODO retrieve all users proxy settings, not only HKCU from _winreg import OpenKey, CloseKey, QueryValueEx, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, KEY_QUERY_VALUE aKey = OpenKey( HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings", 0, KEY_QUERY_VALUE) try: value = QueryValueEx(aKey, "ProxyServer")[0] if value: for p in parse_win_proxy(value): yield p except Exception: pass finally: CloseKey(aKey) aKey = OpenKey( HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings", 0, KEY_QUERY_VALUE) try: value = QueryValueEx(aKey, "ProxyServer")[0] if value: for p in parse_win_proxy(value): yield p except Exception: pass finally: CloseKey(aKey) if "linux" in sys.platform: try: #retrieving gnome proxy settings subprocess.check_call( "which gsettings > /dev/null", shell=True) #raise an exception in case of return code!=0 try: host = subprocess.check_output( "gsettings get org.gnome.system.proxy.http host", shell=True).strip(" \n'\"") port = subprocess.check_output( "gsettings get org.gnome.system.proxy.http port", shell=True).strip(" \n'\"") user = subprocess.check_output( "gsettings get org.gnome.system.proxy.http authentication-user", shell=True).strip(" \n'\"") password = subprocess.check_output( "gsettings get org.gnome.system.proxy.http authentication-password", shell=True).strip(" \n'\"") if host and port: if not user: user = None if not password: password = None yield ('HTTP', "%s:%s" % (host, port), user, password) except Exception: pass try: host = subprocess.check_output( "gsettings get org.gnome.system.proxy.https host", shell=True).strip(" \n'\"") port = subprocess.check_output( "gsettings get org.gnome.system.proxy.https port", shell=True).strip(" \n'\"") if host and port: yield ('HTTP', "%s:%s" % (host, port), None, None) except Exception: pass try: host = subprocess.check_output( "gsettings get org.gnome.system.proxy.socks host", shell=True).strip(" \n'\"") port = subprocess.check_output( "gsettings get org.gnome.system.proxy.socks port", shell=True).strip(" \n'\"") if host and port: yield ('SOCKS4', "%s:%s" % (host, port), None, None) yield ('SOCKS5', "%s:%s" % (host, port), None, None) except Exception: pass except Exception: pass env_proxy = os.environ.get('HTTP_PROXY') if env_proxy: user, passwd, proxy = re.match( "^(?:https?://)?(?:(?P<user>\w+):?(?P<password>\w*)@)?(?P<proxy_addr>\S+:[0-9]+)$", env_proxy).groups() yield ('HTTP', proxy, user, passwd) python_proxies = urllib.getproxies() for key in python_proxies: if key.upper() in ('HTTP', 'HTTPS', 'SOCKS') and python_proxies[key] != '': user, passwd, proxy = re.match( "^(?:https?://)?(?:(?P<user>\w+):?(?P<password>\w*)@)?(?P<proxy_addr>\S+:[0-9]+)$", python_proxies[key]).groups() if key.upper() == 'SOCKS': key = 'SOCKS4' elif key.upper() == 'HTTPS': key = 'HTTP' yield (key.upper(), proxy, user, passwd) if last_wpad is None or time.time( ) - last_wpad > wpad_timeout: # to avoid flooding the network with wpad requests :) last_wpad = time.time() try: wpad_domain = socket.getfqdn("wpad") wpad_request = urllib.urlopen("http://%s/wpad.dat" % (wpad_domain)) wpad_data = wpad_request.read() r = re.findall(r"PROXY\s+([a-zA-Z0-9.-]+:[0-9]+);?\s*", wpad_data) for p in r: yield ('HTTP', p, None, None) except Exception as e: pass
def set_env(name, value, user=True): root, subkey = env_keys(user) key = OpenKey(root, subkey, 0, KEY_ALL_ACCESS) SetValueEx(key, name, 0, REG_EXPAND_SZ, value) CloseKey(key)
def set_office_mrus(self): """Adds randomized MRU's to Office software(s). Occasionally used by macros to detect sandbox environments. """ baseOfficeKeyPath = r"Software\Microsoft\Office" installedVersions = list() basePaths = [ "C:\\", "C:\\Windows\\Logs\\", "C:\\Windows\\Temp\\", "C:\\Program Files\\", ] extensions = { "Word": ["doc", "docx", "docm", "rtf"], "Excel": ["xls", "xlsx", "csv"], "PowerPoint": ["ppt", "pptx"], } try: officeKey = OpenKey(HKEY_CURRENT_USER, baseOfficeKeyPath, 0, KEY_READ) for currentKey in xrange(0, QueryInfoKey(officeKey)[0]): isVersion = True officeVersion = EnumKey(officeKey, currentKey) if "." in officeVersion: for intCheck in officeVersion.split("."): if not intCheck.isdigit(): isVersion = False break if isVersion: installedVersions.append(officeVersion) CloseKey(officeKey) except WindowsError: # Office isn't installed at all return for oVersion in installedVersions: for software in extensions: values = list() mruKeyPath = r"{0}\{1}\{2}\File MRU".format( baseOfficeKeyPath, oVersion, software) try: mruKey = OpenKey(HKEY_CURRENT_USER, mruKeyPath, 0, KEY_READ) displayValue = False for mruKeyInfo in xrange(0, QueryInfoKey(mruKey)[1]): currentValue = EnumValue(mruKey, mruKeyInfo) if currentValue[0] == "Max Display": displayValue = True values.append(currentValue) CloseKey(mruKey) except WindowsError: # An Office version was found in the registry but the # software (Word/Excel/PowerPoint) was not installed. values = "notinstalled" if values != "notinstalled" and len(values) < 5: mruKey = OpenKey(HKEY_CURRENT_USER, mruKeyPath, 0, KEY_SET_VALUE) if not displayValue: SetValueEx(mruKey, "Max Display", 0, REG_DWORD, 25) for i in xrange(1, randint(10, 30)): rString = random_string(minimum=11, charset="0123456789ABCDEF") if i % 2: baseId = "T01D1C" + rString else: baseId = "T01D1D" + rString setVal = "[F00000000][{0}][O00000000]*{1}{2}.{3}".format( baseId, basePaths[randint(0, len(basePaths) - 1)], random_string( minimum=3, maximum=15, charset="abcdefghijkLMNOPQURSTUVwxyz_0369"), extensions[software][randint( 0, len(extensions[software]) - 1)]) name = "Item {0}".format(i) SetValueEx(mruKey, name, 0, REG_SZ, setVal) CloseKey(mruKey)
def delete_key(name, user=True): key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS) DeleteValue(key, name) CloseKey(key) SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
'''Find where InnoSetup exeutable is''' __author__ = "Miki Tebeka <*****@*****.**>" from _winreg import OpenKeyEx, EnumKey, QueryValueEx, CloseKey, \ HKEY_LOCAL_MACHINE from os.path import join from itertools import count uninst = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" key = OpenKeyEx(HKEY_LOCAL_MACHINE, uninst) i = 0 for i in count(): # When i will becode too large we'll get WindowsError innokey = EnumKey(key, i) if "Inno Setup" in innokey: break ikey = OpenKeyEx(key, innokey) instdir, type = QueryValueEx(ikey, "InstallLocation") CloseKey(ikey) CloseKey(key) print join(instdir, "ISCC.exe")
installDir = ("C:\Program Files\Path_Validator\\") Infile = ("Path_Validator-V1.0-Windows-x86.exe") print curnt + Infile print installDir + Infile if not os.path.exists(installDir): os.makedirs(installDir) try: os.rename(curnt + Infile, installDir + Infile) except WindowsError as er: logging.exception("\n\n Something Has Gone Wrong!") exit() #Registry Setup, DONT TOUCH THESE keyVal = r'Directory\Background\shell\Validate Paths\\command' try: key = OpenKey(_winreg.HKEY_CLASSES_ROOT, keyVal, 0, _winreg.KEY_ALL_ACCESS) except: key = CreateKey(_winreg.HKEY_CLASSES_ROOT, keyVal) SetValueEx( key, "", 0, _winreg.REG_SZ, r"C:\Program Files\Path_Validator\Path_Validator-V1.0-Windows-x86.exe %V") CloseKey(key) exit()