예제 #1
0
    def set_new_env(self,path):
        '''
        set env now
        :param path:
        :return:
        '''
        try:
            #路径检测
            print(path)
            if not self.path_check(path):return False
            if path not in self.jdk_list:

                self.savato_json(path)
                self.jdk_list.append(path)

            orgin_path=";".join(self.envstrlist)
            new_path=path+"\\bin"+';'+orgin_path
            wg.SetValueEx(self.sys_handle, 'path', '', self.envint, new_path)
            new_CLASSPATH=".;"+path+"\\lib"
            wg.SetValueEx(self.sys_handle, 'CLASSPATH', '', self.envint, new_CLASSPATH)
            wg.SetValueEx(self.sys_handle, 'JAVA_HOME', '', self.envint, path)
            wg.FlushKey(self.sys_handle)
            self.__broadcast()

            return True
        except:
            return False
예제 #2
0
        def _save(self):
            """
            Save '_paths' System Path value into registry.

            Params:
                None

            Returns:
                None

            Raises:
                EnvironmentError if the user is not an "admin" or the admin check fails
                WindowsError if an error occurred when try to edit System Path value
            """
            # Admin check
            is_admin = False
            try:
                is_admin = ctypes.windll.shell32.IsUserAnAdmin()
            except Exception:
                raise EnvironmentError(
                    'Windows OS detected, but admin check failed')
            if not is_admin:
                raise EnvironmentError(
                    'Edit System Path value requires "Admin" privileges')

            # Write on System Path
            value = os.pathsep.join(self._paths) + os.pathsep
            with winreg.OpenKeyEx(self._root_key, self._sub_key, 0,
                                  winreg.KEY_WRITE) as key:
                winreg.SetValueEx(key, self._value_name, 0,
                                  winreg.REG_EXPAND_SZ, value)
                winreg.FlushKey(key)
예제 #3
0
    def testSandboxSecurity(self):
        with contextlib.ExitStack() as stack:
            port = 12395
            sock = stack.enter_context(
                socket.socket(socket.AF_INET, socket.SOCK_STREAM))
            sock.bind(("", port))
            sock.listen()

            sub_key = "Software\\SandboxTest"
            key = winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE,
                                     sub_key,
                                     access=winreg.KEY_ALL_ACCESS)
            winreg.SetValueEx(key, "foo", 0, winreg.REG_SZ, "bar")
            winreg.FlushKey(key)
            stack.callback(winreg.DeleteKey, winreg.HKEY_LOCAL_MACHINE,
                           sub_key)
            stack.callback(winreg.CloseKey, key)
            stack.callback(winreg.DeleteValue, key, "foo")

            args = [
                sys.executable, "-m",
                "grr_response_client.unprivileged.windows.sandbox_unprivileged_test_lib",
                "--localhost_port",
                str(port), "--registry_sub_key", sub_key
            ]

            p = process.Process(args, [])
            exit_code = p.Wait()
            self.assertEqual(exit_code, 0)
예제 #4
0
 def register_at(root_shell: str, label_values: List[_LabelValuePair],
                 subkey_path: str):
     subkey = '\\'.join([root_shell, subkey_path])
     item = winreg.CreateKey(winreg.HKEY_CURRENT_USER, subkey)
     for i in label_values:
         winreg.SetValueEx(item, i.label, 0, winreg.REG_SZ, i.value)
     winreg.FlushKey(item)
예제 #5
0
    def remove_dir_from_win_path(self, remove_dir):
        import winreg
        try:
            env = None
            path = None
            env = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, 'Environment', 0,
                                   winreg.KEY_SET_VALUE | winreg.KEY_READ)
            path = winreg.QueryValueEx(env, 'Path')[0]

            path_lower = path.lower()
            remove_dir = remove_dir.replace('/', '\\')
            remove_dir_lower = remove_dir.lower()
            start_pos = path_lower.find(remove_dir_lower)
            if (start_pos >= 0):
                length = len(remove_dir_lower)
                need_remove = path[start_pos:(start_pos + length)]
                path = path.replace(need_remove, '')
                path = path.replace(';;', ';')
                winreg.SetValueEx(env, 'Path', 0, winreg.REG_SZ, path)
                winreg.FlushKey(env)
            winreg.CloseKey(env)

            print('  ->Remove directory \"%s\" from PATH!\n' % remove_dir)
        except Exception:
            print('  ->Remove directory \"%s\" from PATH failed!\n' %
                  remove_dir)
예제 #6
0
def reg_replace(bits, kname, vname, value):
    try:
        import winreg
    except ImportError:
        import _winreg as winreg

    access = winreg.KEY_READ | winreg.KEY_WRITE
    access |= {
        32: winreg.KEY_WOW64_32KEY,
        64: winreg.KEY_WOW64_64KEY,
    }[bits]

    key = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, kname, 0, access)

    try:
        prev, type = winreg.QueryValueEx(key, vname)
        assert type == winreg.REG_SZ, type
    except WindowsError as e:
        if e.errno != errno.ENOENT:
            raise
        prev = None

    winreg.SetValueEx(key, vname, 0, winreg.REG_SZ, value)
    winreg.FlushKey(key)
    _log.debug('%s SetValue %s.%s = %s', bits, kname, vname, value)

    return prev
예제 #7
0
def ChangeREG(ssh):
    local_location = os.popen('where {}'.format(app_name)).read().strip('\n')
    assert local_location, '没有找到{}'.format(app_name)
    winreg.CreateKey(winreg.HKEY_CLASSES_ROOT,
                     r'{}\shell\open\command'.format(app_name))
    putty_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, app_name, 0,
                               winreg.KEY_ALL_ACCESS)
    winreg.SetValueEx(putty_key, 'URL Protocol', 0, winreg.REG_SZ,
                      local_location)
    winreg.FlushKey(putty_key)
    putty_key.Close()
    command_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT,
                                 r'{}\shell\open\command'.format(app_name), 0,
                                 winreg.KEY_ALL_ACCESS)
    winreg.SetValueEx(command_key, '', 0, winreg.REG_SZ, local_location)
    winreg.FlushKey(command_key)
    command_key.Close()
예제 #8
0
def registerToFile(templateName):
    """
	templateName must have extension

	TODO: windows only allows one "new" per extension.  Perhaps make some kind of
	selector ui??

	NOTE: I had to do a full restart to make this work.  Is there a better way??

	See also:
		http://mc-computing.com/WinExplorer/WinExplorerRegistry_ShellNew.htm
	NOTE:
		besides the things listed, there are also
		Handler = CLSID
		IconPath = path
		ItemName = new item name
		MenuText = whatever
		Config->DontRename = ???
	"""
    extension = '.' + templateName.rsplit('.', 1)[1]
    try:
        extensionkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, extension)
    except WindowsError as e:
        print(e)
        extensionkey = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, extension)
    # todo: follow the default value and get a new key
    # create or open ShellNew
    try:
        key = winreg.OpenKey(extensionkey, 'ShellNew')
        # since it is present:
        #	1) copy it to ShellNew.N
        newkey = winreg.CreateKey(extensionkey,
                                  _nextShellNewName(extensionkey))
        #	2) create a ShellNew.N+1 for the new stuff below
        newkey = winreg.CreateKey(extensionkey,
                                  _nextShellNewName(extensionkey))
        #	3) point original ShellNew to multimenu.py
    except WindowsError as e2:
        if str(e2).find(
                '[Error 2]') >= 0:  # did not find the key, so create it
            try:
                newkey = winreg.CreateKey(key, 'ShellNew')
            except WindowsError as e2:
                if str(e2).find('[Error 5]') >= 0:
                    print(e2)
                    raise Exception('Did you forget to run as administrator?')
                raise e2
        else:
            raise e
    cmd = PYTHON_COMMAND
    cmd = cmd + '"' + HERE + 'newfiles.py" "' + templateName + '" "%v"'
    winreg.SetValue(key, 'Command', winreg.REG_SZ, cmd)
    winreg.SetValue(key, 'NullFile', winreg.REG_SZ,
                    cmd)  # not sure how necessary this is
    winreg.FlushKey(key)
예제 #9
0
    def set_windows_path(self, add_dir):
        ret = False
        import winreg
        try:
            env = None
            path = None
            env = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, 'Environment', 0,
                                   winreg.KEY_SET_VALUE | winreg.KEY_READ)
            path = winreg.QueryValueEx(env, 'Path')[0]

            # add variable if can't find it in PATH
            path_lower = path.lower()
            add_dir_lower = add_dir.lower()
            if (path_lower.find(add_dir_lower) == -1):
                path = add_dir + ';' + path
                winreg.SetValueEx(env, 'Path', 0, winreg.REG_SZ, path)
                winreg.FlushKey(env)

            winreg.CloseKey(env)
            ret = True
        except Exception:
            if not path:
                path = add_dir
                winreg.SetValueEx(env, 'Path', 0, winreg.REG_SZ, path)
                winreg.FlushKey(env)
                ret = True
            else:
                winreg.SetValueEx(env, 'Path', 0, winreg.REG_SZ, path)
                winreg.FlushKey(env)
                ret = False

            if env:
                winreg.CloseKey(env)

        if ret:
            print("  ->Add directory \"%s\" into PATH succeed!\n" % add_dir)
        else:
            print("  ->Add directory \"%s\" into PATH failed!\n" % add_dir)
예제 #10
0
    def set_settings_directory(path):
        if PLATFORM == "Windows":
            program_key = winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER,
                                             rf"SOFTWARE\{PROGRAM_NAME}")

            winreg.SetValueEx(program_key, "SettingsDirectory", None,
                              winreg.REG_EXPAND_SZ, str(path.resolve()))
            winreg.FlushKey(program_key)

            program_key.Close()

        elif PLATFORM == "Darwin":
            pass

        elif PLATFORM == "Linux":
            pass
예제 #11
0
    def _set_environment_variable_win32(self, key, value):
        ret = False
        import winreg
        try:
            env = None
            env = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, 'Environment', 0,
                                   winreg.KEY_SET_VALUE | winreg.KEY_READ)
            winreg.SetValueEx(env, key, 0, winreg.REG_SZ, value)
            winreg.FlushKey(env)
            winreg.CloseKey(env)
            ret = True
        except Exception:
            if env:
                winreg.CloseKey(env)
            ret = False

        return ret
예제 #12
0
    def flush(self):
        """Ensure that the key's data is flushed to disk.

        Quoting the _winreg documentation:

          It is not necessary to call FlushKey() to change a key. Registry
          changes are flushed to disk by the registry using its lazy flusher.
          Registry changes are also flushed to disk at system shutdown. 
          Unlike CloseKey(), the FlushKey() method returns only when all the
          data has been written to the registry. An application should only
          call FlushKey() if it requires absolute certainty that registry
          changes are on disk.

          If you don't know whether a FlushKey() call is required, it
          probably isn't.

        """
        _winreg.FlushKey(self.hkey)
예제 #13
0
  def SaveData(self, raw_data):
    logging.info("Writing back configuration to key %s.", self._key_spec)

    # Ensure intermediate directories exist.
    try:
      for key, value in raw_data.items():
        # TODO(user): refactor regconfig. At the moment it has no idea
        # what kind of data it's serializing and simply stringifies, them
        # assuming that bytes are simply ascii-encoded strings. Note that
        # lists (Client.tempdir_roots) also get stringified and can't
        # really be deserialized, since RegistryConfigParser doesn't
        # support deserializing anything but strings.
        if isinstance(value, bytes):
          str_value = value.decode("ascii")
        else:
          str_value = str(value)
        winreg.SetValueEx(self._AccessRootKey(), key, 0, winreg.REG_SZ,
                          str_value)

    finally:
      # Make sure changes hit the disk.
      winreg.FlushKey(self._AccessRootKey())
예제 #14
0
import winreg

# open HKEY_USERS reg entry
HKEY_USERS = winreg.ConnectRegistry(None, winreg.HKEY_USERS)
keyVal = r'S-1-5-21-2097320953-2311482321-2132067069-1001\Software\Apple Inc.\Brightness'

try:
    # jump to the subkey we're interested in. 'reserved' os always 0, access being '983103' is dec for '0xF003F', hex key for 'KEY_ALL_ACCESS''
    key = winreg.OpenKey(HKEY_USERS, keyVal, reserved=0, access=983103)
except:
    # subkey was missing, create it instead
    key = winreg.CreateKey(HKEY_USERS, keyVal)

# lastExternalBrightness is a REG_DWORD, and winreg.REG_DWORD is 4
winreg.SetValueEx(key, 'lastExternalBrightness', 0, 4, 25)
winreg.FlushKey(key)
winreg.CloseKey(key)
예제 #15
0
SHEETS = "https://sheets.googleapis.com/v4/spreadsheets"
SHEET_VALUES = SHEETS + "/{}/values/{}"
SHEET_APPEND = SHEET_VALUES + ":append"
SHEET_CLEAR = SHEET_VALUES + ":clear"
SHEET_BATCHUPDATE = SHEETS + "/{}:batchUpdate"

if not os.path.exists(LOCALPATH):
    os.makedirs(LOCALPATH)

QUERYTIMEOUT = 5


reghandle = winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\" +\
                             "Internet Settings\\ZoneMap\\Domains\\googleapis.com\\www")
winreg.SetValueEx(reghandle, "https", 0, winreg.REG_DWORD, 0)
winreg.FlushKey(reghandle)
winreg.CloseKey(reghandle)
del (reghandle)


class DriveNotFoundError(Exception):
    pass


class TeamDriveNotFoundError(Exception):
    pass


class FileNotOpenError(Exception):
    pass
예제 #16
0
def set_background(file_path):
    de = get_desktop_environment()

    if 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'])
    elif de == "windows":
        registry = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)  # open the user registry
        desktop = winreg.OpenKeyEx(registry, sub_key=r"Control Panel\desktop", reserved=0, access=winreg.KEY_WRITE) # open the "desktop" key with write access
        winreg.SetValueEx(desktop, "WallpaperStyle", "", winreg.REG_SZ, "9")  # set the preference to make it center and fit the image
        winreg.FlushKey(desktop)  # make sure the changes were all saved
        SPI_SETDESKWALLPAPER = 20 
        ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, file_path , 0)  # actually set the background image
    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
예제 #17
0
def extend_path(pypath, remove=False, verbose=0, remove_old=True,
                script=False):
    """
    extend(pypath) adds pypath to the PATH env. variable as defined in the
    registry, and then notifies applications (e.g. the desktop) of this change.
    !!! Already opened DOS-Command prompts are not updated. !!!
    Newly opened prompts will have the new path (inherited from the
    updated windows explorer desktop)
    options:
    remove (default unset), remove from PATH instead of extend PATH
    remove_old (default set), removes any (old) python paths first
    script (default unset), try to add/remove the Scripts subdirectory
        of pypath (pip, easy_install) as well
    """
    _sd = 'Scripts' # scripts subdir
    hKey = winreg.OpenKey (winreg.HKEY_LOCAL_MACHINE,
               r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
               0, winreg.KEY_READ | winreg.KEY_SET_VALUE)

    value, typ = winreg.QueryValueEx (hKey, "PATH")
    vals = value.split(';')
    assert isinstance(vals, list)
    if not remove and remove_old:
        new_vals = []
        for v in vals:
            pyexe = os.path.join(v, 'python.exe')
            if v != pypath and os.path.exists(pyexe):
                if verbose > 0:
                    print ('removing from PATH:', v)
                continue
            if script and v != os.path.join(pypath, _sd) and \
               os.path.exists(v.replace(_sd, pyexe)):
                if verbose > 0:
                    print ('removing from PATH:', v)
                continue
            new_vals.append(v)
        vals = new_vals
    if remove:
        try:
            vals.remove(pypath)
        except ValueError:
            if verbose > 0:
                print ('path element', pypath, 'not found')
            return
        if script:
            try:
                vals.remove(os.path.join(pypath, _sd))
            except ValueError:
                pass
            print ('removing from PATH:', pypath)
    else:
        if pypath in vals:
            if verbose > 0:
                print ('path element', pypath, 'already in PATH')
            return
        vals.append(pypath)
        if verbose > 1:
            print ('adding to PATH:', pypath)
        if script:
            if not pypath + '\\Scripts' in vals:
                vals.append(pypath + '\\Scripts')
            if verbose > 1:
                print ('adding to PATH:', pypath + '\\Scripts')
    winreg.SetValueEx(hKey, "PATH", 0, typ, ';'.join(vals) )
    winreg.SetValueEx(hKey, "OLDPATH", 0, typ, value )
    winreg.FlushKey(hKey)
    # notify other programs
    SendMessage = ctypes.windll.user32.SendMessageW
    HWND_BROADCAST = 0xFFFF
    WM_SETTINGCHANGE = 0x1A
    SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment')
    if verbose > 1:
        print ('Do not forget to restart any command prompts')
예제 #18
0
 def Sync(self):
   if not self._synced:
     winreg.FlushKey(_GetServiceKey())
     self._synced = True
예제 #19
0
 def flush(self) -> None:
     self._ensure_handle_exists(False)
     winreg.FlushKey(self._handle)
예제 #20
0
import sys
import os
import winreg as wg
root = os.getcwd()
if not "/MvImport/Win64_x64/;" in os.environ[
        "PATH"] and not "/MvImport/Win32_i86/;" in os.environ["PATH"]:
    try:
        key_test = wg.OpenKey(
            wg.HKEY_LOCAL_MACHINE,
            r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", 0,
            wg.KEY_ALL_ACCESS)
        path_str = wg.QueryValueEx(key_test, 'path')
        path_str_new = path_str[
            0] + ';' + root + "/MvImport/Win64_x64/;" + root + "/MvImport/Win32_i86/;"
        wg.SetValueEx(key_test, 'path', '', path_str[1], path_str_new)
        wg.FlushKey(key_test)
        wg.CloseKey(key_test)
    except:
        import win32api, win32con
        import pyperclip
        path1 = root + "/MvImport/Win64_x64/;"
        path2 = root + "/MvImport/Win32_i86/;"
        pyperclip.copy(path1 + path2)
        message = "权限不够!写入环境变量失败,请手动添加以下两个环境变量,写入后请重启电脑生效(已复制到剪切板!!!):\n" + path1 + "\n" + path2
        win32api.MessageBox(0, message, "警告", win32con.MB_OK)

from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
from PyQt5.QtCore import *
from UI.startwindow import Ui_MainWindowStart
from PyQt5 import QtGui
from PyQt5.QtCore import *