Wrapper for commands to be run against Windows boxes using WinRM.
770490
def winrm_cmd(session, command, flags, **kwargs):
    '''
    
    '''
    log.debug('Executing WinRM command: %s %s', command, flags)
    # rebuild the session to ensure we haven't timed out
    session.protocol.transport.build_session()
    r = session.run_cmd(command, flags)
    return r.status_code
473751
def getWmAllowedActions(self, win, str=False):
        
        wAllowedActions = (
            self._getProperty('_NET_WM_ALLOWED_ACTIONS', win) or [])
        if not str:
            return wAllowedActions
        return [self._getAtomName(a) for a in wAllowedActions]
67745
def run_winpdb(self):
        """"""
        if self.save():
            fname = self.get_current_filename()
            runconf = get_run_configuration(fname)
            if runconf is None:
                args = []
                wdir = None
            else:
                args = runconf.get_arguments().split()
                wdir = runconf.get_working_directory()
            # Handle the case where wdir comes back as an empty string
            # when the working directory dialog checkbox is unchecked.
            # (subprocess "cwd" default is None, so empty str
            # must be changed to None in this case.)
            programs.run_program(WINPDB_PATH, [fname] + args, cwd=wdir or None)
198361
def cli(ctx, pattern, arguments, safe):
    """"""

    matches = utils.grep_commands(pattern)
    if matches:
        selected = utils.select_command(matches)
        if selected >= 0:
            cmd, desc = matches[selected]
            pcmd = utils.create_pcmd(cmd)
            raw_params, params, defaults = utils.get_params_in_pcmd(pcmd)

            arguments = list(arguments)
            kargs = {}
            for r, p, d in zip(raw_params, params, defaults):
                if arguments:
                    val = arguments.pop(0)
                    click.echo("{}: {}".format(p, val))
                    kargs[r] = val
                elif safe:
                    if d:
                        kargs[r] = d
                else:
                    p_default = d if d else None
                    val = click.prompt("Enter value for '{}'".format(p), default=p_default)
                    kargs[r] = val
            click.echo("\n")

            final_cmd = utils.substitute_pcmd(pcmd, kargs, safe)

            command = "$ {} :: {}".format(final_cmd, desc)
            if click.confirm("Execute\n\t{}\n\n?".format(command), default=True):
                os.system(final_cmd)
    elif matches == []:
        click.echo('No saved commands matches the pattern {}'.format(pattern))
    else:
        click.echo("No commands to run, Add one by 'keep new'. ")
1201717
def run_command(self, codeobj):
        """"""
        try:
            value, stdout = yield from self.attempt_exec(codeobj, self.namespace)
        except Exception:
            yield from self.send_exception()
            return
        else:
            yield from self.send_output(value, stdout)
1308452
def run_command(cmd):
    '''
    '''
    output = Popen(cmd,stderr=STDOUT,stdout=PIPE)
    t = output.communicate()[0],output.returncode
    output = {'message':t[0],
              'return_code':t[1]}

    return output
1367216
def _handle_windows(self, event):
        """"""
        vkey = self._keyname(event.GetKey())
        if event.Message in self.KEYS_UP + self.KEYS_DOWN:
            if vkey in self.MODIFIERNAMES:
                self._realmodifiers[vkey] = event.Message in self.KEYS_DOWN
                self._modifiers[self.MODIFIERNAMES[vkey]] = self._realmodifiers[vkey]
        if event.Message not in self.KEYS_DOWN:
            return True

        is_altgr = False
        if (vkey, event.IsExtended()) in self.NUMPAD_SPECIALS:
            key = vkey = "Numpad-" + vkey
        elif not event.Ascii or vkey.startswith("Numpad"):
            key = vkey
        else:
            is_altgr = event.Ascii in self.ALT_GRS
            key = self._keyname(unichr(event.Ascii))

        if DEBUG: print("Adding key %s (real %s)" % (key.encode("utf-8"), vkey.encode("utf-8")))
        self._output(type="keys", key=key, realkey=vkey)

        if vkey not in self.MODIFIERNAMES and not is_altgr:
            modifier = "-".join(k for k in ["Ctrl", "Alt", "Shift", "Win"]
                                if self._modifiers[k])
            if modifier and modifier != "Shift": # Shift-X is not a combo
                if self._modifiers["Ctrl"] and event.Ascii:
                    key = self._keyname(unichr(event.KeyID))
                realmodifier = "-".join(k for k, v in self._realmodifiers.items() if v)
                realkey = "%s-%s" % (realmodifier, key)
                key = "%s-%s" % (modifier, key)
                if DEBUG: print("Adding combo %s (real %s)" % (key.encode("utf-8"), realkey.encode("utf-8")))
                self._output(type="combos", key=key, realkey=realkey)

        if DEBUG:
            print("CHARACTER: %r" % key)
            print('GetKey: {0}'.format(event.GetKey()))  # Name of the virtual keycode, str
            print('IsAlt: {0}'.format(event.IsAlt()))  # Was the alt key depressed?, bool
            print('IsExtended: {0}'.format(event.IsExtended()))  # Is this an extended key?, bool
            print('IsInjected: {0}'.format(event.IsInjected()))  # Was this event generated programmatically?, bool
            print('IsTransition: {0}'.format(event.IsTransition()))  #Is this a transition from up to down or vice versa?, bool
            print('ASCII: {0}'.format(event.Ascii))  # ASCII value, if one exists, str
            print('KeyID: {0}'.format(event.KeyID))  # Virtual key code, int
            print('ScanCode: {0}'.format(event.ScanCode))  # Scan code, int
            print('Message: {0}'.format(event.Message))  # Name of the virtual keycode, str
            print()
        return True
422368
def win_find_exe(filename, installsubdir=None, env="ProgramFiles"):
    """"""
    for fn in [filename, filename+".exe"]:
        try:
            if installsubdir is None:
                path = _where(fn)
            else:
                path = _where(fn, dirs=[os.path.join(os.environ[env], installsubdir)])
        except IOError:
            path = filename
        else:
            break        
    return path
1122549
function resolveWindowsExe(cmd) {
    var winExtensions = ['.exe', '.cmd', '.bat', '.js', '.vbs'];
    function isValidExe(c) {
        return winExtensions.indexOf(path.extname(c).toLowerCase()) !== -1 && fs.existsSync(c);
    }
    if (isValidExe(cmd)) {
        return cmd;
    }
    try {
        cmd = which.sync(cmd);
    } catch (e) {
        // just ignore which's whining
    }
    if (!isValidExe(cmd)) {
        winExtensions.some(function(ext) {
            if (fs.existsSync(cmd + ext)) {
                cmd = cmd + ext;
                return true;
            }
        });
    }
    return cmd;
}
1216869
def main(args=None):
    """"""
    parser = argparse.ArgumentParser(
        description='Fritz!Box Smarthome CLI tool.')
    parser.add_argument('-v', action='store_true', dest='verbose',
                        help='be more verbose')
    parser.add_argument('-f', '--fritzbox', type=str, dest='host',
                        help='Fritz!Box IP address', default='fritz.box')
    parser.add_argument('-u', '--user', type=str, dest='user',
                        help='Username')
    parser.add_argument('-p', '--password', type=str, dest='password',
                        help='Username')
    parser.add_argument('-a', '--ain', type=str, dest='ain',
                        help='Actor Identification', default=None)
    parser.add_argument('-V', '--version', action='version',
                        version='{version}'.format(version=__version__),
                        help='Print version')

    _sub = parser.add_subparsers(title='Commands')

    # list all devices
    subparser = _sub.add_parser('list', help='List all available devices')
    subparser.set_defaults(func=list_all)

    # device
    subparser = _sub.add_parser('device', help='Device/Actor commands')
    _sub_switch = subparser.add_subparsers()

    # device name
    subparser = _sub_switch.add_parser('name', help='get the device name')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=device_name)

    # device presence
    subparser = _sub_switch.add_parser('present',
                                       help='get the device presence')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=device_presence)

    # device stats
    subparser = _sub_switch.add_parser('stats',
                                       help='get the device statistics')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=device_statistics)

    # switch
    subparser = _sub.add_parser('switch', help='Switch commands')
    _sub_switch = subparser.add_subparsers()

    # switch get
    subparser = _sub_switch.add_parser('get', help='get state')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_get)

    # switch on
    subparser = _sub_switch.add_parser('on', help='set on state')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_on)

    # switch off
    subparser = _sub_switch.add_parser('off', help='set off state')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_off)

    # switch toggle
    subparser = _sub_switch.add_parser('toggle', help='set off state')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_toggle)

    args = parser.parse_args(args)

    logging.basicConfig()
    if args.verbose:
        logging.getLogger('pyfritzhome').setLevel(logging.DEBUG)

    fritzbox = None
    try:
        fritzbox = Fritzhome(host=args.host, user=args.user,
                             password=args.password)
        fritzbox.login()
        args.func(fritzbox, args)
    finally:
        if fritzbox is not None:
            fritzbox.logout()
396767
def run(self):
    """"""

    module = self.distribution.ext_modules[0]
    base_dir = os.path.dirname(__file__)

    if base_dir:
      os.chdir(base_dir)

    exclusions = []

    for define in self.define or []:
      module.define_macros.append(define)

    for library in self.libraries or []:
      module.libraries.append(library)

    building_for_windows = self.plat_name in ('win32','win-amd64')
    building_for_osx = 'macosx' in self.plat_name
    building_for_linux = 'linux' in self.plat_name
    building_for_freebsd = 'freebsd' in self.plat_name
    building_for_openbsd = 'openbsd' in self.plat_name # need testing

    if building_for_linux:
      module.define_macros.append(('USE_LINUX_PROC', '1'))
    elif building_for_windows:
      module.define_macros.append(('USE_WINDOWS_PROC', '1'))
      module.define_macros.append(('_CRT_SECURE_NO_WARNINGS', '1'))
      module.libraries.append('kernel32')
      module.libraries.append('advapi32')
      module.libraries.append('user32')
      module.libraries.append('crypt32')
      module.libraries.append('ws2_32')
    elif building_for_osx:
      module.define_macros.append(('USE_MACH_PROC', '1'))
      module.include_dirs.append('/usr/local/opt/openssl/include')
      module.include_dirs.append('/opt/local/include')
      module.library_dirs.append('/opt/local/lib')
      module.include_dirs.append('/usr/local/include')
      module.library_dirs.append('/usr/local/lib')
    elif building_for_freebsd:
      module.define_macros.append(('USE_FREEBSD_PROC', '1'))
      module.include_dirs.append('/opt/local/include')
      module.library_dirs.append('/opt/local/lib')
      module.include_dirs.append('/usr/local/include')
      module.library_dirs.append('/usr/local/lib')
    elif building_for_openbsd:
      module.define_macros.append(('USE_OPENBSD_PROC', '1'))
      module.include_dirs.append('/opt/local/include')
      module.library_dirs.append('/opt/local/lib')
      module.include_dirs.append('/usr/local/include')
      module.library_dirs.append('/usr/local/lib')
    else:
      module.define_macros.append(('USE_NO_PROC', '1'))

    if has_function('memmem'):
      module.define_macros.append(('HAVE_MEMMEM', '1'))
    if has_function('strlcpy'):
      module.define_macros.append(('HAVE_STRLCPY', '1'))
    if has_function('strlcat'):
      module.define_macros.append(('HAVE_STRLCAT', '1'))

    if self.enable_profiling:
      module.define_macros.append(('PROFILING_ENABLED', '1'))

    if self.dynamic_linking:
      module.libraries.append('yara')
    else:
      if not self.define or not ('HASH_MODULE', '1') in self.define:
        if (has_function('MD5_Init', libraries=['crypto']) and
            has_function('SHA256_Init', libraries=['crypto'])):
          module.define_macros.append(('HASH_MODULE', '1'))
          module.define_macros.append(('HAVE_LIBCRYPTO', '1'))
          module.libraries.append('crypto')
        else:
          exclusions.append('yara/libyara/modules/hash.c')

      if self.enable_magic:
        module.define_macros.append(('MAGIC_MODULE', '1'))
        module.libraries.append('magic')
      else:
        exclusions.append('yara/libyara/modules/magic.c')

      if self.enable_cuckoo:
        module.define_macros.append(('CUCKOO_MODULE', '1'))
        module.libraries.append('jansson')
      else:
        exclusions.append('yara/libyara/modules/cuckoo.c')

      if self.enable_dotnet:
        module.define_macros.append(('DOTNET_MODULE', '1'))
      else:
        exclusions.append('yara/libyara/modules/dotnet.c')

      if self.enable_dex:
        module.define_macros.append(('DEX_MODULE', '1'))
      else:
        exclusions.append('yara/libyara/modules/dex.c')

      if self.enable_macho:
        module.define_macros.append(('MACHO_MODULE', '1'))
      else:
        exclusions.append('yara/libyara/modules/macho.c')

      exclusions = [os.path.normpath(x) for x in exclusions]

      for directory, _, files in os.walk('yara/libyara/'):
        for x in files:
          x = os.path.normpath(os.path.join(directory, x))
          if x.endswith('.c') and x not in exclusions:
            module.sources.append(x)

    build_ext.run(self)
1118532
def detect_command(cmdlist):
    ''''''

    for platform, command, args in cmdlist:
        if platform is None or sys.platform == platform:
            path = shutil.which(command)
            if path:
                return ' '.join([path, args])

    return ''
1342717
def cmd_wrapper(cmd_name, **kwds):
    """"""
    cmd = si.Commands(cmd_name)
    if not cmd:
        raise Exception(cmd_name + " doesnt found!")
    for arg in cmd.Arguments:
        value = kwds.get(arg.Name)
        if value:
            arg.Value = value
    return cmd.Execute()
411915
def runCmd(cls, cmd):
        
        cit.echo(cmd, "command")
        result = os.system(cmd)
        cls.checkResult(result)
1102208
def _windows_wwns():
    '''
    
    '''
    ps_cmd = r'Get-WmiObject -ErrorAction Stop ' \
             r'-class MSFC_FibrePortHBAAttributes ' \
             r'-namespace "root\WMI" | ' \
             r'Select -Expandproperty Attributes | ' \
             r'%{($_.PortWWN | % {"{0:x2}" -f $_}) -join ""}'
    ret = []
    cmd_ret = salt.modules.cmdmod.powershell(ps_cmd)
    for line in cmd_ret:
        ret.append(line.rstrip())
    return ret
1185352
def run_command(cmd):
    
    child = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    out = [s.decode("utf-8").strip() for s in child.stdout]
    err = [s.decode("utf-8").strip() for s in child.stderr]
    w = child.wait()
    return os.WEXITSTATUS(w), out, err
393949
def run_system_command(self, command):
        
        def wait_for_enter():
            """
            Create a sub application to wait for the enter key press.
            This has two advantages over using 'input'/'raw_input':
            - This will share the same input/output I/O.
            - This doesn't block the event loop.
            """
            from .shortcuts import create_prompt_application

            registry = Registry()

            @registry.add_binding(Keys.ControlJ)
            @registry.add_binding(Keys.ControlM)
            def _(event):
                event.cli.set_return_value(None)

            application = create_prompt_application(
                message='Press ENTER to continue...',
                key_bindings_registry=registry)
            self.run_sub_application(application)

        def run():
            # Try to use the same input/output file descriptors as the one,
            # used to run this application.
            try:
                input_fd = self.input.fileno()
            except AttributeError:
                input_fd = sys.stdin.fileno()
            try:
                output_fd = self.output.fileno()
            except AttributeError:
                output_fd = sys.stdout.fileno()

            # Run sub process.
            # XXX: This will still block the event loop.
            p = Popen(command, shell=True,
                      stdin=input_fd, stdout=output_fd)
            p.wait()

            # Wait for the user to press enter.
            wait_for_enter()

        self.run_in_terminal(run)