コード例 #1
0
ファイル: contextmanager.py プロジェクト: scalp42/fabtools
    def run_guest_command(command, shell=True, pty=False, combine_stderr=True, sudo=False, user=None):
        """
        Run command inside a guest container
        """

        # Use a non-login shell
        _orig_shell = env.shell
        env.shell = "/bin/bash -c"

        # Use double quotes for the sudo prompt
        _orig_sudo_prefix = env.sudo_prefix
        env.sudo_prefix = 'sudo -S -p "%(sudo_prompt)s" '

        # Try to cd to the user's home directory for consistency,
        # as the default directory is "/" with "vzctl exec2"
        if not env.cwd:
            env.command_prefixes.insert(0, "cd 2>/dev/null || true")

        # Build the guest command
        guest_command = _shell_wrap_inner(
            _prefix_commands(_prefix_env_vars(command), "remote"), True, _sudo_prefix(user) if sudo and user else None
        )
        host_command = "vzctl exec2 %s '%s'" % (name_or_ctid, guest_command)

        # Restore env
        env.shell = _orig_shell
        env.sudo_prefix = _orig_sudo_prefix
        if not env.cwd:
            env.command_prefixes.pop(0)

        # Run host command as root
        return _run_host_command(host_command, shell=shell, pty=pty, combine_stderr=combine_stderr)
コード例 #2
0
ファイル: server.py プロジェクト: zhwei820/fabric
        def split_sudo_prompt(self):
            prefix = re.escape(_sudo_prefix(None, None).rstrip()) + ' +'
            command = self.command
            if six.PY3 and isinstance(command, bytes):
                command = command.decode('utf-8')

            result = re.findall(r'^(%s)?(.*)$' % prefix, command)[0]
            self.sudo_prompt, self.command = result
コード例 #3
0
def test_sudo_prefix_with_user():
    """
    _sudo_prefix() returns prefix plus -u flag for nonempty user
    """
    eq_(
        _sudo_prefix(user="******"),
        "%s -u \"foo\" " % (env.sudo_prefix % env.sudo_prompt)
    )
コード例 #4
0
ファイル: test_operations.py プロジェクト: itsmeallan/fabric
def test_sudo_prefix_with_user():
    """
    _sudo_prefix() returns prefix plus -u flag for nonempty user
    """
    eq_(
        _sudo_prefix(user="******", group=None),
        "%s -u \"foo\" " % (env.sudo_prefix % env)
    )
コード例 #5
0
ファイル: server.py プロジェクト: pzrq/fabric
        def split_sudo_prompt(self):
            prefix = re.escape(_sudo_prefix(None, None).rstrip()) + ' +'
            command = self.command
            if six.PY3 and isinstance(command, bytes):
                command = command.decode('utf-8')

            result = re.findall(r'^(%s)?(.*)$' % prefix, command)[0]
            self.sudo_prompt, self.command = result
コード例 #6
0
def test_sudo_prefix_with_user_and_group():
    """
    _sudo_prefix() returns prefix plus -u and -g for nonempty user and group
    """
    eq_(
        _sudo_prefix(user="******", group="bar"),
        "%s -u \"foo\" -g \"bar\" " % (env.sudo_prefix % env)
    )
コード例 #7
0
def test_sudo_prefix_with_group():
    """
    _sudo_prefix() returns prefix plus -g flag for nonempty group
    """
    eq_(
        _sudo_prefix(user=None, group="foo"),
        "%s -g \"foo\" " % (env.sudo_prefix % env)
    )
コード例 #8
0
ファイル: test_operations.py プロジェクト: itsmeallan/fabric
def test_sudo_prefix_with_group():
    """
    _sudo_prefix() returns prefix plus -g flag for nonempty group
    """
    eq_(
        _sudo_prefix(user=None, group="foo"),
        "%s -g \"foo\" " % (env.sudo_prefix % env)
    )
コード例 #9
0
ファイル: test_operations.py プロジェクト: itsmeallan/fabric
def test_sudo_prefix_with_user_and_group():
    """
    _sudo_prefix() returns prefix plus -u and -g for nonempty user and group
    """
    eq_(
        _sudo_prefix(user="******", group="bar"),
        "%s -u \"foo\" -g \"bar\" " % (env.sudo_prefix % env)
    )
コード例 #10
0
ファイル: contextmanager.py プロジェクト: mt3/fabtools
def _run_host_command(command, shell=True, pty=True, combine_stderr=True):
    """
    Run host wrapper command as root

    (Modified from fabric.operations._run_command to ignore prefixes,
    path(), cd(), and always use sudo.)
    """
    # Set up new var so original argument can be displayed verbatim later.
    given_command = command
    # Handle context manager modifications, and shell wrapping
    wrapped_command = _shell_wrap(
        command,
        shell,
        _sudo_prefix(None)
    )
    # Execute info line
    if output.debug:
        print("[%s] %s: %s" % (env.host_string, 'sudo', wrapped_command))
    elif output.running:
        print("[%s] %s: %s" % (env.host_string, 'sudo', given_command))

    # Actual execution, stdin/stdout/stderr handling, and termination
    stdout, stderr, status = _execute(default_channel(), wrapped_command, pty,
        combine_stderr)

    # Assemble output string
    out = _AttributeString(stdout)
    err = _AttributeString(stderr)

    # Error handling
    out.failed = False
    if status != 0:
        out.failed = True
        msg = "%s() received nonzero return code %s while executing" % (
            'sudo', status
        )
        if env.warn_only:
            msg += " '%s'!" % given_command
        else:
            msg += "!\n\nRequested: %s\nExecuted: %s" % (
                given_command, wrapped_command
            )
        error(message=msg, stdout=out, stderr=err)

    # Attach return code to output string so users who have set things to
    # warn only, can inspect the error code.
    out.return_code = status

    # Convenience mirror of .failed
    out.succeeded = not out.failed

    # Attach stderr for anyone interested in that.
    out.stderr = err

    return out
コード例 #11
0
ファイル: contextmanager.py プロジェクト: cyberj/fabtools
def _run_host_command(command, shell=True, pty=True, combine_stderr=True):
    """
    Run host wrapper command as root

    (Modified from fabric.operations._run_command to ignore prefixes,
    path(), cd(), and always use sudo.)
    """
    # Set up new var so original argument can be displayed verbatim later.
    given_command = command
    # Handle context manager modifications, and shell wrapping
    wrapped_command = _shell_wrap(
        command,
        shell,
        _sudo_prefix(None)
    )
    # Execute info line
    if output.debug:
        print("[%s] %s: %s" % (env.host_string, 'sudo', wrapped_command))
    elif output.running:
        print("[%s] %s: %s" % (env.host_string, 'sudo', given_command))

    # Actual execution, stdin/stdout/stderr handling, and termination
    stdout, stderr, status = _execute(default_channel(), wrapped_command, pty,
        combine_stderr)

    # Assemble output string
    out = _AttributeString(stdout)
    err = _AttributeString(stderr)

    # Error handling
    out.failed = False
    if status != 0:
        out.failed = True
        msg = "%s() received nonzero return code %s while executing" % (
            'sudo', status
        )
        if env.warn_only:
            msg += " '%s'!" % given_command
        else:
            msg += "!\n\nRequested: %s\nExecuted: %s" % (
                given_command, wrapped_command
            )
        error(message=msg, stdout=out, stderr=err)

    # Attach return code to output string so users who have set things to
    # warn only, can inspect the error code.
    out.return_code = status

    # Convenience mirror of .failed
    out.succeeded = not out.failed

    # Attach stderr for anyone interested in that.
    out.stderr = err

    return out
コード例 #12
0
ファイル: contextmanager.py プロジェクト: ianjw11/fabtools
    def run_guest_command(command,
                          shell=True,
                          pty=True,
                          combine_stderr=True,
                          sudo=False,
                          user=None,
                          quiet=False,
                          warn_only=False,
                          stdout=None,
                          stderr=None,
                          group=None,
                          timeout=None,
                          **kwargs):
        """
        Run command inside a guest container
        """

        # Use a non-login shell
        _orig_shell = env.shell
        env.shell = '/bin/bash -c'

        # Use double quotes for the sudo prompt
        _orig_sudo_prefix = env.sudo_prefix
        env.sudo_prefix = 'sudo -S -p "%(sudo_prompt)s" '

        # Try to cd to the user's home directory for consistency,
        # as the default directory is "/" with "vzctl exec2"
        if not env.cwd:
            env.command_prefixes.insert(0, 'cd 2>/dev/null || true')

        # Build the guest command
        guest_command = _shell_wrap_inner(
            _prefix_commands(_prefix_env_vars(command), 'remote'), True,
            _sudo_prefix(user) if sudo and user else None)
        host_command = "vzctl exec2 %s '%s'" % (name_or_ctid, guest_command)

        # Restore env
        env.shell = _orig_shell
        env.sudo_prefix = _orig_sudo_prefix
        if not env.cwd:
            env.command_prefixes.pop(0)

        # Run host command as root
        return _run_host_command(host_command,
                                 shell=shell,
                                 pty=pty,
                                 combine_stderr=combine_stderr)
コード例 #13
0
ファイル: monkey.py プロジェクト: gregbanks/basebox
def _run_command_local(command,
                       shell=True,
                       combine_stderr=True,
                       sudo=False,
                       user=None):
    '''
    Local implementation of fabric.operations._run_command that uses
    subprocess to execute.
    '''

    # Conditionally import error handling function, since different fabric
    # versions handle this differently
    try:
        from fabric.utils import error
    except ImportError:
        from fabric.operations import _handle_failure
        error = lambda msg=None, **kwargs: _handle_failure(msg)

    # Set up new var so original argument can be displayed verbatim later.
    given_command = command

    # Pick up cuisine sudo mode and password as appropriate
    if sudo and cuisine.sudo_password():
        sudo_prefix = ('echo "%s" | %s -S -p ""' %
                       (cuisine.sudo_password, env.sudo_prefix))
    else:
        sudo_prefix = env.sudo_prefix

    # Handle context manager modifications, and shell wrapping
    with settings(sudo_prefix=sudo_prefix):
        wrapped_command = _shell_wrap(
            _prefix_commands(_prefix_env_vars(command), 'remote'), shell,
            _sudo_prefix(user) if sudo else None)

    # Execute info line
    which = 'sudo' if sudo else 'run'
    if output.debug:
        print("[%s] %s: %s" % ('local', which, wrapped_command))
    elif output.running:
        print("[%s] %s: %s" % ('local', which, given_command))

    # Actual execution, stdin/stdout/stderr handling, and termination
    stdout, stderr, status = _execute_local(wrapped_command,
                                            shell=shell,
                                            combine_stderr=combine_stderr)

    # Assemble output string
    out = _AttributeString(stdout)
    err = _AttributeString(stderr)

    # Error handling
    out.failed = False
    if status != 0:
        out.failed = True
        msg = "%s() received nonzero return code %s while executing" % (which,
                                                                        status)
        if env.warn_only:
            msg += " '%s'!" % given_command
        else:
            msg += "!\n\nRequested: %s\nExecuted: %s" % (given_command,
                                                         wrapped_command)
        error(message=msg, stdout=out, stderr=err)

    # Attach return code to output string so users who have set things to
    # warn only, can inspect the error code.
    out.return_code = status

    # Convenience mirror of .failed
    out.succeeded = not out.failed

    # Attach stderr for anyone interested in that.
    out.stderr = err

    return out
コード例 #14
0
ファイル: test_operations.py プロジェクト: imankulov/fabric
def test_sudo_prefix_with_user():
    """
    _sudo_prefix() returns prefix plus -u flag for nonempty user
    """
    eq_(_sudo_prefix(user="******"), '%s -u "foo" ' % (env.sudo_prefix % env.sudo_prompt))
コード例 #15
0
ファイル: test_operations.py プロジェクト: itsmeallan/fabric
def test_sudo_prefix_without_user():
    """
    _sudo_prefix() returns standard prefix when user is empty
    """
    eq_(_sudo_prefix(user=None, group=None), env.sudo_prefix % env)
コード例 #16
0
ファイル: test_operations.py プロジェクト: xpoft/fabric
def test_sudo_prefix_without_user():
    """
    _sudo_prefix() returns standard prefix when user is empty
    """
    eq_(_sudo_prefix(user=None), env.sudo_prefix % env)
コード例 #17
0
ファイル: server.py プロジェクト: disqus/fabric
 def split_sudo_prompt(self):
     prefix = re.escape(_sudo_prefix(None).rstrip()) + ' +'
     result = re.findall(r'^(%s)?(.*)$' % prefix, self.command)[0]
     self.sudo_prompt, self.command = result
コード例 #18
0
def _run_host_command(command,
                      shell=True,
                      pty=True,
                      combine_stderr=True,
                      quiet=False,
                      warn_only=False,
                      stdout=None,
                      stderr=None,
                      timeout=None):
    """
    Run host wrapper command as root

    (Modified from fabric.operations._run_command to ignore prefixes,
    path(), cd(), and always use sudo.)
    """
    manager = _noop
    if warn_only:
        manager = warn_only_manager
    # Quiet's behavior is a superset of warn_only's, so it wins.
    if quiet:
        manager = quiet_manager
    with manager():
        # Set up new var so original argument can be displayed verbatim later.
        given_command = command
        # Handle context manager modifications, and shell wrapping
        wrapped_command = _shell_wrap(
            command,  # !! removed _prefix_commands() & _prefix_env_vars()
            shell,
            _sudo_prefix(None)  # !! always use sudo
        )
        # Execute info line
        which = 'sudo'  # !! always use sudo
        if output.debug:
            print(("[%s] %s: %s" % (env.host_string, which, wrapped_command)))
        elif output.running:
            print(("[%s] %s: %s" % (env.host_string, which, given_command)))

        # Actual execution, stdin/stdout/stderr handling, and termination
        result_stdout, result_stderr, status = _execute(
            channel=default_channel(),
            command=wrapped_command,
            pty=pty,
            combine_stderr=combine_stderr,
            invoke_shell=False,
            stdout=stdout,
            stderr=stderr,
            timeout=timeout)

        # Assemble output string
        out = _AttributeString(result_stdout)
        err = _AttributeString(result_stderr)

        # Error handling
        out.failed = False
        out.command = given_command
        out.real_command = wrapped_command
        if status not in env.ok_ret_codes:
            out.failed = True
            msg = "%s() received nonzero return code %s while executing" % (
                which, status)
            if env.warn_only:
                msg += " '%s'!" % given_command
            else:
                msg += "!\n\nRequested: %s\nExecuted: %s" % (given_command,
                                                             wrapped_command)
            error(message=msg, stdout=out, stderr=err)

        # Attach return code to output string so users who have set things to
        # warn only, can inspect the error code.
        out.return_code = status

        # Convenience mirror of .failed
        out.succeeded = not out.failed

        # Attach stderr for anyone interested in that.
        out.stderr = err

        return out
コード例 #19
0
ファイル: contextmanager.py プロジェクト: kstateome/fabtools
def _run_host_command(command, shell=True, pty=True, combine_stderr=True,
    quiet=False, warn_only=False, stdout=None, stderr=None, timeout=None):
    """
    Run host wrapper command as root

    (Modified from fabric.operations._run_command to ignore prefixes,
    path(), cd(), and always use sudo.)
    """
    manager = _noop
    if warn_only:
        manager = warn_only_manager
    # Quiet's behavior is a superset of warn_only's, so it wins.
    if quiet:
        manager = quiet_manager
    with manager():
        # Set up new var so original argument can be displayed verbatim later.
        given_command = command
        # Handle context manager modifications, and shell wrapping
        wrapped_command = _shell_wrap(
            command,    # !! removed _prefix_commands() & _prefix_env_vars()
            shell,
            _sudo_prefix(None)  # !! always use sudo
        )
        # Execute info line
        which = 'sudo'          # !! always use sudo
        if output.debug:
            print("[%s] %s: %s" % (env.host_string, which, wrapped_command))
        elif output.running:
            print("[%s] %s: %s" % (env.host_string, which, given_command))

        # Actual execution, stdin/stdout/stderr handling, and termination
        result_stdout, result_stderr, status = _execute(
            channel=default_channel(), command=wrapped_command, pty=pty,
            combine_stderr=combine_stderr, invoke_shell=False, stdout=stdout,
            stderr=stderr, timeout=timeout)

        # Assemble output string
        out = _AttributeString(result_stdout)
        err = _AttributeString(result_stderr)

        # Error handling
        out.failed = False
        out.command = given_command
        out.real_command = wrapped_command
        if status not in env.ok_ret_codes:
            out.failed = True
            msg = "%s() received nonzero return code %s while executing" % (
                which, status
            )
            if env.warn_only:
                msg += " '%s'!" % given_command
            else:
                msg += "!\n\nRequested: %s\nExecuted: %s" % (
                    given_command, wrapped_command
                )
            error(message=msg, stdout=out, stderr=err)

        # Attach return code to output string so users who have set things to
        # warn only, can inspect the error code.
        out.return_code = status

        # Convenience mirror of .failed
        out.succeeded = not out.failed

        # Attach stderr for anyone interested in that.
        out.stderr = err

        return out
コード例 #20
0
ファイル: server.py プロジェクト: cmattoon/fabric
 def split_sudo_prompt(self):
     prefix = re.escape(_sudo_prefix(None, None).rstrip()) + ' +'
     result = re.findall(r'^(%s)?(.*)$' % prefix, self.command)[0]
     self.sudo_prompt, self.command = result
コード例 #21
0
ファイル: monkey.py プロジェクト: grahamgreen/basebox
def _run_command_local(command, shell=True, combine_stderr=True, sudo=False,
    user=None):
    '''
    Local implementation of fabric.operations._run_command that uses
    subprocess to execute.
    '''

    # Conditionally import error handling function, since different fabric
    # versions handle this differently
    try:
        from fabric.utils import error
    except ImportError:
        from fabric.operations import _handle_failure
        error = lambda msg=None, **kwargs: _handle_failure(msg)

    # Set up new var so original argument can be displayed verbatim later.
    given_command = command

    # Pick up cuisine sudo mode and password as appropriate
    if sudo and cuisine.sudo_password():
        sudo_prefix = ('echo "%s" | %s -S -p ""' %
            (cuisine.sudo_password, env.sudo_prefix))
    else:
        sudo_prefix = env.sudo_prefix

    # Handle context manager modifications, and shell wrapping
    with settings(sudo_prefix=sudo_prefix):
        wrapped_command = _shell_wrap(
            _prefix_commands(_prefix_env_vars(command), 'remote'),
            shell,
            _sudo_prefix(user) if sudo else None
        )

    # Execute info line
    which = 'sudo' if sudo else 'run'
    if output.debug:
        print("[%s] %s: %s" % ('local', which, wrapped_command))
    elif output.running:
        print("[%s] %s: %s" % ('local', which, given_command))

    # Actual execution, stdin/stdout/stderr handling, and termination
    stdout, stderr, status = _execute_local(wrapped_command, shell=shell,
        combine_stderr=combine_stderr)

    # Assemble output string
    out = _AttributeString(stdout)
    err = _AttributeString(stderr)

    # Error handling
    out.failed = False
    if status != 0:
        out.failed = True
        msg = "%s() received nonzero return code %s while executing" % (
            which, status
        )
        if env.warn_only:
            msg += " '%s'!" % given_command
        else:
            msg += "!\n\nRequested: %s\nExecuted: %s" % (
                given_command, wrapped_command
            )
        error(message=msg, stdout=out, stderr=err)

    # Attach return code to output string so users who have set things to
    # warn only, can inspect the error code.
    out.return_code = status

    # Convenience mirror of .failed
    out.succeeded = not out.failed

    # Attach stderr for anyone interested in that.
    out.stderr = err

    return out