# Buggy code
def root_cmd(command, tty, sudo, **kwargs):
    """
    Wrapper for commands to be run as root
    """
    if sudo:
        if "sudo_password" in kwargs and kwargs["sudo_password"] is not None:
            command = 'echo "{1}" | sudo -S {0}'.format(
                command,
                kwargs["sudo_password"],
            )
        else:
            command = "sudo {0}".format(command)
        log.debug("Using sudo to run command {0}".format(command))

    ssh_args = []

    if tty:
        # Use double `-t` on the `ssh` command, it's necessary when `sudo` has
        # `requiretty` enforced.
        ssh_args.extend(["-t", "-t"])

    ssh_args.extend(
        [
            # Don't add new hosts to the host key database
            "-oStrictHostKeyChecking=no",
            # Set hosts key database path to /dev/null, ie, non-existing
            "-oUserKnownHostsFile=/dev/null",
            # Don't re-use the SSH connection. Less failures.
            "-oControlPath=none",
        ]
    )

    if "key_filename" in kwargs:
        # There should never be both a password and an ssh key passed in, so
        ssh_args.extend(
            [
                # tell SSH to skip password authentication
                "-oPasswordAuthentication=no",
                "-oChallengeResponseAuthentication=no",
                # Make sure public key authentication is enabled
                "-oPubkeyAuthentication=yes",
                # No Keyboard interaction!
                "-oKbdInteractiveAuthentication=no",
                # Also, specify the location of the key file
                "-i {0}".format(kwargs["key_filename"]),
            ]
        )

    cmd = "ssh {0} {1[username]}@{1[hostname]} {2}".format(
        " ".join(ssh_args), kwargs, pipes.quote(command)
    )
    log.debug("SSH command: {0!r}".format(cmd))

    try:
        proc = vt.Terminal(
            cmd,
            shell=True,
            log_stdout=True,
            log_stderr=True,
            stream_stdout=kwargs.get("display_ssh_output", True),
            stream_stderr=kwargs.get("display_ssh_output", True),
        )

        sent_password = False
        while proc.isalive():
            stdout, stderr = proc.recv()
            if stdout and SSH_PASSWORD_PROMP_RE.match(stdout):
                if sent_password:
                    # second time??? Wrong password?
                    log.warning("Asking for password again. Wrong one provided???")
                    proc.terminate()
                    return 1

                proc.sendline(kwargs["password"])
                sent_password = True

            time.sleep(0.025)

        return proc.exitstatus
    except vt.TerminalException as err:
        log.error(
            "Failed to execute command {0!r}: {1}\n".format(command, err), exc_info=True
        )

    # Signal an error
    return 1


# Traceback (OSError)
2014-02-12 13:06:50,022 [salt.utils.cloud ][DEBUG   ] SSH command: "ssh -t -t -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oControlPath=none -oPasswordAuthentication=no -oChallengeResponseAuthentica
tion=no -oPubkeyAuthentication=yes -oKbdInteractiveAuthentication=no -i /mnt/stackdio_root/stackdio/storage/cloud/aws-qatp/id_rsa root@10.44.13.132 '/tmp/.saltcloud/deploy.sh -c /tmp/.saltcloud -D git 3a894d76069
9ab155bc63a3e35e6730f87cc7d8c'"
2014-02-12 13:06:50,024 [salt.utils.vt    ][WARNING ] Failed to spawn the VT: out of pty devices
Traceback (most recent call last):
File "/home/stackdio/.virtualenvs/stackdio/src/salt/salt/utils/vt.py", line 198, in __init__
self._spawn()
File "/home/stackdio/.virtualenvs/stackdio/src/salt/salt/utils/vt.py", line 377, in _spawn
self.pid, self.child_fd, self.child_fde = self.__fork_ptys()
File "/home/stackdio/.virtualenvs/stackdio/src/salt/salt/utils/vt.py", line 451, in __fork_ptys
stderr_parent_fd, stderr_child_fd = pty.openpty()
File "/usr/lib/python2.7/pty.py", line 29, in openpty
master_fd, slave_name = _open_terminal()
File "/usr/lib/python2.7/pty.py", line 70, in _open_terminal
raise os.error, 'out of pty devices'
OSError: out of pty devices
2014-02-12 13:06:50,025 [salt.utils.cloud ][ERROR   ] Failed to execute command '/tmp/.saltcloud/deploy.sh -c /tmp/.saltcloud -D git 3a894d760699ab155bc63a3e35e6730f87cc7d8c': Failed to spawn the VT. Error: out of pty devices
Traceback (most recent call last):
File "/home/stackdio/.virtualenvs/stackdio/src/salt/salt/utils/cloud.py", line 1235, in root_cmd
stream_stderr=kwargs.get('display_ssh_output', True)
File "/home/stackdio/.virtualenvs/stackdio/src/salt/salt/utils/vt.py", line 207, in __init__
'Failed to spawn the VT. Error: {0}'.format(err)
TerminalException: Failed to spawn the VT. Error: out of pty devices
2014-02-12 13:06:50,026 [salt.cloud       ][ERROR   ] Failed to deploy 'test-spot-dn-126'. Error: Executing the command '/tmp/.saltcloud/deploy.sh -c /tmp/.saltcloud -D git 3a894d760699ab155bc63a3e35e6730f87cc7d8c' failed
Traceback (most recent call last):
File "/home/stackdio/.virtualenvs/stackdio/src/salt/salt/cloud/__init__.py", line 1699, in create_multiprocessing
local_master=parallel_data['local_master']
File "/home/stackdio/.virtualenvs/stackdio/src/salt/salt/cloud/__init__.py", line 854, in create
output = self.clouds[func](vm_)
File "/home/stackdio/.virtualenvs/stackdio/src/salt/salt/cloud/clouds/ec2.py", line 1576, in create
deployed = salt.utils.cloud.deploy_script(**deploy_kwargs)
File "/home/stackdio/.virtualenvs/stackdio/src/salt/salt/utils/cloud.py", line 864, in deploy_script
deploy_command
SaltCloudSystemExit: Executing the command '/tmp/.saltcloud/deploy.sh -c /tmp/.saltcloud -D git 3a894d760699ab155bc63a3e35e6730f87cc7d8c' failed

# Fixed code
def root_cmd(command, tty, sudo, **kwargs):
    """
    Wrapper for commands to be run as root
    """
    if sudo:
        if "sudo_password" in kwargs and kwargs["sudo_password"] is not None:
            command = 'echo "{1}" | sudo -S {0}'.format(
                command,
                kwargs["sudo_password"],
            )
        else:
            command = "sudo {0}".format(command)
        log.debug("Using sudo to run command {0}".format(command))

    ssh_args = []

    if tty:
        # Use double `-t` on the `ssh` command, it's necessary when `sudo` has
        # `requiretty` enforced.
        ssh_args.extend(["-t", "-t"])

    ssh_args.extend(
        [
            # Don't add new hosts to the host key database
            "-oStrictHostKeyChecking=no",
            # Set hosts key database path to /dev/null, ie, non-existing
            "-oUserKnownHostsFile=/dev/null",
            # Don't re-use the SSH connection. Less failures.
            "-oControlPath=none",
        ]
    )

    if "key_filename" in kwargs:
        # There should never be both a password and an ssh key passed in, so
        ssh_args.extend(
            [
                # tell SSH to skip password authentication
                "-oPasswordAuthentication=no",
                "-oChallengeResponseAuthentication=no",
                # Make sure public key authentication is enabled
                "-oPubkeyAuthentication=yes",
                # No Keyboard interaction!
                "-oKbdInteractiveAuthentication=no",
                # Also, specify the location of the key file
                "-i {0}".format(kwargs["key_filename"]),
            ]
        )

    cmd = "ssh {0} {1[username]}@{1[hostname]} {2}".format(
        " ".join(ssh_args), kwargs, pipes.quote(command)
    )
    log.debug("SSH command: {0!r}".format(cmd))

    try:
        proc = vt.Terminal(
            cmd,
            shell=True,
            log_stdout=True,
            log_stderr=True,
            stream_stdout=kwargs.get("display_ssh_output", True),
            stream_stderr=kwargs.get("display_ssh_output", True),
        )

        sent_password = False
        while proc.isalive():
            stdout, stderr = proc.recv()
            if stdout and SSH_PASSWORD_PROMP_RE.match(stdout):
                if sent_password:
                    # second time??? Wrong password?
                    log.warning("Asking for password again. Wrong one provided???")
                    proc.terminate()
                    return 1

                proc.sendline(kwargs["password"])
                sent_password = True

            time.sleep(0.025)

        proc.close(force=True)
        return proc.exitstatus
    except vt.TerminalException as err:
        log.error(
            "Failed to execute command {0!r}: {1}\n".format(command, err), exc_info=True
        )

    # Signal an error
    return 1