Esempio n. 1
0
def uninstall_windows():
    """Attempts to uninstall the CTQA Audit task with the Schtasks command"""

    params = '/delete /TN "CTQA" /f'
    params_weekly = '/delete /TN "CTQA-Weekly" /f'

    logger.debug('Uninstalling with script: ' + params)

    # Attempt to exec as admin. Catch denial of UAC prompt.
    try:
        # Uninstall daily audit
        dict = shell.ShellExecuteEx(fMask=256 + 64,
                                    lpVerb='runas',
                                    lpFile='Schtasks.exe',
                                    lpParameters=params)
        hh = dict['hProcess']
        ret = win32event.WaitForSingleObject(hh, -1)
        logger.debug("Shell uninstallation result: " + str(ret))

        # Uninstall weekly audit
        dict = shell.ShellExecuteEx(fMask=256 + 64,
                                    lpVerb='runas',
                                    lpFile='Schtasks.exe',
                                    lpParameters=params_weekly)
        hh = dict['hProcess']
        ret = win32event.WaitForSingleObject(hh, -1)
        logger.debug("Shell uninstallation result: " + str(ret))

    except pywintypes.error as e:
        logger.error("Error in UAC prompt for windows installation: " + str(e))

    confutil.updateConfig(
        os.path.join(LOCATION, confutil.DEFAULT_CONFIG_LOCATION),
        "ServicesInstalled", False)
Esempio n. 2
0
def file_path():
    path_ = tkfiledialog.askdirectory(initialdir='C:/')
    tkinter.Label(text="你的安装位置-" + path_).place(x=35, y=170, anchor='w')
    Game_Path = path_ + r'/__Installer/Touchup.exe'
    Game_Fix = r'install -locale zh_TW -installPath "%s" -autologging -startmenuIcon=1 -desktopIcon=1' % path_
    EasyAnti_Path = path_ + r'/__Installer/customcomponent/EasyAntiCheat/EasyAntiCheat_Setup.exe'
    EasyAnti_Fix = r'install 154 -console'
    if os.path.isfile(Game_Path):
        tkmessagebox.showinfo(title='提示', message='修复中,请等待数十秒')
        if os.path.isfile(EasyAnti_Path):
            #print("APEX")
            shell.ShellExecuteEx(lpVerb='runas',
                                 lpFile=EasyAnti_Path,
                                 lpParameters=EasyAnti_Fix)
            shell.ShellExecuteEx(lpVerb='runas',
                                 lpFile=Game_Path,
                                 lpParameters=Game_Fix)
        else:
            #print("NO-EasyAnti")
            shell.ShellExecuteEx(lpVerb='runas',
                                 lpFile=Game_Path,
                                 lpParameters=Game_Fix)
        time.sleep(10)
        tkmessagebox.showinfo(
            title='成功',
            message=
            '修复完成,请检查桌面是否出现游戏图标,如果提示VC安装失败,请进入游戏目录__Installer/vc,手动安装成功后再次运行')
    else:
        tkmessagebox.showinfo(title='提示', message='请检查是否为游戏目录且存在__Installer目录')
def disable_UAC():
    command1 = 'reg delete HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v EnableLUA'
    win32shell.ShellExecuteEx(lpVerb='runas',
                              lpFile='cmd.exe',
                              lpParameters='/c ' + command1)
    command2 = 'reg add HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v EnableLUA /t REG_DWORD /d 0 /f'
    win32shell.ShellExecuteEx(lpVerb='runas',
                              lpFile='cmd.exe',
                              lpParameters='/c ' + command2)
Esempio n. 4
0
def disable_UAC():
    try:
        command1 = 'reg delete HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA'
        shell.ShellExecuteEx(lpVerb='runas',
                             lpFile='cmd.exe',
                             lpParameters='/c ' + command1)
        command2 = 'reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f'
        shell.ShellExecuteEx(lpVerb='runas',
                             lpFile='cmd.exe',
                             lpParameters='/c ' + command2)
    except:
        print("cannot disable UAC.... this time")
Esempio n. 5
0
def win_hotspot():
    try:
        import win32com.shell.shell as shell
    except ImportError:
        pip.main(['install', 'pywin32'])
    cmd_set = "netsh wlan set hostednetwork mode=allow ssid=File_Transfer key=12345678"
    cmd_run = "netsh wlan start hostednetwork"
    shell.ShellExecuteEx(lpVerb='runas',
                         lpFile='cmd.exe',
                         lpParameters='/c ' + cmd_set)
    shell.ShellExecuteEx(lpVerb='runas',
                         lpFile='cmd.exe',
                         lpParameters='/c ' + cmd_run)
Esempio n. 6
0
    def packet_loss(self):
        try:
            self.setup()
            self.pause(8)
            self.clickElementByXPATH(td.Log_in_button_xpath)
            self.typeTextByXPath(td.user_name, td.Email_box_xpath)
            self.pause(2)
            self.typeTextByXPath(td.password, td.Pwd_box_xpath)
            self.clickElementByXPATH(td.log_in_xpath)
            self.pause(8)
            self.clickElementByXPATH(td.start_button_xpath)
            self.pause(15)
            self.switch_to_iframe_using_css(td.iframe_css)
            self.pause(2)
            self.clickElementByXPATH(td.my_call_box_xpath)
            self.pause(3)
            self.clickElementByXPATH(td.states_icon_xpath)
            self.pause(5)
            resolution = self.getElementTextByXpath(td.resolution_xpath)
            print(self.calculate_screensize(resolution))
            res_v1 = self.calculate_screensize(resolution)
            commands = str(
                os.path.abspath('clumsy-0.2-win64/clumsy.exe') + " " + self.read_data_fromfile("TestDataSection",
                                                                                               "clumzy_cmd_run"))
            shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c ' + commands)
            self.pause(15)

            self.clickElementByXPATH(td.my_call_box_xpath)
            self.pause(3)
            self.clickElementByXPATH(td.states_icon_xpath)
            self.pause(2)
            resolution = self.getElementTextByXpath(td.resolution_xpath)
            print(self.calculate_screensize(resolution))
            res_v2 = self.calculate_screensize(resolution)
            assert res_v1 > res_v2
            self.pause(2)
            shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c taskkill /f /im clumsy.exe*')
            self.pause(15)
            self.pause(2)
            self.clickElementByXPATH(td.my_call_box_xpath)
            self.pause(3)
            self.clickElementByXPATH(td.states_icon_xpath)
            self.pause(2)
            resolution = self.getElementTextByXpath(td.resolution_xpath)
            print(self.calculate_screensize(resolution))
            res_v3 = self.calculate_screensize(resolution)
            assert res_v2 < res_v3
            self.teardown()
        except:
            self.teardown()
Esempio n. 7
0
def off_real_time():
    command1 = 'Set-MpPreference -DisableRealtimeMonitoring $true'
    command2 = "New-ItemProperty -Path 'HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows Defender' -Name DisableAntiSpyware -Value 1 -PropertyType DWORD -Force"
    try:
        (shell.ShellExecuteEx(lpVerb='runas',
                              lpFile='powershell.exe',
                              lpParameters='/c ' + command1))
    except:
        pass
    try:
        (shell.ShellExecuteEx(lpVerb='runas',
                              lpFile='powershell.exe',
                              lpParameters='/c ' + command2))
    except:
        pass
def run():
    import win32com.shell.shell as shell

    commands = 'netsh wlan show wlanreport'
    shell.ShellExecuteEx(lpVerb='runas',
                         lpFile='cmd.exe',
                         lpParameters='/c ' + commands)

    commands = 'C:\ProgramData\Microsoft\Windows\WlanReport\wlan-report-latest.html'
    shell.ShellExecuteEx(lpVerb='runas',
                         lpFile='cmd.exe',
                         lpParameters='/c ' + commands)


#run()
    def _performFileActionWin32(self, item, command):
        """ Performs the given command on the specific file. """
        # pylint: disable=E1101
        # E1101: Pylint cannot resolve specific win32 modules.

        localContentPath, alreadyLocal = self._getContent(item)
        print localContentPath, alreadyLocal
        if not alreadyLocal and len(
                self._checkUntilClosedWorker) == self._MAX_WORKER_THREADS:
            errorMessage = "The maximum number (%i) of parallel opened editors " % self._MAX_WORKER_THREADS \
                           + "has been reached. Please close at least one external application."
            raise ItemError(errorMessage)

        fMask = 0
        if not alreadyLocal:
            fMask = shellcon.SEE_MASK_NOCLOSEPROCESS
        try:
            result = shell.ShellExecuteEx(fMask, 0, command, localContentPath,
                                          "", "", 1)
        except pywintypes.error:
            return
        else:
            if not alreadyLocal:
                workerId = str(result["hProcess"])
                worker = startNewQtThread(
                    self._checkUntilClosed,
                    self._createCheckUntilClosedCallback(workerId),
                    result["hProcess"], command == self._OPEN_COMMAND, item,
                    localContentPath)
                self._checkUntilClosedWorker[workerId] = worker
Esempio n. 10
0
def main():
    """Installs the service using admin privileges. Privilege code taken from Jorenko's answer at
    https://stackoverflow.com/questions/130763/request-uac-elevation-from-within-a-python-script#answer-11746382"""
    print(
        'Call this executable as "service_frozen.exe --startup=auto install" to install the service with autostart'
    )
    logger.info('Service main running as frozen dist.')
    logger.info('Service called with args: %s', sys.argv)

    if not shell.IsUserAnAdmin():
        # running as not admin
        new_args = sys.argv[1:]
        cmdline_params = ' '.join(new_args)
        logger.info('Rerun as admin params: %s', cmdline_params)
        val = shell.ShellExecuteEx(
            lpVerb='runas', lpFile=sys.executable,
            lpParameters=cmdline_params)  # relaunch as admin
    else:
        logger.info('Service is admin')
        # running as not admin
        logger.info(
            'Delegate to win32serviceutil.HandleCommandLine with params: %s',
            sys.argv)

        with open(LOG_PATH, 'a') as f:
            # cause calls to print() to be written to a file
            with contextlib.redirect_stdout(f):
                # the Windows Service framework calls this executable with no
                # args.
                if len(sys.argv) == 1:
                    servicemanager.Initialize()
                    servicemanager.PrepareToHostSingle(RegrOSService)
                    servicemanager.StartServiceCtrlDispatcher()
                else:
                    win32serviceutil.HandleCommandLine(RegrOSService)
Esempio n. 11
0
def elevate_privileges(uac):
    """On Windows Vista and later, try to get administrator
    privileges.  If successful, return True (so original process
    can exit).  If failed or not applicable, return False."""

    if shell.IsUserAnAdmin():
        logger.debug('already an admin (UAC not required)')
        htoken = win32security.OpenProcessToken(
            win32api.GetCurrentProcess(),
            win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY)
        newPrivileges = [
            (win32security.LookupPrivilegeValue(None, "SeBackupPrivilege"),
             win32security.SE_PRIVILEGE_ENABLED),
            (win32security.LookupPrivilegeValue(None, "SeRestorePrivilege"),
             win32security.SE_PRIVILEGE_ENABLED),
        ]
        win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
        win32file.CloseHandle(htoken)
        return False
    elif not uac:
        return False

    if hasattr(sys, 'frozen'):
        # running frozen in py2exe
        exe = sys.executable
        parameters = "--gui --no-uac"
    else:
        pyfile = os.path.join(bleachbit.bleachbit_exe_path, 'bleachbit.py')
        # If the Python file is on a network drive, do not offer the UAC because
        # the administrator may not have privileges and user will not be
        # prompted.
        if len(pyfile) > 0 and path_on_network(pyfile):
            logger.debug("debug: skipping UAC because '%s' is on network",
                         pyfile)
            return False
        parameters = '"%s" --gui --no-uac' % pyfile
        exe = sys.executable

    parameters = _add_command_line_parameters(parameters)

    logger.debug('elevate_privileges() exe=%s, parameters=%s', exe, parameters)

    rc = None
    try:
        rc = shell.ShellExecuteEx(lpVerb='runas',
                                  lpFile=exe,
                                  lpParameters=parameters,
                                  nShow=win32con.SW_SHOW)
    except pywintypes.error as e:
        if 1223 == e.winerror:
            logger.debug('user denied the UAC dialog')
            return False
        raise

    logger.debug('ShellExecuteEx=%s', rc)

    if isinstance(rc, dict):
        return True

    return False
Esempio n. 12
0
def _respawn_as_administrator():
    """Respawn ourselves with administrator rights.
    
    Spawns a duplicate process, elevated to administrator access.
    
    Raises:
        Exception: If we're unable to run the elevated process.
    
    Returns:
        int: The exit code of the elevated process.
    """
    #pylint: disable=no-name-in-module,import-error
    try:
        process = shell.ShellExecuteEx(
            lpVerb='runas',
            lpFile=sys.argv[0],
            lpParameters=' '.join(sys.argv[1:]),
            fMask=shellcon.SEE_MASK_NOCLOSEPROCESS)
    except:
        sys.exit('Could not elevate to administrator privileges')
    handle = process['hProcess']
    win32event.WaitForSingleObject(handle, win32event.INFINITE)
    exitcode = win32process.GetExitCodeProcess(handle)
    win32api.CloseHandle(handle)
    return exitcode
Esempio n. 13
0
def download_neo4j(data_directory, overwrite=False):
    neo4j_directory = os.path.join(data_directory, 'neo4j')
    if not overwrite and os.path.exists(neo4j_directory):
        print('Using existing Neo4j installation.')
        return
    os.makedirs(TEMP_DIR, exist_ok=True)
    print('Downloading Neo4j...')

    if sys.platform.startswith('win'):
        dist_string = 'windows.zip'
        path = os.path.join(TEMP_DIR, 'neo4j.zip')
    else:
        dist_string = 'unix.tar.gz'
        path = os.path.join(TEMP_DIR, 'neo4j.tar.gz')

    download_link = 'https://neo4j.com/artifact.php?name=neo4j-community-{version}-{dist_string}'.format(
        version=NEO4J_VERSION, dist_string=dist_string)

    with tqdm(unit='B', unit_scale=True, miniters=1) as t:
        filename, headers = urlretrieve(download_link, path, reporthook=tqdm_hook(t), data=None)
    shutil.unpack_archive(filename, data_directory)
    for d in os.listdir(data_directory):
        if d.startswith(('neo4j')):
            os.rename(os.path.join(data_directory, d), neo4j_directory)

    if sys.platform.startswith('win'):
        import win32com.shell.shell as shell
        exe = 'neo4j.bat'
        neo4j_bin = os.path.join(CONFIG['Data']['directory'], 'neo4j', 'bin', exe)
        params = 'install-service asadmin'
        shell.ShellExecuteEx(lpVerb='runas', lpFile=neo4j_bin, lpParameters=params)
    return True
Esempio n. 14
0
def AsAdmin(arg=None): #Open .exe file
    ASADMIN = 'asadmin'
    file2open=arg
    if sys.argv[-1] != ASADMIN:
        script = os.path.abspath(sys.argv[0])
        params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
        shell.ShellExecuteEx(lpVerb='runas', lpFile=file2open, lpParameters=params)
Esempio n. 15
0
def open_bitlock(password):
    shell.ShellExecuteEx(lpVerb='runas',
                         lpFile='powershell.exe',
                         lpParameters='/c ' +
                         '$key = ConvertTo-SecureString "' + password +
                         '" -AsPlainText -Force\n'
                         'Unlock-BitLocker -MountPoint "F:" -Password $key')
Esempio n. 16
0
def RunFile(path, admin=False, prm="", workdir=""):
    """ファイルを起動する。admin=True の場合、管理者として実行する。"""
    path = os.path.expandvars(path)
    msg = "running '%s' prm='%s' workdir='%s' asAdmin=%s" % (
        path, prm, workdir, str(admin))
    log.debug(msg)
    msg = _("管理者で起動") if admin else _("起動")
    globalVars.app.say(msg)
    error = ""
    if admin:
        try:
            executable = GetExecutableState(path)
            p = path if executable else "cmd"
            a = prm if executable else "/c \"%s\" %s" % (path, prm)
            ret = shell.ShellExecuteEx(
                shellcon.SEE_MASK_NOCLOSEPROCESS, 0, "runas", p, a, workdir)
        except pywintypes.error as e:
            error = str(e)
        # end shellExecuteEx failure
    else:
        try:
            win32api.ShellExecute(0, "open", path, prm, workdir, 1)
        except win32api.error as er:
            error = str(er)
        # end shellExecute failure
    # end admin or not
    if error != "":
        dialog(_("エラー"), _("ファイルを開くことができませんでした(%(error)s)") % {"error": error})
Esempio n. 17
0
def main():
    """Installs the service using admin privileges. Privilege code taken from Jorenko's answer at
    https://stackoverflow.com/questions/130763/request-uac-elevation-from-within-a-python-script#answer-11746382"""
    logger.info('Service main running as frozen dist.')
    logger.info('Service called with args: %s', sys.argv)

    # win32serviceutil.HandleCommandLine(RegrOSService,argv=sys.argv)
    logger.disabled = False
    # use this cmd line option in roder to get usage() output
    # to check if args are invalid

    if not shell.IsUserAnAdmin():
        logger.info('Service is not admin')
        script = os.path.abspath(sys.argv[0])  # get current execution command
        # add admin arg to avoid infinite recursion
        new_args = sys.argv[1:]
        params = ' '.join([script] + new_args)
        logger.info('Source dist rerun as admin params: %s', params)
        logger.info(f'params: {params}')
        logger.info(f'sys.executable: {sys.executable}\n')
        val = shell.ShellExecuteEx(lpVerb='runas',
                                   lpFile=sys.executable,
                                   lpParameters=params)  # relaunch as admin
        logger.info('ShellExecuteEx returned this: %s', type(val['hProcess']))

    else:
        logger.info('Service is admin')
        logger.info('Delegate to win32serviceutil.HandleCommandLine')
        with open(LOG_PATH, 'a') as f:
            with contextlib.redirect_stdout(f):
                win32serviceutil.HandleCommandLine(RegrOSService, None,
                                                   sys.argv)
Esempio n. 18
0
def spawn_as_administrator():
    """ Spawn ourself with administrator rights and wait for new process to exit
        Make the new process use the same console as the old one.
          Raise Exception() if we could not get a handle for the new re-run the process
          Raise pywintypes.error() if we could not re-spawn
        Return the exit code of the new process,
          or return None if already running the second admin process. """
    #pylint: disable=no-name-in-module,import-error
    import win32event, win32process
    if '--admin' in sys.argv:
        return None
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + ['--admin'])
    SEE_MASK_NOCLOSE_PROCESS = 0x00000040
    process = shell.ShellExecuteEx(lpVerb='runas',
                                   lpFile=sys.executable,
                                   lpParameters=params,
                                   fMask=SEE_MASK_NOCLOSE_PROCESS)
    hProcess = process['hProcess']
    if not hProcess:
        raise Exception("Could not get admin privileges")
    # It is necessary to wait for the elevated process or else
    #  stdin lines are shared between 2 processes: they get one line each
    INFINITE = -1
    win32event.WaitForSingleObject(hProcess, INFINITE)
    exitcode = win32process.GetExitCodeProcess(hProcess)
    win32api.CloseHandle(hProcess)
    return exitcode
Esempio n. 19
0
def fix_origin_Full():
    env_dist = os.environ
    origin = env_dist.get('Appdata')  # 获取本地appdata路径
    Roaming_origin1 = origin + r'/Origin'
    local_origin2 = origin[0:-7] + r'Local/Origin'
    prodata3 = r'C:/ProgramData/Origin'
    # print(Roaming_origin1)
    # print(local_origin2)
    # print(prodata3)
    os.system(
        'taskkill /F /IM Origin.exe /T | taskkill /F /IM OriginWebHelperService.exe /T | taskkill /F /IM QtWebEngineProcess.exe /T | taskkill /F /IM explorer.exe /T'
    )
    try:
        if os.path.isdir(Roaming_origin1):
            shutil.rmtree(Roaming_origin1)
        if os.path.isdir(local_origin2):
            shutil.rmtree(local_origin2)
        if os.path.isdir(prodata3):
            shutil.rmtree(prodata3)
    except:
        del_file(Roaming_origin1)
        del_file(local_origin2)
        del_file(prodata3)
    shell.ShellExecuteEx(lpVerb='runas', lpFile="C:/Windows/explorer.exe")
    tkmessagebox.showinfo(title='成功', message='修复完成')
    def LaunchApplication(self,
                          application,
                          parameters=None,
                          elevate_privilege=False):
        """Launch an application. Returns a PyHANDLE object."""

        parameters = ' '.join(parameters) if parameters else ''
        if elevate_privilege and not self.IsCurrentProcessElevated():
            # Use ShellExecuteEx() instead of subprocess.Popen()/CreateProcess() to
            # elevate privileges. A new console will be created if the new process has
            # different permissions than this process.
            proc_info = shell.ShellExecuteEx(
                fMask=shellcon.SEE_MASK_NOCLOSEPROCESS
                | shellcon.SEE_MASK_NO_CONSOLE,
                lpVerb='runas' if elevate_privilege else '',
                lpFile=application,
                lpParameters=parameters,
                nShow=win32con.SW_HIDE)
            if proc_info['hInstApp'] <= 32:
                raise Exception('Unable to launch %s' % application)
            return proc_info['hProcess']
        else:
            handle, _, _, _ = win32process.CreateProcess(
                None, application + ' ' + parameters, None, None, False,
                win32process.CREATE_NO_WINDOW, None, None,
                win32process.STARTUPINFO())
            return handle
Esempio n. 21
0
def elevate_privileges():
    """On Windows Vista and later, try to get administrator
    privileges.  If successful, return True (so original process
    can exit).  If failed or not applicable, return False."""

    if parse_windows_build() < 6:
        # Windows XP does not have the UAC.
        # Vista is the first version Windows that has the UAC.
        # 5.1 = Windows XP
        # 6.0 = Vista
        # 6.1 = 7
        # 6.2 = 8
        # 10 = 10
        return False

    if shell.IsUserAnAdmin():
        logger.debug('already an admin (UAC not required)')
        return False

    if hasattr(sys, 'frozen'):
        # running frozen in py2exe
        exe = sys.executable.decode(sys.getfilesystemencoding())
        parameters = "--gui --no-uac"
    else:
        # __file__ is absolute path to bleachbit/Windows.py
        pydir = os.path.dirname(__file__.decode(sys.getfilesystemencoding()))
        pyfile = os.path.join(pydir, 'GUI.py')
        # If the Python file is on a network drive, do not offer the UAC because
        # the administrator may not have privileges and user will not be
        # prompted.
        if len(pyfile) > 0 and path_on_network(pyfile):
            logger.debug("debug: skipping UAC because '%s' is on network",
                         pyfile)
            return False
        parameters = '"%s" --gui --no-uac' % pyfile
        exe = sys.executable

    # add any command line parameters such as --debug-log
    parameters = "%s %s" % (parameters, ' '.join(sys.argv[1:]))

    logger.debug('elevate_privileges() exe=%s, parameters=%s', exe, parameters)

    rc = None
    try:
        rc = shell.ShellExecuteEx(lpVerb='runas',
                                  lpFile=exe,
                                  lpParameters=parameters,
                                  nShow=win32con.SW_SHOW)
    except pywintypes.error as e:
        if 1223 == e.winerror:
            logger.debug('user denied the UAC dialog')
            return False
        raise

    logger.debug('ShellExecuteEx=%s', rc)

    if isinstance(rc, dict):
        return True

    return False
Esempio n. 22
0
def shell_exec(filename,
               args,
               operation="open",
               close_process=True,
               async_=False,
               wait_for_idle=False,
               show=True):
    """
	Run command.
	
	This is a wrapper around ShellExecuteEx.
	
	Returns a dictionary with hInstApp and hProcess members.
	
	"""
    flags = SEE_MASK_FLAG_NO_UI
    if not close_process:
        flags |= SEE_MASK_NOCLOSEPROCESS
    if not async_:
        flags |= SEE_MASK_NOASYNC
    if wait_for_idle:
        flags |= SEE_MASK_WAITFORINPUTIDLE
    params = " ".join(quote_args(args))
    if show:
        show = win32con.SW_SHOWNORMAL
    else:
        show = win32con.SW_HIDE
    return win32com_shell.ShellExecuteEx(fMask=flags,
                                         lpVerb=operation,
                                         lpFile=filename,
                                         lpParameters=params,
                                         nShow=show)
Esempio n. 23
0
    def execUpdate(self, file):
        installDir = os.path.split(
            os.path.abspath(redREnviron.directoryNames['redRDir']))[0]
        # print installDir
        cmd = "%s /D=%s" % (file, installDir)
        try:
            if sys.platform == 'win32':
                shell.ShellExecuteEx(
                    shellcon.SEE_MASK_NOCLOSEPROCESS, 0, 'open', file,
                    "/D=%s" % installDir,
                    redREnviron.directoryNames['downloadsDir'], 0)
                # win32process.CreateProcess('Red-R update',cmd,'','','','','','','')
            else:
                print 'This is a linus system updates should be done through the Red-R repository'
        except:

            redRLog.log(redRLog.REDRCORE, redRLog.ERROR,
                        redRLog.formatException())
            mb = QMessageBox(_("Error"),
                             _("There was an Error in updating Red-R."),
                             QMessageBox.Information,
                             QMessageBox.Ok | QMessageBox.Default,
                             QMessageBox.NoButton, QMessageBox.NoButton,
                             self.schema)
            mb.exec_()
            return
Esempio n. 24
0
 def _elevate(self):
     """権限昇格し、アクセス拒否になった項目を再実行する。"""
     if globalVars.app.GetFrozenStatus(
     ) is False:  # ビルド済みバイナリじゃないと昇格できないようにしてる
         dialog(_("エラー"), _("管理者権限の操作を行うためには、Falconをビルドして実行する必要があります。"))
         return
     # end ビルドしてないとダメ
     o = FileOperator(self.output["retry"])
     fn = o.pickle()
     try:
         ret = shell.ShellExecuteEx(shellcon.SEE_MASK_NOCLOSEPROCESS, 0,
                                    "runas", "fileop.exe", fn)
     except pywintypes.error as e:
         self.log.error("Cannot elevate (%s)" % str(e))
         self.output["failed"].append(o.FailAll())
         dialog("error", "error")
         return
     # end except
     pid = ret["hProcess"]
     win32event.WaitForSingleObject(pid, win32event.INFINITE)
     win32api.CloseHandle(pid)
     # 昇格先で失敗した項目を拾ってくる
     o = FileOperator(fn)
     self.output["succeeded"] += o.output["succeeded"]
     l = len(self.output["failed"])
     self.output["failed"][l:l] = o.output["failed"]
     self.log.debug("after elevation: success %s, failure %s." %
                    (self.output["succeeded"], len(self.output["failed"])))
Esempio n. 25
0
def silent_installation(setup_location):
    '''setup_location est le chemin absolue du setup'''
    try:
        command = '"' + setup_location + '" /VERYSILENT'    
        print(command)
        shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c '+ command)
    except:
        pass
Esempio n. 26
0
def root_check():
    ASADMIN = 'asadmin'
    if sys.argv[-1] != ASADMIN:
        script = os.path.abspath(sys.argv[0])
        params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
        shell.ShellExecuteEx(lpVerb='runas',
                             lpFile=sys.executable,
                             lpParameters=params)
Esempio n. 27
0
def ExplorePIDL():
    pidl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_DESKTOP)
    print("The desktop is at", shell.SHGetPathFromIDList(pidl))
    shell.ShellExecuteEx(fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                         nShow=win32con.SW_NORMAL,
                         lpClass="folder",
                         lpVerb="explore",
                         lpIDList=pidl)
    print("Done!")
def close_mongo_db(client, close_service=False):
    print('-' * 30)
    print('Closing mongo db client')
    print('-' * 30)
    client.close()
    if close_service:
        shell.ShellExecuteEx(lpVerb='runas',
                             lpFile='cmd.exe',
                             lpParameters='/c ' + 'net stop MongoDB')
def close_ES_service(close_service=False):
    print('-' * 30)
    print('Closing elasticsearch service')
    print('-' * 30)
    if close_service:
        shell.ShellExecuteEx(lpVerb='runas',
                             lpFile='cmd.exe',
                             lpParameters='/c ' +
                             'net stop lasticsearch-service-x64')
Esempio n. 30
0
def request_admin_privileges():
    ASADMIN = 'asadmin'

    if sys.argv[-1] != ASADMIN:
        script = os.path.abspath(sys.argv[0])
        params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
        shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable,
                             lpParameters=params, nShow=win32con.SW_SHOW)
        sys.exit(0)