# Buggy code
def exec_command(self, cmd, in_data=None, sudoable=True):
    """run a command on the remote host"""

    super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)

    if in_data:
        raise AnsibleError(
            "Internal Error: this module does not support optimized module pipelining"
        )

    bufsize = 4096

    try:
        self.ssh.get_transport().set_keepalive(5)
        chan = self.ssh.get_transport().open_session()
    except Exception as e:
        msg = "Failed to open session"
        if len(str(e)) > 0:
            msg += ": %s" % str(e)
        raise AnsibleConnectionFailure(msg)

    # sudo usually requires a PTY (cf. requiretty option), therefore
    # we give it one by default (pty=True in ansble.cfg), and we try
    # to initialise from the calling environment when sudoable is enabled
    if C.PARAMIKO_PTY and sudoable:
        chan.get_pty(
            term=os.getenv("TERM", "vt100"),
            width=int(os.getenv("COLUMNS", 0)),
            height=int(os.getenv("LINES", 0)),
        )

    display.vvv("EXEC %s" % cmd, host=self._play_context.remote_addr)

    cmd = to_bytes(cmd, errors="surrogate_or_strict")

    no_prompt_out = b""
    no_prompt_err = b""
    become_output = b""

    try:
        chan.exec_command(cmd)
        if self._play_context.prompt:
            passprompt = False
            become_sucess = False
            while not (become_sucess or passprompt):
                display.debug("Waiting for Privilege Escalation input")

                chunk = chan.recv(bufsize)
                display.debug("chunk is: %s" % chunk)
                if not chunk:
                    if "unknown user" in become_output:
                        raise AnsibleError(
                            "user %s does not exist" % self._play_context.become_user
                        )
                    else:
                        break
                        # raise AnsibleError('ssh connection closed waiting for password prompt')
                become_output += chunk

                # need to check every line because we might get lectured
                # and we might get the middle of a line in a chunk
                for l in become_output.splitlines(True):
                    if self.check_become_success(l):
                        become_sucess = True
                        break
                    elif self.check_password_prompt(l):
                        passprompt = True
                        break

            if passprompt:
                if self._play_context.become and self._play_context.become_pass:
                    chan.sendall(self._play_context.become_pass + "\n")
                else:
                    raise AnsibleError("A password is reqired but none was supplied")
            else:
                no_prompt_out += become_output
                no_prompt_err += become_output
    except socket.timeout:
        raise AnsibleError(
            "ssh timed out waiting for privilege escalation.\n" + become_output
        )

    stdout = b"".join(chan.makefile("rb", bufsize))
    stderr = b"".join(chan.makefile_stderr("rb", bufsize))

    return (chan.recv_exit_status(), no_prompt_out + stdout, no_prompt_out + stderr)


# Traceback (UnicodeEncodeError)
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/executor/task_executor.py", line 96, in run
item_results = self._run_loop(items)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/executor/task_executor.py", line 252, in _run_loop
res = self._execute(variables=task_vars)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/executor/task_executor.py", line 447, in _execute
result = self._handler.run(task_vars=variables)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/action/normal.py", line 33, in run
results = merge_hash(results, self._execute_module(tmp=tmp, task_vars=task_vars))
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/action/__init__.py", line 647, in _execute_module
res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/action/__init__.py", line 721, in _low_level_execute_command
rc, stdout, stderr = self._connection.exec_command(cmd, in_data=in_data, sudoable=sudoable)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/connection/paramiko_ssh.py", line 311, in exec_command
chan.sendall(self._play_context.become_pass + '\n')
File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 797, in sendall
sent = self.send(s)
File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 729, in send
m.add_string(s[:size])
File "/usr/lib/python2.7/dist-packages/paramiko/message.py", line 259, in add_string
self.packet.write(s)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 1: ordinal not in range(128)

fatal: [server.example.com]: FAILED! => {"failed": true, "msg": "Unexpected failure during module execution.", "stdout": ""}

# Fixed code
def exec_command(self, cmd, in_data=None, sudoable=True):
    """run a command on the remote host"""

    super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)

    if in_data:
        raise AnsibleError(
            "Internal Error: this module does not support optimized module pipelining"
        )

    bufsize = 4096

    try:
        self.ssh.get_transport().set_keepalive(5)
        chan = self.ssh.get_transport().open_session()
    except Exception as e:
        msg = "Failed to open session"
        if len(str(e)) > 0:
            msg += ": %s" % str(e)
        raise AnsibleConnectionFailure(msg)

    # sudo usually requires a PTY (cf. requiretty option), therefore
    # we give it one by default (pty=True in ansble.cfg), and we try
    # to initialise from the calling environment when sudoable is enabled
    if C.PARAMIKO_PTY and sudoable:
        chan.get_pty(
            term=os.getenv("TERM", "vt100"),
            width=int(os.getenv("COLUMNS", 0)),
            height=int(os.getenv("LINES", 0)),
        )

    display.vvv("EXEC %s" % cmd, host=self._play_context.remote_addr)

    cmd = to_bytes(cmd, errors="surrogate_or_strict")

    no_prompt_out = b""
    no_prompt_err = b""
    become_output = b""

    try:
        chan.exec_command(cmd)
        if self._play_context.prompt:
            passprompt = False
            become_sucess = False
            while not (become_sucess or passprompt):
                display.debug("Waiting for Privilege Escalation input")

                chunk = chan.recv(bufsize)
                display.debug("chunk is: %s" % chunk)
                if not chunk:
                    if "unknown user" in become_output:
                        raise AnsibleError(
                            "user %s does not exist" % self._play_context.become_user
                        )
                    else:
                        break
                        # raise AnsibleError('ssh connection closed waiting for password prompt')
                become_output += chunk

                # need to check every line because we might get lectured
                # and we might get the middle of a line in a chunk
                for l in become_output.splitlines(True):
                    if self.check_become_success(l):
                        become_sucess = True
                        break
                    elif self.check_password_prompt(l):
                        passprompt = True
                        break

            if passprompt:
                if self._play_context.become and self._play_context.become_pass:
                    chan.sendall(to_bytes(self._play_context.become_pass) + b"\n")
                else:
                    raise AnsibleError("A password is reqired but none was supplied")
            else:
                no_prompt_out += become_output
                no_prompt_err += become_output
    except socket.timeout:
        raise AnsibleError(
            "ssh timed out waiting for privilege escalation.\n" + become_output
        )

    stdout = b"".join(chan.makefile("rb", bufsize))
    stderr = b"".join(chan.makefile_stderr("rb", bufsize))

    return (chan.recv_exit_status(), no_prompt_out + stdout, no_prompt_out + stderr)