def _run_command(self, cmd, args, internal, cwd=None): if cwd and not os.path.isdir(cwd): self.warn(cwd, " does not exist.") return if internal: command = "{} {}".format(cmd, args) startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW self.info("running", command, "in", cwd) proc = subprocess.Popen(command, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, startupinfo=startupinfo) output, _ = proc.communicate() if output: self.info(output) self.info(command, "returned", proc.returncode) else: self.dbg("running", cmd, args) self.dbg(cwd) if cwd: kpu.shell_execute(cmd, args, working_dir=cwd) else: kpu.shell_execute(cmd, args)
def openprofile(self, guid, elevate=False): if elevate: kpu.shell_execute("cmd.exe", args=[ '/c', 'start', '', '/b', self._wt_executable, '--profile', guid ], verb="runas") else: kpu.shell_execute(self._wt_executable, args=['--profile', guid])
def do_call_action(self, contact, selection, protocol): url = protocol.replace("%s", selection.replace(" ", "")) kpu.shell_execute(url, args='', working_dir='', verb='', try_runas=True, detect_nongui=True, api_flags=None, terminal_cmd=None, show=-1)
def on_execute(self, item, action): if item.data_bag(): # open with a custom command parts = re.findall(r'(?=\s|\A)\s*([^" ]+|"[^"]*")(?=\s|\Z)', item.data_bag(), re.U) if len(parts) > 0: command, *params = parts kpu.shell_execute(command, params) else: self.info("Cannot open item with: '%s', parsed as %s" % (item.data_bag(), parts)) else: kpu.execute_default_action(self, item, action)
def on_execute(self, item, action): if item.category() == kp.ItemCategory.FILE: kpu.execute_default_action(self, item, action) return if item.category() != kp.ItemCategory.REFERENCE: return # extract info from item's target property try: item_target = kpu.kwargs_decode(item.target()) distro_name = item_target['dist'] if 'session' in item_target: session_name = item_target['session'] else: session_name = None if 'host_name' in item_target: host_name = item_target['host_name'] else: host_name = None except Exception as e: self.dbg(e) return # check if the desired distro is available and enabled if distro_name not in self._distros: self.warn( 'Could not execute item "{}". Distro "{}" not found.'.format( item.label(), distro_name)) return distro = self._distros[distro_name] if not distro['enabled']: self.warn( 'Could not execute item "{}". Distro "{}" is disabled.'.format( item.label(), distro_name)) return if host_name: kpu.shell_execute(distro['exe_file'], args=host_name) return # check if the desired session still exists if session_name not in distro['sessions']: self.warn( 'Could not execute item "{}". Session "{}" not found in distro "{}".' .format(item.label(), session_name, distro_name)) return # find the placeholder of the session name in the args list and execute sidx = distro['cmd_args'].index('%1') kpu.shell_execute(distro['exe_file'], args=distro['cmd_args'][0:sidx] + [session_name] + distro['cmd_args'][sidx + 1:])
def openshelltool(self, path): tool = self._load_config().get("ShellTool") if not tool: command = get_bash_for_git_instance(self.gitinstance()) or "cmd.exe" kpu.shell_execute(command, working_dir = path) else: params = get_tool(tool.get("Type"), tool.get("ApplicationPath"), \ tool.get("Arguments")) kpu.shell_execute( params['command'], args = params['args'], working_dir = path )
def on_execute(self, item, action): try: cpitem = self.panel_items[item.target()] except KeyError: self.warn("Control Panel item not found with ID:", item.target()) return if cpitem['canonical_name'] is not None: control_exe = os.path.expandvars( "%SYSTEMROOT%\\System32\\control.exe") kpu.shell_execute(control_exe, args=["/name", cpitem['canonical_name']]) elif cpitem['open_command'] is not None: cmd_exe = os.path.expandvars("%SYSTEMROOT%\\System32\\cmd.exe") kpu.shell_execute(cmd_exe, args="/C " + cpitem['open_command'])
def on_execute(self, item, action): if item.category() == kp.ItemCategory.FILE: kpu.execute_default_action(self, item, action) return if item.category() != kp.ItemCategory.REFERENCE: return # extract info from item's target property try: item_target = kpu.kwargs_decode(item.target()) distro_name = item_target['dist'] if 'session' in item_target: session_name = item_target['session'] else: session_name = None if 'host_name' in item_target: host_name = item_target['host_name'] else: host_name = None except Exception as e: self.dbg(e) return # check if the desired distro is available and enabled if distro_name not in self._distros: self.warn('Could not execute item "{}". Distro "{}" not found.'.format(item.label(), distro_name)) return distro = self._distros[distro_name] if not distro['enabled']: self.warn('Could not execute item "{}". Distro "{}" is disabled.'.format(item.label(), distro_name)) return if host_name: kpu.shell_execute(distro['exe_file'], args=host_name) return # check if the desired session still exists if session_name not in distro['sessions']: self.warn('Could not execute item "{}". Session "{}" not found in distro "{}".'.format(item.label(), session_name, distro_name)) return # find the placeholder of the session name in the args list and execute sidx = distro['cmd_args'].index('%1') kpu.shell_execute( distro['exe_file'], args=distro['cmd_args'][0:sidx] + [session_name.replace(' ', '%20')] + distro['cmd_args'][sidx+1:])
def _kill_process_normal(self, target_item, action_name): """Kills the selected process(es) using the windows api """ target_name, target_pid = target_item.target().split("|") if action_name.startswith(self.ACTION_KILL_BY_NAME): # loop over all processes and kill all by the same name for process_item in self._processes: pname, pid = process_item.target().split("|") pid = int(pid) if pname == target_name: self.dbg("Killing process with id: {} and name: {}".format(pid, pname)) if not self._kill_by_pid(pid): self.warn("Killing process with id", pid, "failed") elif action_name.startswith(self.ACTION_KILL_BY_ID): # kill process with that pid self.dbg("Killing process with id: {} and name: {}".format(target_pid, target_name)) pid = int(target_pid) self._kill_by_pid(pid) if not self._kill_by_pid(pid): self.warn("Killing process with id", pid, "failed") elif self.ACTION_KILL_RESTART_BY_ID: # kill process with that pid and try to restart it self.dbg("Killing process with id: {} and name: {}".format(target_pid, target_name)) pid = int(target_pid) if not self._kill_by_pid(pid, wait_for_exit=True): self.warn("Killing process with id", pid, "failed. Not restarting") return databag = eval(target_item.data_bag()) self.dbg("databag for process: ", databag) if "CommandLine" not in databag: self.warn("No commandline, cannot restart") return cmd = ct.wintypes.LPCWSTR(databag["CommandLine"]) argc = ct.c_int(0) argv = CommandLineToArgvW(cmd, ct.byref(argc)) if argc.value <= 0: self.dbg("No args parsed") return args = [argv[i] for i in range(0, argc.value)] self.dbg("CommandLine args from CommandLineToArgvW:", args) if args[0] == "" or args[0].isspace(): args[0] = databag["ExecutablePath"] self.dbg("Restarting:", args) kpu.shell_execute(args[0], args[1:])
def on_execute(self, item, action): """Starts the windows app """ self.dbg("Executing:", item.target(), action.name() if action else None) if action and action.name() == self.ACTION_OPEN_STORE_PAGE: pfn = item.data_bag() self.dbg("PackageFamilyName", pfn, self.STORE_PREFIX.format(pfn)) kpu.shell_execute(self.STORE_PREFIX.format(pfn)) return if not action or action.name() == self.ACTION_RUN_NORMAL: verb = None elif action.name() == self.ACTION_RUN_ELEVATED: verb = "runas" kpu.shell_execute(item.target(), verb=verb)
def on_execute(self, item, action): if item.category() != kp.ItemCategory.URL: return url_scheme, corrected_url = self._extract_url_scheme(item.target()) if not url_scheme: self.warn("Could not guess URL scheme from URL:", item.target()) return scheme_registered = self._is_registered_url_scheme(url_scheme) if not scheme_registered: self.warn('URL cannot be launched because its scheme "{}" is not registered'.format(url_scheme)) return if url_scheme in self.WEB_SCHEMES: kpu.execute_default_action(self, item, action) else: kpu.shell_execute(item.target())
def _kill_process_admin(self, target_item, action_name): """Kills the selected process(es) using a call to windows' taskkill.exe with elevated rights """ target_name, target_pid = target_item.target().split("|") args = ["taskkill", "/F"] # add parameters according to action if action_name.startswith(self.ACTION_KILL_BY_NAME): args.append("/IM") # process name args.append(target_name) elif action_name.startswith(self.ACTION_KILL_BY_ID): args.append("/PID") # process id args.append(target_pid) self.dbg("Calling:", args) kpu.shell_execute(args[0], args[1:], verb="runas", show=subprocess.SW_HIDE)
def on_execute(self, item, action): # execute conemu and ssh command # c:\Program Files\ConEmu>ConEmu64.exe -run {Bash::bash} -c 'ssh some-server-name-defined-in-ssh-config' data_bag = item.data_bag().split('|') server_name = data_bag[0] conemu_task = data_bag[1] # ssh in the conemu if ((action and action.name() == 'ssh') or not action): cmd = self.config_command_line args = self.config_args.format(conemu_task, server_name) if (self.config_debug): self.log(cmd) self.log(args) kpu.shell_execute(cmd, args) return
def on_execute(self, item, action): # item's category is assumed to be self.ITEMCAT_CUSTOMCMD cmd_name = item.target() if cmd_name not in self.custom_cmds: self.warn('Could not execute item "{}". Custom command "{}" not found.'.format(item.label(), cmd_name)) return custcmd = self.custom_cmds[cmd_name] cmd_lines = self._customcmd_apply_args(custcmd['cmds'][:], item.raw_args()) for cmdline in cmd_lines: try: args = kpu.cmdline_split(cmdline) kpu.shell_execute( args[0], args=args[1:], verb="runas" if custcmd['elevated'] else "", detect_nongui=custcmd['auto_terminal']) except: traceback.print_exc()
def _do_update(self, download_url): self.dbg("Doing update") src_7z = self._download(download_url) self.dbg("Extracting update scripts to keypirinha cache") cmd_file = os.path.join(self.get_package_cache_path(), "update.cmd") with open(cmd_file, "wb") as cmd: cmd.write( self.load_binary_resource("update.cmd".format( self.package_full_name()))) ps1_file = os.path.join(self.get_package_cache_path(), "updater.ps1") with open(ps1_file, "wb") as ps1: ps1.write( self.load_binary_resource("updater.ps1".format( self.package_full_name()))) dest_dir = self._get_install_dir() args = [ "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps1_file, '"{}"'.format(src_7z), '"{}"'.format(dest_dir) ] if not self._can_read_write(dest_dir): args.append("-admin") self.dbg("Calling update script:", args) kpu.shell_execute("powershell", args, show=0)
def on_execute(self, item, action): """Starts the windows app """ self.dbg("Executing:", item.target()) kpu.shell_execute("explorer.exe", item.target())
def on_execute(self, item, action): kpu.shell_execute(item.short_desc())
def on_execute(self, item, action): kpu.shell_execute( "{}\{}".format(self.sharex_path, self.SHAREX_EXE), args=item.target() if not item.target() == "ShareX" else "")
def on_execute(self, item, action): """Executes the command """ self.dbg("on_execute() item: {}, action: {}".format(item, action)) self.dbg("args:", item.raw_args()) if self.__command_executing: self.warn("Another command is already executing, doing nothing") return try: self.__command_executing = True if action is not None and action.name() == "visit_homepage": package = self._get_package(item.data_bag()) if package.homepage: self.dbg(urllib.parse.urlparse(package.homepage).scheme) if urllib.parse.urlparse( package.homepage).scheme in ("http", "https"): kpu.shell_execute(package.homepage) else: self.warn("Package homepage is not a web link:", package.homepage) else: self.warn("Package homepage not set") return if item.target() == self.COMMAND_INSTALL: self._install_package(self._get_package(item.data_bag())) elif item.target() == self.COMMAND_REMOVE: self._remove_package(self._get_package(item.data_bag())) elif item.target() == self.COMMAND_UPDATE: self._update_package(self._get_package(item.data_bag())) elif item.target() == self.COMMAND_REINSTALL: package = self._get_package(item.data_bag()) self._remove_package(package, save_settings=False) self._install_package(package) elif item.target() == self.COMMAND_REINSTALL_UNTRACKED: self._install_package(self._get_package(item.data_bag()), force=True) elif item.target() == self.COMMAND_UPDATE_REPO: self._get_available_packages(True) self._check_installed() elif item.target() == self.COMMAND_UPDATE_ALL: self._get_available_packages(True) for package_name in self._installed_packages: package = self._get_package(package_name) self._update_package(package) self.info("Updating all packages finished") elif item.target() == self.COMMAND_REINSTALL_ALL_UNTRACKED: for untracked in self._untracked_packages: package = self._get_package_from_filename(untracked) if package: self._install_package(package, force=True, save_settings=False) else: self.info("Package not found in repository:", untracked) self._save_settings() self.info("Reinstalling all untracked packages finished") except Exception: self.err("Error occurred while executing command '{}'\n{}".format( item, traceback.format_exc())) finally: self.__command_executing = False
def on_execute(self, item, action): file = item.data_bag() #os.startfile(urllib.parse.unquote(file)[8:]) kpu.shell_execute(file)
def on_execute(self, item, action): if item.category() == kp.ItemCategory.REFERENCE: kpu.shell_execute(os.path.join(self._conemu_path, self._exe_name), args="-run " + item.label().replace(self._task_prefix, ""))
def on_execute(self, item, action): if item.category() not in (self.ITEMCAT_REGKEY, self.ITEMCAT_REGVALUE): return keypath_full = self._parse_key(item.target()) if not keypath_full: self.warn('Invalid registry key "{}"'.format(item.target())) return # copy full path if action is not None and action.name() == "copy_fullpath": kpu.set_clipboard(keypath_full.path) # copy parent's path elif action is not None and action.name() == "copy_parentpath": if (item.category() == self.ITEMCAT_REGVALUE and item.target()[-1] in ("\\", "/")): # "default" value? keypath_parent = keypath_full else: keypath_parent = self._parent_key(keypath_full)[0] if keypath_parent: kpu.set_clipboard(keypath_parent.path) else: kpu.set_clipboard("") # copy value (or "default" value) elif action is not None and action.name() == "copy_value": if item.category() == self.ITEMCAT_REGVALUE: if item.target()[-1] in ("\\", "/"): # "default" value? keypath_parent, value_name = (keypath_full, "") else: keypath_parent, value_name = self._parent_key(keypath_full) else: keypath_parent, value_name = (keypath_full, "") try: with winreg.OpenKey(keypath_parent.root_hkey, keypath_parent.subkey, access=winreg.KEY_READ) as hkey: value = winreg.QueryValueEx(hkey, value_name)[0] value = "" if value is None else str(value) kpu.set_clipboard(value) except OSError as exc: self.warn('Failed to open registry key "{}". Error: {}'.format( keypath_parent.path, exc)) kpu.set_clipboard("") # open key/value in regedit else: if item.category() == self.ITEMCAT_REGKEY: key_to_open = keypath_full elif item.category() == self.ITEMCAT_REGVALUE: key_to_open, value_name = self._parent_key(keypath_full) else: self.warn("Unknown item category: {}", item.category()) return if not self._readable_key(key_to_open): self.warn('Registry key not found or not readable "{}"'.format( keypath_full.path)) return try: with winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit", access=winreg.KEY_WRITE) as hkey: winreg.SetValueEx(hkey, "LastKey", 0, winreg.REG_SZ, key_to_open.path) except OSError as exc: self.warn("Failed to initialize regedit. Error:", str(exc)) return try: kpu.shell_execute("regedit.exe", args=("/m", ), try_runas=True, detect_nongui=False) except Exception as exc: self.warn("Failed to launch regedit. Error:", str(exc))
def opennewtab(self, guid): kpu.shell_execute(self._wt_executable, args=['--window', '0', '--profile', guid])
def openrepository(self, path): kpu.shell_execute(self._fork_exe, args=path)
async def _kill_process_normal(self, target_item, action_name): """Kills the selected process(es) using the windows api """ target_name, target_pid = target_item.target().split("|") if action_name.startswith(self.ACTION_KILL_BY_NAME): # loop over all processes and kill all by the same name kill_tasks = {} for process_item in self._processes: pname, pid = process_item.target().split("|") pid = int(pid) if pname == target_name: self.dbg("Killing process with id: {} and name: {}".format(pid, pname)) kill_tasks[pid] = asyncio.get_event_loop().run_in_executor(None, self._kill_by_pid, pid) await asyncio.gather(*kill_tasks.values(), return_exceptions=True) self.dbg("Kill tasks finished") for pid, kill_task in kill_tasks.items(): exc = kill_task.exception() if exc: self.err(exc) self.dbg(traceback.format_exception(exc.__class__, exc, exc.__traceback__)) continue result = kill_task.result() if result: process = next((p for p in self._processes if int(p.target().split("|")[1]) == pid), None) if process: self.dbg("removing from list:", process) self._processes.remove(process) else: self.warn("Killing process with pid", pid, "failed") elif action_name.startswith(self.ACTION_KILL_BY_ID): # kill process with that pid self.dbg("Killing process with id: {} and name: {}".format(target_pid, target_name)) pid = int(target_pid) killed = await asyncio.get_event_loop().run_in_executor(None, self._kill_by_pid, pid) if killed: process = next((p for p in self._processes if int(p.target().split("|")[1]) == pid), None) if process: self.dbg("removing from list:", process) self._processes.remove(process) else: self.warn("Killing process with id", pid, "failed") elif self.ACTION_KILL_RESTART_BY_ID: # kill process with that pid and try to restart it self.dbg("Killing process with id: {} and name: {}".format(target_pid, target_name)) pid = int(target_pid) killed = await asyncio.get_event_loop().run_in_executor(None, lambda: self._kill_by_pid(pid, wait_for_exit=True)) if not killed: self.warn("Killing process with id", pid, "failed. Not restarting") return databag = eval(target_item.data_bag()) self.dbg("databag for process: ", databag) if "CommandLine" not in databag: self.warn("No commandline, cannot restart") return cmd = ct.wintypes.LPCWSTR(databag["CommandLine"]) argc = ct.c_int(0) argv = CommandLineToArgvW(cmd, ct.byref(argc)) if argc.value <= 0: self.dbg("No args parsed") return args = [argv[i] for i in range(0, argc.value)] self.dbg("CommandLine args from CommandLineToArgvW:", args) if args[0] == "" or args[0].isspace(): args[0] = databag["ExecutablePath"] self.dbg("Restarting:", args) kpu.shell_execute(args[0], args[1:])
def on_execute(self, item, action): if item.category() == self.category: kpu.shell_execute("explorer.exe", args="/e," + folder_dict[item.label()])
def on_execute(self, item, action): appname = item.target() target = GAME_LAUNCH_URL.format(appname) kpu.shell_execute(target)