def set_LOCAL_MACHINE_REG_DWORD(clf, keyname, value_name, value): key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, keyname, 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(key, value_name, 0, winreg.REG_DWORD, value) winreg.CloseKey(key)
def getDesktop(): key = winreg.OpenKey( winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders') return winreg.QueryValueEx(key, "Desktop")[0]
def add_to_system_path(paths, allusers=True, path_env_var='PATH'): """Adds the requested paths to the system PATH variable. You must call broadcast_environment_settings_change() after you are finished manipulating the environment with this and other functions. """ # Make sure it's a list if not issubclass(type(paths), list): paths = [paths] # Ensure all the paths are valid before we start messing with the # registry. new_paths = None for p in paths: p = path.abspath(p) if new_paths: new_paths = new_paths + os.pathsep + p else: new_paths = p if allusers: # All Users root, keyname = ( reg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment') else: # Just Me root, keyname = (reg.HKEY_CURRENT_USER, r'Environment') key = reg.OpenKey(root, keyname, 0, reg.KEY_QUERY_VALUE | reg.KEY_SET_VALUE) reg_type = None reg_value = None try: try: reg_value = reg.QueryValueEx(key, path_env_var) except WindowsError: # This will happen if we're a non-admin install and the user has # no PATH variable; in which case, we can write our new paths # directly. reg_type = reg.REG_EXPAND_SZ final_value = new_paths else: # Put to the front of PATH irrespective of allusers. The old # behaviour was asking for trouble and did not, contrary to what # this comment used to say, mirror what happens on *nix. reg_type = reg_value[1] final_value = new_paths + os.pathsep + reg_value[0] # Replace coincident ';' with a single ';' final_value = re.sub(r'([\;])+', r'\1', final_value) # Remove trailing ';' final_value = re.sub(r'\;$', '', final_value) # Remove any '"', they are not needed and break conda. final_value = final_value.replace('"', '') # Warn about directories that do not exist. directories = final_value.split(';') for directory in directories: if '%' not in directory and not os.path.exists(directory): out("WARNING: Old PATH entry '%s' does not exist\n" % (directory)) reg.SetValueEx(key, path_env_var, 0, reg_type, final_value) finally: reg.CloseKey(key)
def create_driver(browser_name): if browser_name not in GlobalUtils.BROWSER_NAMES: raise Exception("Unsupported browser string: '%s' Use: %s" % (browser_name, GlobalUtils.BROWSER_NAMES)) spinner_locator_file = os.path.join(os.getcwd(), GlobalUtils.PROJECT_SPINNER_LOCATORS_FILE) if not os.path.isfile(spinner_locator_file): shutil.copyfile(GlobalUtils.FRAMEWORK_SPINNER_LOCATORS_FILE, spinner_locator_file) if __REMOTE_SERVER_ADDRESS: if _REMOTE_SERVER_CAPTIONS: desired_capabilities = _REMOTE_SERVER_CAPTIONS else: desired_capabilities = __get_desired_capabilities(browser_name) print(__REMOTE_SERVER_ADDRESS) print(desired_capabilities) _driver = webdriver.Remote(__REMOTE_SERVER_ADDRESS, desired_capabilities) return _driver if browser_name == GlobalUtils.BROWSER_NAMES[Browsers.IE]: # Read browser language from config import winreg try: my_lang = get_config_value("browser_language") country_key = get_country_key(my_lang) try: key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Internet Explorer\\International", 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(key, "AcceptLanguage", 0, winreg.REG_SZ, str(country_key + ";q=0.5")) winreg.CloseKey(key) except Exception as e: try: winreg.CloseKey(key) throw_error("\nCould not set language value: " + str(e)) except Exception as msg: print(str(msg)) except: pass # Turn protected mode on for all zones try: for i in range(1, 5): key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\" + str(i), 0, winreg.KEY_ALL_ACCESS) try: _protected_values[i - 1] = winreg.QueryValueEx(key, "2500")[0] except WindowsError as e: pass winreg.SetValueEx(key, "2500", 0, winreg.REG_DWORD, 0) winreg.CloseKey(key) except Exception as e: try: winreg.CloseKey(key) reset_protected_mode() throw_error("\nCould not change Internet Explorer zone settings: " + str(e)) except Exception as msg: print(str(msg)) pass capabilities = _get_browser_options_from_project_xml("default", GlobalUtils.BROWSER_FULL_NAMES[GlobalUtils.BROWSER_NAMES[Browsers.IE]], "capabilities") ie_capabilities = DesiredCapabilities.INTERNETEXPLORER for arg in capabilities: ie_capabilities[arg["option"]] = eval(arg["text"]) # Adding driver to path if not GlobalUtils.is_linux(): print("Using IEDriverServer") if not os.path.join(GlobalUtils.RESOURCES_IE_PATH) in os.environ["PATH"]: print("Adding IEDriverServer to path") os.environ["PATH"] += os.pathsep + os.path.join(GlobalUtils.RESOURCES_IE_PATH) else: raise Exception("Linux can't use IEDriverServer") _driver = webdriver.Ie(capabilities=ie_capabilities) return _driver elif browser_name == GlobalUtils.BROWSER_NAMES[Browsers.CHROME]: options = webdriver.ChromeOptions() # enable chrome switches try: opt_values = get_config_value("browser_options") for opt_value in opt_values: options.add_argument("--" + opt_value) except: pass extension_if_cases = [] argument_if_cases = [] # enable cache cleaner for resource timings if get_config_value("enable_live_monitoring").lower() == 'true': extension_if_cases.append("enable_live_monitoring") # enable precise memory info if get_config_value("enable_precise_memory").lower() == 'true': argument_if_cases.append("enable_precise_memory") # Get add_argument options from xml add_arguments = _get_browser_options_from_project_xml("default", GlobalUtils.BROWSER_FULL_NAMES[GlobalUtils.BROWSER_NAMES[Browsers.CHROME]], "add_argument", argument_if_cases) # Get add_extensions options from xml add_extensions = _get_browser_options_from_project_xml("default", GlobalUtils.BROWSER_FULL_NAMES[GlobalUtils.BROWSER_NAMES[Browsers.CHROME]], "add_extension", extension_if_cases) # Get add_experimental_options options from xml add_experimental_options = _get_browser_options_from_project_xml("default", GlobalUtils.BROWSER_FULL_NAMES[GlobalUtils.BROWSER_NAMES[Browsers.CHROME]], "add_experimental_option") # add_argument using dict parsed from xml for arg in add_arguments: options.add_argument(eval(arg["text"])) # add_extension using dict parsed from xml for arg in add_extensions: options.add_extension(eval(arg["text"])) # add_experimental_option using dict parsed from xml for arg in add_experimental_options: try: # Selenium 2.26 options.add_experimental_option(arg["option"], eval(arg["text"])) except: pass # Adding driver to path if not GlobalUtils.is_linux(): print("Using 32bit win chromedriver") if not os.path.join(GlobalUtils.RESOURCES_CHROME32_PATH) in os.environ["PATH"]: print("Adding 32bit win chromedriver to path") os.environ["PATH"] += os.pathsep + os.path.join(GlobalUtils.RESOURCES_CHROME32_PATH) else: print("Using 64bit linux chromedriver") if not os.path.join(GlobalUtils.RESOURCES_LINUX_CHROME64_PATH) in os.environ["PATH"]: print("Adding 64bit linux chromedriver to path") os.environ["PATH"] += os.pathsep + os.path.join(GlobalUtils.RESOURCES_LINUX_CHROME64_PATH) _driver = webdriver.Chrome(chrome_options=options) try: selenium_library = BuiltIn().get_library_instance("SeleniumLibrary") selenium_library.register_driver(_driver, "default_gc") except: pass return _driver elif browser_name == GlobalUtils.BROWSER_NAMES[Browsers.FIREFOX]: profile = webdriver.FirefoxProfile() preference_if_cases = [] set_preferences = _get_browser_options_from_project_xml("default", GlobalUtils.BROWSER_FULL_NAMES[GlobalUtils.BROWSER_NAMES[Browsers.FIREFOX]], "set_preference", preference_if_cases) for arg in set_preferences: profile.set_preference(arg["option"], eval(arg["text"])) set_capabilities = _get_browser_options_from_project_xml("default", GlobalUtils.BROWSER_FULL_NAMES[GlobalUtils.BROWSER_NAMES[Browsers.FIREFOX]], "set_capabilities") firefox_capabilities = DesiredCapabilities.FIREFOX for arg in set_capabilities: firefox_capabilities[arg["option"]] = eval(arg["text"]) # Adding driver to path if not GlobalUtils.is_linux(): print("Using 32bit win geckodriver") # first we try to use 32bit wersion if not os.path.join(GlobalUtils.RESOURCES_GECKO32_PATH) in os.environ["PATH"]: print("Adding 32bit win geckodriver to path") os.environ["PATH"] += os.pathsep + os.path.join(GlobalUtils.RESOURCES_GECKO32_PATH) else: print("Using 64bit linux geckodriver") if not os.path.join(GlobalUtils.RESOURCES_LINUX_GECKO64_PATH) in os.environ["PATH"]: print("Adding 64bit linux geckodriver to path") os.environ["PATH"] += os.pathsep + os.path.join(GlobalUtils.RESOURCES_LINUX_GECKO64_PATH) try: _driver = webdriver.Firefox(firefox_profile=profile, capabilities=firefox_capabilities, log_path=_geckodriver_log_path) except WebDriverException as e: # try with 64bit version if we are using windows if not GlobalUtils.is_linux(): if os.path.join(GlobalUtils.RESOURCES_GECKO32_PATH) in os.environ["PATH"]: os.environ["PATH"] = os.environ["PATH"].replace(os.pathsep + os.path.join(GlobalUtils.RESOURCES_GECKO32_PATH), "") if not os.path.join(GlobalUtils.RESOURCES_GECKO64_PATH) in os.environ["PATH"]: os.environ["PATH"] += os.pathsep + os.path.join(GlobalUtils.RESOURCES_GECKO64_PATH) _driver = webdriver.Firefox(firefox_profile=profile, capabilities=firefox_capabilities) try: selenium_library = BuiltIn().get_library_instance("SeleniumLibrary") selenium_library.register_driver(_driver, "default_ff") except: pass else: raise e return _driver elif browser_name == GlobalUtils.BROWSER_NAMES[Browsers.EDGE]: capabilities = _get_browser_options_from_project_xml("default", GlobalUtils.BROWSER_FULL_NAMES[GlobalUtils.BROWSER_NAMES[Browsers.EDGE]], "capabilities") options = EdgeOptions() for arg in capabilities: options.set_capability(arg["option"], eval(arg["text"])) options.use_chromium = True # Adding driver to path print("Using EdgeWebDriver") if not GlobalUtils.is_linux(): options.set_capability("platform", "WINDOWS") else: options.set_capability("platform", "LINUX") _driver = Edge(options=options) return _driver elif browser_name == GlobalUtils.BROWSER_NAMES[Browsers.SAFARI]: desired_capabilities = _get_browser_options_from_project_xml("default", GlobalUtils.BROWSER_FULL_NAMES[GlobalUtils.BROWSER_NAMES[Browsers.SAFARI]], "desired_capabilities") safari_capabilities = DesiredCapabilities.SAFARI for arg in desired_capabilities: safari_capabilities[arg["option"]] = eval(arg["text"]) _driver = webdriver.Safari(desired_capabilities=safari_capabilities) return _driver elif browser_name == GlobalUtils.BROWSER_NAMES[Browsers.OPERA]: desired_capabilities = _get_browser_options_from_project_xml("default", GlobalUtils.BROWSER_FULL_NAMES[GlobalUtils.BROWSER_NAMES[Browsers.OPERA]], "desired_capabilities") opera_capabilities = DesiredCapabilities.OPERA for arg in desired_capabilities: opera_capabilities[arg["option"]] = eval(arg["text"]) _driver = webdriver.Opera(desired_capabilities=opera_capabilities) return _driver else: return None
def get_Chrome_version(): key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Google\Chrome\BLBeacon') version, types = winreg.QueryValueEx(key, 'version') return version
def choose_key(write=False): param = [] param = [winreg.HKEY_CURRENT_USER, "Environment"] if write: param.extend([0, winreg.KEY_ALL_ACCESS]) return winreg.OpenKey(*param)
def __init__(self, DeviceNo=1, raiseExceptions=1): self.version = '0.15' if sys.platform.startswith('linux'): try: if sys.version_info[0] == 3: f = open('/etc/adwin/ADWINDIR', 'r') else: f = file('/etc/adwin/ADWINDIR', 'r') self.ADwindir = f.readline( )[:-1] + '/' # without newline at the end self.dll = ctypes.CDLL(self.ADwindir + 'lib/libadwin.so') except: raise ADwinError('__init__', 'shared library libadwin.so not found.', 200) f.close() self.dll.Set_DeviceNo(DeviceNo) elif sys.platform == 'darwin': try: if sys.version_info[0] == 3: f = open('/etc/adwin/ADWINDIR', 'r') else: f = file('/etc/adwin/ADWINDIR', 'r') self.ADwindir = f.readline( )[:-1] + '/' # without newline at the end self.dll = ctypes.CDLL( '/Library/Frameworks/adwin32.framework/Versions/A/libadwin.5.dylib' ) self.dll.Set_DeviceNo(DeviceNo) except: raise ADwinError('__init__', 'shared library libadwin.5.dylib not found.', 200) else: try: aKey = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"SOFTWARE\Jäger Meßtechnik GmbH\ADwin\Directory") self.ADwindir = str(_winreg.QueryValueEx(aKey, 'BTL')[0]) _winreg.CloseKey(aKey) except: try: aKey = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Jäger Meßtechnik GmbH\ADwin\Directory") self.ADwindir = str(_winreg.QueryValueEx(aKey, 'BTL')[0]) _winreg.CloseKey(aKey) except: try: aKey = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Wow6432Node\ADwin\Directory") self.ADwindir = str( _winreg.QueryValueEx(aKey, 'BTL')[0]) _winreg.CloseKey(aKey) except: raise ADwinError('__init__', 'Could not read Registry.', 200) try: if struct.calcsize("P") == 4: self.dll = ctypes.WinDLL('ADWIN32') else: self.dll = ctypes.WinDLL('ADWIN64') self.dll.DeviceNo = DeviceNo except: raise ADwinError('__init__', 'ADwin-DLL not found.', 200) self.raiseExceptions = raiseExceptions self.DeviceNo = DeviceNo
def get_windows_cpu_speed(): key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") speed, type = winreg.QueryValueEx(key, "~MHz") speed = round(float(speed) / 1024, 1) return "{speed} GHz".format(speed=speed)
'fallback to desktop when both cmd and csv are omitted"' ])) logger.info(f'Template export to {templatePath}.') csvPath: str = input('Input csv file path, include title in csv file : ').strip().strip('"\'') logger.debug(f'User input {csvPath=}') checkPath(csvPath, '.csv') splitByCsvWithConfig(csvPath=csvPath, saveDir=saveDir) case '4': logger.debug(f'User input {names=}') angle: int = int(input('Input rotate angle, 90 or +90 for clockwise 90°, ' '-90 for counterclockwise 90° ').strip() or 90) logger.debug(f'User input {angle=}') rotate(names, angle, saveDir) case '5': logger.debug(f'User input {names=}') splitByIntervalWithNames(pdfPath, names, interval, saveDir) # global var csvHeader = ['pdfPath', 'pageFrom', 'pageTo', 'interval', 'savePath'] regKey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders') desktopDir = winreg.QueryValueEx(regKey, "Desktop")[0] if __name__ == '__main__': logger.debug('init from __main__') main() logger.info('Finished.')
import winreg import subprocess import win32event import EventLogger import win32service import servicemanager import win32serviceutil ##get file name without extension drive_letter, tail = os.path.splitdrive(__file__) path, file = os.path.split(tail) file_name = file[:-3] # read registry try: reg_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "Software\MarginMate", 0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY) license_key = winreg.QueryValueEx(reg_key, "MM_MBS_LicenseKey")[0] period = winreg.QueryValueEx(reg_key, "MM_MBS_Value")[0] time_out_value = winreg.QueryValueEx(reg_key, "MM_MBS_TimeOut")[0] command = winreg.QueryValueEx(reg_key, "MM_MBS_Command")[0] arguments = winreg.QueryValueEx(reg_key, "MM_MBS_Parameters")[0] execution_time_out_value = winreg.QueryValueEx( reg_key, "MM_MBS_Execution_TimeOut")[0] except FileNotFoundError: # this print, prints directly to cmd when installing the service. print("{} failed to read required values from 32bit registry.".format( file_name)) try: reg_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\MarginMate", 0,
def RegisterPythonServer(filename, progids=None, verbose=0): if progids: if isinstance(progids, str): progids = [progids] # we know the CLSIDs we need, but we might not be an admin user # and otherwise unable to register them. So as long as the progids # exist and the DLL points at our version, assume it already is. why_not = None for progid in progids: try: clsid = pythoncom.MakeIID(progid) except pythoncom.com_error: # no progid - not registered. break # have a CLSID - open it. try: HKCR = winreg.HKEY_CLASSES_ROOT hk = winreg.OpenKey(HKCR, "CLSID\\%s" % clsid) dll = winreg.QueryValue(hk, "InprocServer32") except WindowsError: # no CLSID or InProcServer32 - not good! break ok_files = [ os.path.basename(pythoncom.__file__), 'pythoncomloader%d%d.dll' % (sys.version_info[0], sys.version_info[1]) ] if os.path.basename(dll) not in ok_files: why_not = "%r is registered against a different Python version (%s)" % ( progid, dll) break else: # print "Skipping registration of '%s' - already registered" % # filename return # needs registration - see if its likely! try: from win32com.shell.shell import IsUserAnAdmin except ImportError: print( "Can't import win32com.shell - no idea if you are an admin or not?" ) is_admin = False else: try: is_admin = IsUserAnAdmin() except pythoncom.com_error: # old, less-secure OS - assume *is* admin. is_admin = True if not is_admin: msg = "%r isn't registered, but I'm not an administrator who can register it." % progids[ 0] if why_not: msg += "\n(registration check failed as %s)" % why_not # throw a normal "class not registered" exception - we don't report # them the same way as "real" errors. raise pythoncom.com_error(winerror.CO_E_CLASSSTRING, msg, None, -1) # so theoretically we are able to register it. cmd = '%s "%s" --unattended > nul 2>&1' % (win32api.GetModuleFileName(0), filename) if verbose: print("Registering engine", filename) # print cmd rc = os.system(cmd) if rc: print("Registration command was:") print(cmd) raise RuntimeError("Registration of engine '%s' failed" % filename)
def is_win_dumping_to_default(): # pylint: disable=too-complex """Check whether Windows minidumps are enabled and set to go to Windows' default location. Raises: OSError: Raises if querying for the DumpType key throws and it is unrelated to various issues, e.g. the key not being present. Returns: bool: Returns True when Windows has dumping enabled, and is dumping to the default location, otherwise False """ import winreg # pylint: disable=import-error # For now, this code does not edit the Windows Registry because we tend to be in a 32-bit # version of Python and if one types in regedit in the Run dialog, opens up the 64-bit registry. # If writing a key, we most likely need to flush. For the moment, no keys are written. try: with winreg.OpenKey( winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE), r"Software\Microsoft\Windows\Windows Error Reporting\LocalDumps", # Read key from 64-bit registry, which also works for 32-bit 0, (winreg.KEY_WOW64_64KEY + winreg.KEY_READ)) as key: try: dump_type_reg_value = winreg.QueryValueEx(key, "DumpType") if not (dump_type_reg_value[0] == 1 and dump_type_reg_value[1] == winreg.REG_DWORD): print(NO_DUMP_MSG) return False except OSError as ex: if ex.errno == 2: # pylint: disable=no-else-return print(NO_DUMP_MSG) return False else: raise try: dump_folder_reg_value = winreg.QueryValueEx(key, "DumpFolder") # %LOCALAPPDATA%\CrashDumps is the default location. if not (dump_folder_reg_value[0] == r"%LOCALAPPDATA%\CrashDumps" and dump_folder_reg_value[1] == winreg.REG_EXPAND_SZ): print() print( f"WARNING: Dumps are instead appearing at: {dump_folder_reg_value[0]} - " f"all crashes will be uninteresting.") print() return False except OSError as ex: # If the key value cannot be found, the dumps will be put in the default location # pylint: disable=no-else-return if ex.errno == 2 and ex.strerror == "The system cannot find the file specified": return True else: raise return True except OSError as ex: # If the LocalDumps registry key cannot be found, dumps will be put in the default location. # pylint: disable=no-else-return if ex.errno == 2 and ex.strerror == "The system cannot find the file specified": print() print( "WARNING: The registry key HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\" "Windows\\Windows Error Reporting\\LocalDumps cannot be found." ) print() return False else: raise
install_directory, folder_name = os.path.split(install_directory) mainDir = os.path.abspath(install_directory) sitePackagesDir = os.path.join( mainDir, "lib%d%d" % version, "site-packages" ) sys.path.insert(0, mainDir.encode('mbcs')) sys.path.insert(1, sitePackagesDir.encode('mbcs')) try: if "PYTHONPATH" in os.environ: for path in os.environ.get("PYTHONPATH").split(os.pathsep): site.addsitedir(path) key = winreg.HKEY_LOCAL_MACHINE subkey = r"SOFTWARE\Python\PythonCore\%d.%d\InstallPath" % version with winreg.OpenKey(key, subkey) as hand: site.addsitedir( os.path.join( winreg.QueryValue(hand, None), "Lib", "site-packages", ) ) except: pass
import COMRegistrationFixes import winKernel _wsh = None def _getWSH(): global _wsh if not _wsh: import comtypes.client _wsh = comtypes.client.CreateObject("wScript.Shell", dynamic=True) return _wsh defaultStartMenuFolder = versionInfo.name with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion") as k: programFilesPath = winreg.QueryValueEx(k, "ProgramFilesDir")[0] defaultInstallPath = os.path.join(programFilesPath, versionInfo.name) def createShortcut(path, targetPath=None, arguments=None, iconLocation=None, workingDirectory=None, hotkey=None, prependSpecialFolder=None): # #7696: The shortcut is only physically saved to disk if it does not already exist, or one or more properties have changed. wsh = _getWSH() if prependSpecialFolder: specialPath = wsh.SpecialFolders(prependSpecialFolder)
def on_user_logged_in(sender, user): # Keep hold of the user ID user_id = user.id # Get the first server group for the user servergroup_id = 1 servergroups = ServerGroup.query.filter_by( user_id=user_id ).order_by("id") if servergroups.count() > 0: servergroup = servergroups.first() servergroup_id = servergroup.id '''Add a server to the config database''' def add_server(user_id, servergroup_id, name, superuser, port, discovery_id, comment): # Create a server object if needed, and store it. servers = Server.query.filter_by( user_id=user_id, discovery_id=svr_discovery_id ).order_by("id") if servers.count() > 0: return; svr = Server(user_id=user_id, servergroup_id=servergroup_id, name=name, host='localhost', port=port, maintenance_db='postgres', username=superuser, ssl_mode='prefer', comment=svr_comment, discovery_id=discovery_id) db.session.add(svr) db.session.commit() # Figure out what servers are present if winreg is not None: arch_keys = set() proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower() try: proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower() except: proc_arch64 = None if proc_arch == 'x86' and not proc_arch64: arch_keys.add(0) elif proc_arch == 'x86' or proc_arch == 'amd64': arch_keys.add(winreg.KEY_WOW64_32KEY) arch_keys.add(winreg.KEY_WOW64_64KEY) for arch_key in arch_keys: for server_type in ('PostgreSQL', 'EnterpriseDB'): try: root_key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\" + server_type + "\Services", 0, winreg.KEY_READ | arch_key ) for i in xrange(0, winreg.QueryInfoKey(root_key)[0]): inst_id = winreg.EnumKey(root_key, i) inst_key = winreg.OpenKey(root_key, inst_id) svr_name = winreg.QueryValueEx( inst_key, 'Display Name' )[0] svr_superuser = winreg.QueryValueEx( inst_key, 'Database Superuser' )[0] svr_port = winreg.QueryValueEx(inst_key, 'Port')[0] svr_discovery_id = inst_id svr_comment = gettext( "Auto-detected %s installation with the data directory at %s" % ( winreg.QueryValueEx( inst_key, 'Display Name' )[0], winreg.QueryValueEx( inst_key, 'Data Directory' )[0] ) ) add_server( user_id, servergroup_id, svr_name, svr_superuser, svr_port, svr_discovery_id, svr_comment ) inst_key.Close() except: pass else: # We use the postgres-winreg.ini file on non-Windows try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser # Python 2 registry = ConfigParser() try: registry.read('/etc/postgres-reg.ini') sections = registry.sections() # Loop the sections, and get the data from any that are PG or PPAS for section in sections: if section.startswith('PostgreSQL/') or section.startswith('EnterpriseDB/'): svr_name = registry.get(section, 'Description') svr_superuser = registry.get(section, 'Superuser') svr_port = registry.getint(section, 'Port') svr_discovery_id = section description = registry.get(section, 'Description') data_directory = registry.get(section, 'DataDirectory') if hasattr(str, 'decode'): description = description.decode('utf-8') data_directory = data_directory.decode('utf-8') svr_comment = gettext(u"Auto-detected %s installation with the data directory at %s" % ( description, data_directory )) add_server(user_id, servergroup_id, svr_name, svr_superuser, svr_port, svr_discovery_id, svr_comment) except: pass
def create_sub_key(self): key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.path, 0, winreg.KEY_WRITE) winreg.CreateKeyEx(key, self.name, 0, winreg.KEY_WRITE) winreg.CloseKey(key)
def from_live_system(): logger.debug('Obtaining registry from local system') try: from pypykatz.commons.winapi.processmanipulator import ProcessManipulator from pypykatz.commons.winapi.constants import SE_BACKUP import winreg import tempfile import os import ntpath except Exception as e: logger.error('Could not import necessary packages! Are you on Windows? Error: %s' % str(e)) raise sam_name = ntpath.join(tempfile.gettempdir(), os.urandom(4).hex()) system_name = ntpath.join(tempfile.gettempdir(), os.urandom(4).hex()) security_name = ntpath.join(tempfile.gettempdir(), os.urandom(4).hex()) locations = [ ('SAM', sam_name), ('SYSTEM', system_name), ('SECURITY', security_name), ] logger.debug('Obtaining SE_BACKUP privilege...') try: po = ProcessManipulator() po.set_privilege(SE_BACKUP) except Exception as e: logger.error('Failed to obtain SE_BACKUP privilege! Registry dump will not work! Reason: %s' % str(e)) raise e logger.debug('Obtaining SE_BACKUP OK!') dumped_names = {} for reg_name, location in locations: logger.debug('Dumping %s...' % reg_name) try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_name, access=0x00020000) winreg.SaveKey(key, location) key.Close() except Exception as e: logger.error('Dumping %s FAILED!! Reason: %s' % (reg_name, str(e))) else: logger.debug('Dumping %s OK!' % reg_name) dumped_names[reg_name] = location ### ### Do Parsing here! ### po = None if 'SYSTEM' in dumped_names: try: po = OffineRegistry.from_files(system_name, sam_name if 'SAM' in dumped_names else None, security_name if 'SECURITY' in dumped_names else None) except Exception as e: import traceback traceback.print_exc() else: logger.error('Failed to dump SYSTEM hive, exiting...') logger.debug('Cleaning up temp files') for reg_name, location in locations: try: os.remove(location) except Exception as e: logger.error('Failed to clean up temp file for %s! Sensitive files might have been left on the filesystem! Path: %s Reason: %s' % (reg_name, location, str(e))) else: logger.debug('Cleanup for %s OK!' % reg_name) return po
def clear_entry(self): key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.path, 0, winreg.KEY_WRITE) winreg.SetValueEx(key, self.name, 0, winreg.REG_MULTI_SZ, []) winreg.CloseKey(key)
def _find_windows_sdk_in_registry_view(self, view): products_key = None roots_key = None installed_options_keys = [] try: sam = view | winreg.KEY_READ products_key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows Kits\Installed Products', 0, sam) # This is the GUID for the desktop component. If this is present # then the components required for the Desktop SDK are installed. # If not it will throw an exception. winreg.QueryValueEx(products_key, '{5A3D81EC-D870-9ECF-D997-24BDA6644752}') roots_key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows Kits\Installed Roots', 0, sam) root_dir = winreg.QueryValueEx(roots_key, 'KitsRoot10') root_dir = to_string(root_dir[0]) sdk_versions = [] index = 0 while True: # Installed SDK versions are stored as sub-keys of the # 'Installed Roots' key. Find all of their names, then sort # them by version try: ver_key = winreg.EnumKey(roots_key, index) sdk_versions.append(ver_key) index = index + 1 except WindowsError: break if not sdk_versions: return (None, None) # Windows SDK version numbers consist of 4 dotted components, so we # have to use LooseVersion, as StrictVersion supports 3 or fewer. from distutils.version import LooseVersion sdk_versions.sort(key=lambda x: LooseVersion(x), reverse=True) option_value_name = 'OptionId.DesktopCPP' + self.msvc_arch_str for v in sdk_versions: try: version_subkey = v + r'\Installed Options' key = winreg.OpenKey(roots_key, version_subkey) installed_options_keys.append(key) (value, value_type) = winreg.QueryValueEx(key, option_value_name) if value == 1: # The proper architecture is installed. Return the # associated paths. if self.verbose: print('Found Installed Windows SDK v{0} at {1}'. format(v, root_dir)) return (root_dir, v) except: continue except: return (None, None) finally: del products_key del roots_key for k in installed_options_keys: del k return (None, None)
def on_user_logged_in(sender, user): # If Auto Discover servers is turned off then return from the # function. if not config.AUTO_DISCOVER_SERVERS: return # Keep hold of the user ID user_id = user.id # Get the first server group for the user servergroup_id = 1 servergroups = ServerGroup.query.filter_by( user_id=user_id).order_by("id") if servergroups.count() > 0: servergroup = servergroups.first() servergroup_id = servergroup.id '''Add a server to the config database''' def add_server(user_id, servergroup_id, name, superuser, port, discovery_id, comment): # Create a server object if needed, and store it. servers = Server.query.filter_by( user_id=user_id, discovery_id=svr_discovery_id).order_by("id") if servers.count() > 0: return svr = Server(user_id=user_id, servergroup_id=servergroup_id, name=name, host='localhost', port=port, maintenance_db='postgres', username=superuser, ssl_mode='prefer', comment=svr_comment, discovery_id=discovery_id) db.session.add(svr) db.session.commit() # Figure out what servers are present if winreg is not None: arch_keys = set() proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower() try: proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower() except Exception: proc_arch64 = None if proc_arch == 'x86' and not proc_arch64: arch_keys.add(0) elif proc_arch == 'x86' or proc_arch == 'amd64': arch_keys.add(winreg.KEY_WOW64_32KEY) arch_keys.add(winreg.KEY_WOW64_64KEY) for arch_key in arch_keys: for server_type in ('PostgreSQL', 'EnterpriseDB'): try: root_key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\" + server_type + "\\Services", 0, winreg.KEY_READ | arch_key) for i in range(0, winreg.QueryInfoKey(root_key)[0]): inst_id = winreg.EnumKey(root_key, i) inst_key = winreg.OpenKey(root_key, inst_id) svr_name = winreg.QueryValueEx( inst_key, 'Display Name')[0] svr_superuser = winreg.QueryValueEx( inst_key, 'Database Superuser')[0] svr_port = winreg.QueryValueEx(inst_key, 'Port')[0] svr_discovery_id = inst_id svr_comment = gettext( "Auto-detected {0} installation with the data " "directory at {1}").format( winreg.QueryValueEx( inst_key, 'Display Name')[0], winreg.QueryValueEx( inst_key, 'Data Directory')[0]) add_server(user_id, servergroup_id, svr_name, svr_superuser, svr_port, svr_discovery_id, svr_comment) inst_key.Close() except Exception: pass else: # We use the postgres-winreg.ini file on non-Windows from configparser import ConfigParser registry = ConfigParser() try: registry.read('/etc/postgres-reg.ini') sections = registry.sections() # Loop the sections, and get the data from any that are PG or PPAS for section in sections: if (section.startswith('PostgreSQL/') or section.startswith('EnterpriseDB/')): svr_name = registry.get(section, 'Description') svr_superuser = registry.get(section, 'Superuser') # getint function throws exception if value is blank. # Ex: Port= # In such case we should handle the exception and continue # to read the next section of the config file. try: svr_port = registry.getint(section, 'Port') except ValueError: continue svr_discovery_id = section description = registry.get(section, 'Description') data_directory = registry.get(section, 'DataDirectory') svr_comment = gettext( "Auto-detected {0} installation " "with the data directory at {1}").format( description, data_directory) add_server(user_id, servergroup_id, svr_name, svr_superuser, svr_port, svr_discovery_id, svr_comment) except Exception: pass
def get_diagnostic_information(): '''Get diagnostic information about the system state that is suitable for printing or logging returns: dict note: Python bitness may be incorrect when running in a virtual environment ''' import os import pkg_resources import platform import struct import sys def is_python_64bit(): return (struct.calcsize("P") == 8) def is_os_64bit(): return platform.machine().endswith('64') def is_venv(): return 'VIRTUAL_ENV' in os.environ info = {} info['os'] = {} info['python'] = {} info['driver'] = {} info['module'] = {} if platform.system() == 'Windows': try: import winreg as winreg except ImportError: import _winreg as winreg os_name = 'Windows' try: driver_version_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\National Instruments\NI-SCOPE\CurrentVersion") driver_version = winreg.QueryValueEx(driver_version_key, "Version")[0] except WindowsError: driver_version = 'Unknown' elif platform.system() == 'Linux': os_name = 'Linux' driver_version = 'Unknown' else: raise SystemError('Unsupported platform: {}'.format(platform.system())) installed_packages = pkg_resources.working_set installed_packages_list = [{'name': i.key, 'version': i.version, } for i in installed_packages] info['os']['name'] = os_name info['os']['version'] = platform.version() info['os']['bits'] = '64' if is_os_64bit() else '32' info['driver']['name'] = "NI-SCOPE" info['driver']['version'] = driver_version info['module']['name'] = 'niscope' info['module']['version'] = "1.4.2.dev0" info['python']['version'] = sys.version info['python']['bits'] = '64' if is_python_64bit() else '32' info['python']['is_venv'] = is_venv() info['python']['packages'] = installed_packages_list return info
def initsysfonts_win32(): """initialize fonts dictionary on Windows""" fontdir = join(os.environ.get('WINDIR', 'C:\\Windows'), 'Fonts') TrueType_suffix = '(TrueType)' mods = ('demibold', 'narrow', 'light', 'unicode', 'bt', 'mt') fonts = {} # add fonts entered in the registry # find valid registry keys containing font information. # http://docs.python.org/lib/module-sys.html # 0 (VER_PLATFORM_WIN32s) Win32s on Windows 3.1 # 1 (VER_PLATFORM_WIN32_WINDOWS) Windows 95/98/ME # 2 (VER_PLATFORM_WIN32_NT) Windows NT/2000/XP # 3 (VER_PLATFORM_WIN32_CE) Windows CE if sys.getwindowsversion()[0] == 1: key_name = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Fonts" else: key_name = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts" key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key_name) for i in xrange_(_winreg.QueryInfoKey(key)[1]): try: # name is the font's name e.g. Times New Roman (TrueType) # font is the font's filename e.g. times.ttf name, font = _winreg.EnumValue(key, i)[0:2] except EnvironmentError: break # try to handle windows unicode strings for file names with # international characters if PY_MAJOR_VERSION < 3: # here are two documents with some information about it: # http://www.python.org/peps/pep-0277.html # https://www.microsoft.com/technet/archive/interopmigration/linux/mvc/lintowin.mspx#ECAA try: font = str(font) except UnicodeEncodeError: # MBCS is the windows encoding for unicode file names. try: font = font.encode('MBCS') except: # no success with str or MBCS encoding... skip this font. continue if splitext(font)[1].lower() not in OpenType_extensions: continue if not dirname(font): font = join(fontdir, font) if name.endswith(TrueType_suffix): name = name.rstrip(TrueType_suffix).rstrip() name = name.lower().split() bold = italic = 0 for m in mods: if m in name: name.remove(m) if 'bold' in name: name.remove('bold') bold = 1 if 'italic' in name: name.remove('italic') italic = 1 name = ''.join(name) name = _simplename(name) _addfont(name, bold, italic, font, fonts) return fonts
""" clone Path to vmx file Create a copy of the VM Path to destination vmx file full|linked [Snapshot name] """ return self.do('clone', dest_vmx, mode, snap_name) if sys.platform == "win32": # get vmrun.exe's full path via registry import winreg reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) try: rh = winreg.OpenKey(reg, r'SOFTWARE\VMware, Inc.\VMware Workstation') try: vw_dir = winreg.QueryValueEx(rh, 'InstallPath')[0] finally: winreg.CloseKey(rh) finally: reg.Close() if vw_dir != '': VMRUN_PATH = vw_dir + 'vmrun.exe' else: if "PATH" in os.environ: for path in os.environ["PATH"].split(os.pathsep): tmp_file = path + os.sep + "vmrun" if os.path.exists(tmp_file): VMRUN_PATH = tmp_file
elif runstatus == ZOSAPI.Tools.RunStatus.FailedToStart: print('Failed To Start!') elif runstatus == ZOSAPI.Tools.RunStatus.InvalidTimeout: print('Invalid Timeout') else: print('Timed Out!') print('Progress: ', ToolExportCAD.Progress) # If the exporting is not completed and can be cancelled, cancel the work if (runstatus != ZOSAPI.Tools.RunStatus.Completed and ToolExportCAD.CanCancel): # noqa ToolExportCAD.Cancel() # Close the tool ToolExportCAD.Close() aKey = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER), r"Software\Zemax", 0, winreg.KEY_READ) zemaxData = winreg.QueryValueEx(aKey, 'ZemaxRoot') NetHelper = os.path.join(os.sep, zemaxData[0], r'ZOS-API\Libraries\ZOSAPI_NetHelper.dll') winreg.CloseKey(aKey) # add the NetHelper DLL for locating the OpticStudio install folder clr.AddReference(NetHelper) import ZOSAPI_NetHelper # noqa pathToInstall = '' success = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize(pathToInstall) zemaxDir = '' if success: zemaxDir = ZOSAPI_NetHelper.ZOSAPI_Initializer.GetZemaxDirectory()
root_dir as app_root, app_start, icon_gotox, direct_ipdb, direct_domains, get_dirname, getlogger, load_config as _load_config) logging = getlogger() app_start = os.path.join(app_root, 'start.py') create_shortcut_js = os.path.join(app_root, 'create_shortcut.vbs') refresh_proxy = os.path.join(app_root, 'launcher', 'refresh_proxy_win.py') import winreg from subprocess import Popen from local import __version__ as gotoxver SET_PATH = r'Software\Microsoft\Windows\CurrentVersion\Internet Settings' SETTINGS = winreg.OpenKey(winreg.HKEY_CURRENT_USER, SET_PATH, 0, winreg.KEY_ALL_ACCESS) ProxyOverride = ';'.join( ['localhost', '127.*', '192.168.*', '10.*'] + ['100.%d.*' % (64 + n) for n in range(1 << 6)] + ['172.%d.*' % (16 + n) for n in range(1 << 4)]) class proxy_server: __slots__ = 'type', 'pac', 'http', 'https', 'ftp', 'socks' def __init__(self, server_str, http_only=None): if not server_str: self.type = 0 return if '://' in server_str: self.type = 1 self.pac = server_str
p_info = ctypes.pointer(info) if joyGetPos(0, p_info) != 0: print("Joystick %d not plugged in." % (joy_id + 1)) # Get device capabilities. caps = JOYCAPS() if joyGetDevCaps(joy_id, ctypes.pointer(caps), ctypes.sizeof(JOYCAPS)) != 0: print("Failed to get device capabilities.") print("Driver name:", caps.szPname) # Fetch the name from registry. key = None if len(caps.szRegKey) > 0: try: key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "System\\CurrentControlSet\\Control\\MediaResources\\Joystick\\%s\\CurrentJoystickSettings" % (caps.szRegKey)) except WindowsError: key = None if key: oem_name = winreg.QueryValueEx(key, "Joystick%dOEMName" % (joy_id + 1)) if oem_name: key2 = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "System\\CurrentControlSet\\Control\\MediaProperties\\PrivateProperties\\Joystick\\OEM\\%s" % (oem_name[0])) if key2: oem_name = winreg.QueryValueEx(key2, "OEMName") print("OEM name:", oem_name[0]) key2.Close() # Set the initial button states. button_states = {} for b in range(caps.wNumButtons):
def check(cls): try: winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"CLSID\%s" % CLSID_TTSEnumerator).Close() return True except WindowsError: return False
def main(): FULLDIR = "{}\\{}".format(MAINDIR, PROJECTDIR) print(""" ###################################### # MTS Development Environment Setup # ###################################### This script will create your MTS dev environment for you. Before you run this, you should already have: - A properly set up P-drive If you have not done those things yet, please abort this script in the next step and do so first. This script will create two hard links on your system, both pointing to your MTS project folder: [Arma 3 installation directory]\\{} => MTS project folder P:\\{} => MTS project folder It will also copy the required CBA includes to {}, if you do not have the CBA source code already.""" .format(FULLDIR, FULLDIR, CBA)) print("\n") try: reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) key = winreg.OpenKey( reg, r"SOFTWARE\Wow6432Node\bohemia interactive\arma 3") armapath = winreg.EnumValue(key, 1)[1] except: print("Failed to determine Arma 3 Path.") return 1 if not os.path.exists("P:\\"): print("No P-drive detected.") return 2 scriptpath = os.path.realpath(__file__) projectpath = os.path.dirname(os.path.dirname(scriptpath)) print("# Detected Paths:") print(" Arma Path: {}".format(armapath)) print(" Project Path: {}".format(projectpath)) repl = input("\nAre these correct? (y/n): ") if repl.lower() != "y": return 3 print("\n# Creating links ...") if os.path.exists("P:\\{}\\{}".format(MAINDIR, PROJECTDIR)): print("Link on P: already exists. Please finish the setup manually.") return 4 if os.path.exists(os.path.join(armapath, MAINDIR, PROJECTDIR)): print( "Link in Arma directory already exists. Please finish the setup manually." ) return 5 try: if not os.path.exists("P:\\{}".format(MAINDIR)): os.mkdir("P:\\{}".format(MAINDIR)) if not os.path.exists(os.path.join(armapath, MAINDIR)): os.mkdir(os.path.join(armapath, MAINDIR)) subprocess.call([ "cmd", "/c", "mklink", "/J", "P:\\{}\\{}".format(MAINDIR, PROJECTDIR), projectpath ]) subprocess.call([ "cmd", "/c", "mklink", "/J", os.path.join(armapath, MAINDIR, PROJECTDIR), projectpath ]) except: raise print( "Something went wrong during the link creation. Please finish the setup manually." ) return 6 print("# Links created successfully.") print("\n# Copying required CBA includes ...") if os.path.exists(CBA): print("{} already exists, skipping.".format(CBA)) return -1 try: shutil.copytree(os.path.join(projectpath, "tools", "cba"), CBA) except: raise print( "Something went wrong while copying CBA includes. Please copy tools\\cba to {} manually." .format(CBA)) return 7 print("# CBA includes copied successfully to {}.".format(CBA)) return 0
def find_lib(): dll = None plugin_path = os.environ.get('PYTHON_VLC_MODULE_PATH', None) if 'PYTHON_VLC_LIB_PATH' in os.environ: try: dll = ctypes.CDLL(os.environ['PYTHON_VLC_LIB_PATH']) except OSError: logger.error( "Cannot load lib specified by PYTHON_VLC_LIB_PATH env. variable" ) sys.exit(1) if plugin_path and not os.path.isdir(plugin_path): logger.error("Invalid PYTHON_VLC_MODULE_PATH specified. Please fix.") sys.exit(1) if dll is not None: return dll, plugin_path if sys.platform.startswith('win'): libname = 'libvlc.dll' p = find_library(libname) if p is None: try: # some registry settings # leaner than win32api, win32con if PYTHON3: import winreg as w else: import _winreg as w for r in w.HKEY_LOCAL_MACHINE, w.HKEY_CURRENT_USER: try: r = w.OpenKey(r, 'Software\\VideoLAN\\VLC') plugin_path, _ = w.QueryValueEx(r, 'InstallDir') w.CloseKey(r) break except w.error: pass except ImportError: # no PyWin32 pass if plugin_path is None: # try some standard locations. programfiles = os.environ["ProgramFiles"] homedir = os.environ["HOMEDRIVE"] for p in ('{programfiles}\\VideoLan{libname}', 'hotexamples_com:\\VideoLan{libname}', '{programfiles}{libname}', 'hotexamples_com:{libname}'): p = p.format(homedir=homedir, programfiles=programfiles, libname='\\VLC\\' + libname) if os.path.exists(p): plugin_path = os.path.dirname(p) break if plugin_path is not None: # try loading p = os.getcwd() os.chdir(plugin_path) # if chdir failed, this will raise an exception dll = ctypes.CDLL(libname) # restore cwd after dll has been loaded os.chdir(p) else: # may fail dll = ctypes.CDLL(libname) else: plugin_path = os.path.dirname(p) dll = ctypes.CDLL(p) elif sys.platform.startswith('darwin'): # FIXME: should find a means to configure path d = '/Applications/VLC.app/Contents/MacOS/' c = d + 'lib/libvlccore.dylib' p = d + 'lib/libvlc.dylib' if os.path.exists(p) and os.path.exists(c): # pre-load libvlccore VLC 2.2.8+ ctypes.CDLL(c) dll = ctypes.CDLL(p) for p in ('modules', 'plugins'): p = d + p if os.path.isdir(p): plugin_path = p break else: # hope, some [DY]LD_LIBRARY_PATH is set... # pre-load libvlccore VLC 2.2.8+ ctypes.CDLL('libvlccore.dylib') dll = ctypes.CDLL('libvlc.dylib') else: # All other OSes (linux, freebsd...) p = find_library('vlc') try: dll = ctypes.CDLL(p) except OSError: # may fail dll = None if dll is None: try: dll = ctypes.CDLL('libvlc.so.5') except: raise NotImplementedError('Cannot find libvlc lib') return (dll, plugin_path)
import datetime import re from multiprocessing import Process import winreg import os import psutil import logging import win32evtlog # requires pywin32 pre-installed import urllib3 import signal urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) val = False hKeys = [] hKeys_run = [] hKeys.append(winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Compatibility Assistant\\Store"))#AYTO hKeys.append(winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache")) hKeys.append(winreg.OpenKey(winreg.HKEY_USERS, "S-1-5-21-733142866-2450513131-3585932315-1001_Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache")) hKeys.append(winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache")) hKeys_run.append(winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Run")) hKeys_run.append(winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run")) hKeys_run.append(winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce")) hKeys_run.append(winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce")) paths = [] no_path = []