def run(cmd,
        cwd=None,
        stdin=None,
        runas=None,
        shell=DEFAULT_SHELL,
        python_shell=None,
        env=None,
        clean_env=False,
        template=None,
        rstrip=True,
        umask=None,
        output_loglevel='debug',
        log_callback=None,
        timeout=None,
        reset_system_locale=True,
        ignore_retcode=False,
        saltenv='base',
        use_vt=False,
        bg=False,
        encoded_cmd=False,
        **kwargs):
    r'''
    Execute the passed command and return the output as a string

    Note that ``env`` represents the environment variables for the command, and
    should be formatted as a dict, or a YAML string which resolves to a dict.

    :param str cmd: The command to run. ex: 'ls -lart /home'

    :param str cwd: The current working directory to execute the command in,
      defaults to `/root` (`C:\` in windows)

    :param str stdin: A string of standard input can be specified for the
      command to be run using the ``stdin`` parameter. This can be useful in cases
      where sensitive information must be read from standard input.:

    :param str runas: User to run script as. If running on a Windows minion you
      must also pass a password

    :param str password: Windows only. Pass a password if you specify runas.
      This parameter will be ignored for other OS's

      .. versionadded:: 2016.3.0

    :param str shell: Shell to execute under. Defaults to the system default
      shell.

    :param bool python_shell: If False, let python handle the positional
      arguments. Set to True to use shell features, such as pipes or redirection

    :param bool bg: If True, run command in background and do not await or deliver it's results

    :param list env: A list of environment variables to be set prior to
      execution.

        Example:

        .. code-block:: yaml

            salt://scripts/foo.sh:
              cmd.script:
                - env:
                  - BATCH: 'yes'

        .. warning::

            The above illustrates a common PyYAML pitfall, that **yes**,
            **no**, **on**, **off**, **true**, and **false** are all loaded as
            boolean ``True`` and ``False`` values, and must be enclosed in
            quotes to be used as strings. More info on this (and other) PyYAML
            idiosyncrasies can be found :doc:`here
            </topics/troubleshooting/yaml_idiosyncrasies>`.

        Variables as values are not evaluated. So $PATH in the following
        example is a literal '$PATH':

        .. code-block:: yaml

            salt://scripts/bar.sh:
              cmd.script:
                - env: "PATH=/some/path:$PATH"

        One can still use the existing $PATH by using a bit of Jinja:

        .. code-block:: yaml

            {% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}

            mycommand:
              cmd.run:
                - name: ls -l /
                - env:
                  - PATH: {{ [current_path, '/my/special/bin']|join(':') }}

    :param bool clean_env: Attempt to clean out all other shell environment
      variables and set only those provided in the 'env' argument to this
      function.

    :param str template: If this setting is applied then the named templating
      engine will be used to render the downloaded file. Currently jinja, mako,
      and wempy are supported

    :param bool rstrip: Strip all whitespace off the end of output before it is
      returned.

    :param str umask: The umask (in octal) to use when running the command.

    :param str output_loglevel: Control the loglevel at which the output from
      the command is logged. Note that the command being run will still be logged
      (loglevel: DEBUG) regardless, unless ``quiet`` is used for this value.

    :param int timeout: A timeout in seconds for the executed process to return.

    :param bool use_vt: Use VT utils (saltstack) to stream the command output
      more interactively to the console and the logs. This is experimental.

    :param bool encoded_cmd: Specify if the supplied command is encoded.
      Only applies to shell 'powershell'.

    .. warning::
        This function does not process commands through a shell
        unless the python_shell flag is set to True. This means that any
        shell-specific functionality such as 'echo' or the use of pipes,
        redirection or &&, should either be migrated to cmd.shell or
        have the python_shell=True flag set here.

        The use of python_shell=True means that the shell will accept _any_ input
        including potentially malicious commands such as 'good_command;rm -rf /'.
        Be absolutely certain that you have sanitized your input prior to using
        python_shell=True

    CLI Example:

    .. code-block:: bash

        salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'"

    The template arg can be set to 'jinja' or another supported template
    engine to render the command arguments before execution.
    For example:

    .. code-block:: bash

        salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"

    Specify an alternate shell with the shell parameter:

    .. code-block:: bash

        salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell'

    A string of standard input can be specified for the command to be run using
    the ``stdin`` parameter. This can be useful in cases where sensitive
    information must be read from standard input.:

    .. code-block:: bash

        salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'

    If an equal sign (``=``) appears in an argument to a Salt command it is
    interpreted as a keyword argument in the format ``key=val``. That
    processing can be bypassed in order to pass an equal sign through to the
    remote shell command by manually specifying the kwarg:

    .. code-block:: bash

        salt '*' cmd.run cmd='sed -e s/=/:/g'
    '''
    python_shell = _python_shell_default(python_shell,
                                         kwargs.get('__pub_jid', ''))
    ret = _run(cmd,
               runas=runas,
               shell=shell,
               python_shell=python_shell,
               cwd=cwd,
               stdin=stdin,
               stderr=subprocess.STDOUT,
               env=env,
               clean_env=clean_env,
               template=template,
               rstrip=rstrip,
               umask=umask,
               output_loglevel=output_loglevel,
               log_callback=log_callback,
               timeout=timeout,
               reset_system_locale=reset_system_locale,
               ignore_retcode=ignore_retcode,
               saltenv=saltenv,
               pillarenv=kwargs.get('pillarenv'),
               pillar_override=kwargs.get('pillar'),
               use_vt=use_vt,
               password=kwargs.get('password', None),
               bg=bg,
               encoded_cmd=encoded_cmd)

    log_callback = _check_cb(log_callback)

    if 'pid' in ret and '__pub_jid' in kwargs:
        # Stuff the child pid in the JID file
        try:
            proc_dir = os.path.join(__opts__['cachedir'], 'proc')
            jid_file = os.path.join(proc_dir, kwargs['__pub_jid'])
            if os.path.isfile(jid_file):
                serial = salt.payload.Serial(__opts__)
                with salt.utils.fopen(jid_file, 'rb') as fn_:
                    jid_dict = serial.load(fn_)

                if 'child_pids' in jid_dict:
                    jid_dict['child_pids'].append(ret['pid'])
                else:
                    jid_dict['child_pids'] = [ret['pid']]
                # Rewrite file
                with salt.utils.fopen(jid_file, 'w+b') as fn_:
                    fn_.write(serial.dumps(jid_dict))
        except (NameError, __HOLE__):
            # Avoids errors from msgpack not being loaded in salt-ssh
            pass

    lvl = _check_loglevel(output_loglevel)
    if lvl is not None:
        if not ignore_retcode and ret['retcode'] != 0:
            if lvl < LOG_LEVELS['error']:
                lvl = LOG_LEVELS['error']
            msg = (
                'Command \'{0}\' failed with return code: {1}'.format(
                    cmd,
                    ret['retcode']
                )
            )
            log.error(log_callback(msg))
        log.log(lvl, 'output: {0}'.format(log_callback(ret['stdout'])))
    return ret['stdout']
dataset/ETHPy150Open saltstack/salt/salt/modules/cmdmod.py/run