def setWallpaper(img): regKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) # 0=居中 1=平铺 2=延伸 win32api.RegSetValueEx(regKey, "WallpaperStyle", 0, win32con.REG_SZ, "2") win32api.RegCloseKey(regKey) try: win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img, win32con.SPIF_SENDWININICHANGE) except: getWallpaper()
def GetServiceCustomOption(serviceName, option, defaultValue = None): # First param may also be a service class/instance. # This allows services to pass "self" try: serviceName = serviceName._svc_name_ except AttributeError: pass key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName) try: try: return win32api.RegQueryValueEx(key, option)[0] except win32api.error: # No value. return defaultValue finally: win32api.RegCloseKey(key)
def AddSourceToRegistry(appName, msgDLL=None, eventLogType="Application", eventLogFlags=None): """Add a source of messages to the event log. Allows Python program to register a custom source of messages in the registry. You must also provide the DLL name that has the message table, so the full message text appears in the event log. Note that the win32evtlog.pyd file has a number of string entries with just "%1" built in, so many Python programs can simply use this DLL. Disadvantages are that you do not get language translation, and the full text is stored in the event log, blowing the size of the log up. """ # When an application uses the RegisterEventSource or OpenEventLog # function to get a handle of an event log, the event loggging service # searches for the specified source name in the registry. You can add a # new source name to the registry by opening a new registry subkey # under the Application key and adding registry values to the new # subkey. if msgDLL is None: msgDLL = win32evtlog.__file__ # Create a new key for our application hkey = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, \ "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName)) # Add the Event-ID message-file name to the subkey. win32api.RegSetValueEx( hkey, "EventMessageFile", # value name \ 0, # reserved \ win32con.REG_EXPAND_SZ, # value type \ msgDLL) # Set the supported types flags and add it to the subkey. if eventLogFlags is None: eventLogFlags = win32evtlog.EVENTLOG_ERROR_TYPE | win32evtlog.EVENTLOG_WARNING_TYPE | win32evtlog.EVENTLOG_INFORMATION_TYPE win32api.RegSetValueEx( hkey, # subkey handle \ "TypesSupported", # value name \ 0, # reserved \ win32con.REG_DWORD, # value type \ eventLogFlags) win32api.RegCloseKey(hkey)
def FindDllClsid(dllname): key = 0 hSubKey = 0 ret = [] try: #print "CLSID\\%s\\ProID" % clsid.upper() key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "CLSID") num = 0 while True: try: keyName = win32api.RegEnumKey(key, num) #print keyName if num != 0: subKey = win32api.RegOpenKey(key, keyName) #print subKey num1 = 0 while True: try: name = win32api.RegEnumKey(subKey, num1) num1 += 1 #print name dll = "" progid = "" if name.lower() == "progid": progid = win32api.RegQueryValue(subKey, name) #print progid if name.lower() == "inprocserver32": dll = win32api.RegQueryValue(subKey, name) #print dll if dll.lower() == dllname.lower(): return (progid, keyName) except: break win32api.RegCloseKey(subKey) num += 1 except: print 222 break; #hSubKey = win32api.RegOpenKey(key, 0) #value, typ = win32api.RegQueryValueEx(hSubKey, None) #print value except Exception, e: #print e pass
def CheckPythonPaths(verbose): if verbose: print("Python Paths:") # Check the core path if verbose: print("\tCore Path:", end=" ") try: appPath = win32api.RegQueryValue( regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath") except win32api.error as exc: print("** does not exist - ", exc.strerror) problem = CheckPathString(appPath) if problem: print(problem) else: if verbose: print(appPath) key = win32api.RegOpenKey( regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath", 0, win32con.KEY_READ, ) try: keyNo = 0 while 1: try: appName = win32api.RegEnumKey(key, keyNo) appPath = win32api.RegQueryValue(key, appName) if verbose: print("\t" + appName + ":", end=" ") if appPath: problem = CheckPathString(appPath) if problem: print(problem) else: if verbose: print(appPath) else: if verbose: print("(empty)") keyNo = keyNo + 1 except win32api.error: break finally: win32api.RegCloseKey(key)
def set_wallpaper_from_bmp(bmp_path): try: # 打开指定注册表路径 hKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) # 最后的参数:2拉伸,0居中,6适应,10填充,0平铺 win32api.RegSetValueEx(hKey, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 最后的参数:1表示平铺,拉伸居中等都是0 win32api.RegSetValueEx(hKey, "TileWallpaper", 0, win32con.REG_SZ, "0") # 刷新桌面 win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmp_path, win32con.SPIF_SENDWININICHANGE) win32api.RegCloseKey(hKey) return True except: logging.exception(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) return False
def win_getenv_system(varname, default=''): import win32api import win32con v = default try: rkey = win32api.RegOpenKey( win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment') try: v = str(win32api.RegQueryValueEx(rkey, varname)[0]) v = win32api.ExpandEnvironmentStrings(v) except: pass finally: win32api.RegCloseKey(rkey) return v
def get_applications_from_default_action(extension): ret = None hkey = None try: hkey = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, extension, 0, win32con.KEY_READ) (value, _) = win32api.RegQueryValueEx(hkey, None) ret = value except: pass finally: if hkey is not None: win32api.RegCloseKey(hkey) return ret
def base(): hKey = None keyFound = True try: hKey = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, BIND_SUBKEY) except: keyFound = False if keyFound: try: (namedBase, _) = win32api.RegQueryValueEx(hKey, "InstallDir") except: keyFound = False win32api.RegCloseKey(hKey) if keyFound: return namedBase return win32api.GetSystemDirectory()
def infostartup(self): self.isuphandle = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, self.sccss + self.sserv, 0, win32con.KEY_READ) self.isuptype = win32api.RegQueryValueEx(self.isuphandle, "Start")[0] win32api.RegCloseKey(self.isuphandle) if self.isuptype == 0: return "boot" elif self.isuptype == 1: return "system" elif self.isuptype == 2: return "automatic" elif self.isuptype == 3: return "manual" elif self.isuptype == 4: return "disabled"
def SetServiceCustomOption(serviceName, option, value): try: serviceName = serviceName._svc_name_ except AttributeError: pass key = win32api.RegCreateKey( win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName, ) try: if type(value) == type(0): win32api.RegSetValueEx(key, option, 0, win32con.REG_DWORD, value) else: win32api.RegSetValueEx(key, option, 0, win32con.REG_SZ, value) finally: win32api.RegCloseKey(key)
def setWallpaper(img): regKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) # 0=居中 1=平铺 2=拉伸 win32api.RegSetValueEx(regKey, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 0=居中 1=平铺 2=拉伸 win32api.RegSetValueEx(regKey, "TileWallpaper", 0, win32con.REG_SZ, "0") win32api.RegCloseKey(regKey) # 设置桌面壁纸并更新 try: win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img, win32con.SPIF_SENDWININICHANGE) except: win32api.MessageBox(0, "未抓取到圖片!!", "錯誤", win32con.MB_ICONWARNING) print("NO Picture")
def get_ie_history(self): reg_root = win32con.HKEY_CURRENT_USER reg_path = r"Software\\Microsoft\\Internet Explorer\\typedURLs" reg_flags = win32con.WRITE_OWNER | win32con.KEY_WOW64_64KEY | win32con.KEY_ALL_ACCESS try: key = win32api.RegOpenKeyEx(reg_root, reg_path, 0, reg_flags) i = 0 while True: url = (win32api.RegEnumValue(key, i)) command_list.append(url[1]) i += 1 win32api.RegCloseKey(key) except Exception: pass return command_list
def GetSubList(self): keyStr = regutil.BuildDefaultPythonKey() + "\\PythonPath" hKey = win32api.RegOpenKey(regutil.GetRootKey(), keyStr) try: ret = [] ret.append(HLIProjectRoot("", "Standard Python Library")) # The core path. index = 0 while 1: try: ret.append(HLIProjectRoot(win32api.RegEnumKey(hKey, index))) index = index + 1 except win32api.error: break return ret finally: win32api.RegCloseKey(hKey)
def startingUpWindow(self): """实现开机自启""" name = 'oftpublic' # 要添加的项值名称 print() path = os.getcwd() + '\getip.exe' # 要添加的exe路径 # 注册表项名 KeyName = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' # 异常处理 try: key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, KeyName, 0, win32con.KEY_ALL_ACCESS) win32api.RegSetValueEx(key, name, 0, win32con.REG_SZ, path) win32api.RegCloseKey(key) except: print('error') print('开机启动成功!')
def SetupCore(searchPaths): """Setup the core Python information in the registry. This function makes no assumptions about the current state of sys.path. After this function has completed, you should have access to the standard Python library, and the standard Win32 extensions """ import sys for path in searchPaths: sys.path.append(path) import os import regutil, win32api, win32con installPath, corePaths = LocatePythonCore(searchPaths) # Register the core Pythonpath. print(corePaths) regutil.RegisterNamedPath(None, ";".join(corePaths)) # Register the install path. hKey = win32api.RegCreateKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey()) try: # Core Paths. win32api.RegSetValue(hKey, "InstallPath", win32con.REG_SZ, installPath) finally: win32api.RegCloseKey(hKey) # Register the win32 core paths. win32paths = ( os.path.abspath(os.path.split(win32api.__file__)[0]) + ";" + os.path.abspath( os.path.split(LocateFileName("win32con.py;win32con.pyc", sys.path))[0])) # Python has builtin support for finding a "DLLs" directory, but # not a PCBuild. Having it in the core paths means it is ignored when # an EXE not in the Python dir is hosting us - so we add it as a named # value check = os.path.join(sys.prefix, "PCBuild") if "64 bit" in sys.version: check = os.path.join(check, "amd64") if os.path.isdir(check): regutil.RegisterNamedPath("PCBuild", check)
def get_sensitive_registry_key(self): keys = [] runkeys_hklm = self.definePath() # access either in read only mode, or in write mode accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE accessWrite = win32con.KEY_WRITE | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE # Loop through all keys to check for keyPath in runkeys_hklm: is_key_writable = False # check if the registry key has writable access try: hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyPath, 0, accessWrite) is_key_writable = keyPath except: try: hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyPath, 0, accessRead) except: continue # retrieve all value of the registry key try: num = win32api.RegQueryInfoKey(hkey)[1] # loop through number of value in the key for x in range(0, num): k = win32api.RegEnumValue(hkey, x) stk = Registry_key() if is_key_writable: stk.is_key_writable = is_key_writable stk.key = keyPath stk.name = k[0] stk.full_path = k[1] stk.paths = get_path_info(k[1]) keys.append(stk) win32api.RegCloseKey(hkey) except win32api.error: pass return keys
def set_pc_id(): reg_root = win32con.HKEY_LOCAL_MACHINE reg_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AutoTax.exe" reg_flags = win32con.WRITE_OWNER | win32con.KEY_WOW64_64KEY | win32con.KEY_ALL_ACCESS try: #直接创建(若存在,则为获取) key, _ = win32api.RegCreateKeyEx(reg_root, reg_path, reg_flags) #设置项 uid = uuid.uuid1() win32api.RegSetValueEx(key, "uid", 0, win32con.REG_SZ, str(uid)) #关闭 win32api.RegCloseKey(key) return uid except: return ''
def GetRPathPy(): keyName = "SOFTWARE\\R-core\\R" kHandle = None try: kHandle = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, keyName, 0, win32con.KEY_READ) except: try: kHandle = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, keyName, 0, win32con.KEY_READ) except: vim.command("let s:rinstallpath = 'Not found'") if kHandle: (kname, rpath, vtype) = win32api.RegEnumValue(kHandle, 0) win32api.RegCloseKey(kHandle) if kname == 'InstallPath': vim.command("let s:rinstallpath = '" + rpath + "'") else: vim.command("let s:rinstallpath = 'Not found'")
def GetSubList(self): hkey = win32api.RegOpenKey(self.keyRoot, self.keyName) win32ui.DoWaitCursor(1) try: keyNum = 0 ret = [] while 1: try: key = win32api.RegEnumKey(hkey, keyNum) except win32api.error: break ret.append(HLIRegistryKey(self.keyRoot, self.keyName + "\\" + key, key)) keyNum = keyNum + 1 finally: win32api.RegCloseKey(hkey) win32ui.DoWaitCursor(0) return ret
def read_key_registry_autostart(self): global PATH_EXE data = None try: regkey = win32api.RegOpenKeyEx( win32con.HKEY_CURRENT_USER, "SOFTWARE\Microsoft\Windows\CurrentVersion\Run", 0, win32con.KEY_READ) (data, key) = win32api.RegQueryValueEx(regkey, 'DiabloS60') win32api.RegCloseKey(regkey) except: pass if data == PATH_EXE: self.checkbutton.set_active(True)
def _set_winreg_key(self, name, value, keyname='PythonClass'): # see "collective.buildout.cluster.ClusterBase" # TODO: use Python module "_winreg" def open_key(keyname=None): keypath = ('System\\CurrentControlSet\\Services\\' + self._get_service_name()) if keyname: keypath += ('\\' + keyname) return win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keypath, 0, win32con.KEY_ALL_ACCESS) key = open_key(keyname) try: win32api.RegSetValueEx(key, name, 0, win32con.REG_SZ, value) finally: win32api.RegCloseKey(key)
def _win32_current_app_path(edition): assert edition in editions.EDITIONS, repr(edition) edition_full_name = editions.EDITIONS[edition].full_name try: fbkey = win32api.RegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\\FreeBrie\\{}'.format(edition_full_name)) instdir = str(win32api.RegQueryValueEx(fbkey, 'Install_Dir')[0]) except Exception: logger.exception('application install path not in win32 register') instdir = '' finally: win32api.RegCloseKey(fbkey) logger.debug('current_app_path() = %r', instdir) return instdir
def FormatMessage(eventLogRecord, logType="Application"): """Given a tuple from ReadEventLog, and optionally where the event record came from, load the message, and process message inserts. Note that this function may raise win32api.error. See also the function SafeFormatMessage which will return None if the message can not be processed. """ # From the event log source name, we know the name of the registry # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % ( logType, eventLogRecord.SourceName) # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) try: dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";") # Win2k etc appear to allow multiple DLL names data = None for dllName in dllNames: try: # Expand environment variable strings in the message DLL path name, # in case any are there. dllName = win32api.ExpandEnvironmentStrings(dllName) dllHandle = win32api.LoadLibraryEx( dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE) try: data = win32api.FormatMessageW( win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts) finally: win32api.FreeLibrary(dllHandle) except win32api.error: pass # Not in this DLL - try the next if data is not None: break finally: win32api.RegCloseKey(handle) return data or '' # Don't want "None" ever being returned.
def StartRPy(): global Rterm if vim.eval("g:vimrplugin_Rterm") == "1": Rterm = True else: Rterm = False rpath = vim.eval("g:rplugin_Rgui") rpath = rpath.replace("\\", "\\\\") rargs = ['"' + rpath + '"'] r_args = vim.eval("b:rplugin_r_args") if r_args != " ": r_args = r_args.split(' ') i = 0 alen = len(r_args) while i < alen: rargs.append(r_args[i]) i = i + 1 kHandle = None keyName = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders" try: kHandle = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, keyName, 0, win32con.KEY_READ) except: vim.command("RWarningMsg('Personal folder not found in registry')") if kHandle: i = 0 folder = "none" while folder != "Personal": try: (folder, fpath, vtype) = win32api.RegEnumValue(kHandle, i) except: break i = i + 1 win32api.RegCloseKey(kHandle) if folder == "Personal": rargs.append('HOME="' + fpath + '"') else: vim.command("RWarningMsg('Personal folder not found in registry')") if os.path.isfile(rpath): os.spawnv(os.P_NOWAIT, rpath, rargs) else: vim.command("echoerr 'File ' . g:rplugin_Rgui . ' not found.'")
def setenv_var(varname, value): try: rkey = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment',0 ,win32con.KEY_WRITE) try: win32api.RegSetValueEx(rkey, varname, 0, win32con.REG_SZ, value) print("Saved ", varname) return True except Exception: pass except Exception: print("No access to save environment variables, if you want to save them, please run this once in administrator mode") print("Running bot without save\n") finally: try: win32api.RegCloseKey(rkey) except UnboundLocalError: pass return False
def UpdateForRegItem(self, item): self.DeleteAllItems() hkey = win32api.RegOpenKey(item.keyRoot, item.keyName) try: valNum = 0 ret = [] while 1: try: res = win32api.RegEnumValue(hkey, valNum) except win32api.error: break name = res[0] if not name: name = "(Default)" self.InsertItem(valNum, name) self.SetItemText(valNum, 1, str(res[1])) valNum = valNum + 1 finally: win32api.RegCloseKey(hkey)
def configure_nici(): path = r"Software\Novell\NICI" hkey = None try: Reg.CreateKeyR(win32con.HKEY_LOCAL_MACHINE, path) hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, path, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(hkey, "EnableUserProfileDirectory", 0, win32con.REG_DWORD, 1) except: return False finally: if hkey is not None: win32api.RegCloseKey(hkey) return True
def setWallpaper(img): bmpImage = Image.open(img) newPath = img.replace('.png', '.bmp') bmpImage.save(newPath, "BMP") img = newPath print(img) regKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) # 0=居中 1=平铺 2=拉伸 win32api.RegSetValueEx(regKey, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 0=居中 1=平铺 2=拉伸 win32api.RegSetValueEx(regKey, "TileWallpaper", 0, win32con.REG_SZ, "0") win32api.RegCloseKey(regKey) # 设置桌面壁纸并更新 win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img, win32con.SPIF_SENDWININICHANGE)
def addfile2autorun():#注册表的修改 #global run_path runpath = "Software\Microsoft\Windows\CurrentVersion\Run" hKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, runpath, 0, win32con.KEY_ALL_ACCESS) exe_path = sys.argv[0] #exe_path = run_path + '\\' + exeName + '.exe' #print(exe_path) #读取键值 try: value, key_type = win32api.RegQueryValueEx(hKey, exeName) except Exception as e: win32api.RegSetValueEx(hKey,exeName, 0, win32con.REG_SZ, exe_path) #log2(exe_path) #win32api.RegDeleteValue(hKey, exeName) win32api.RegCloseKey(hKey)