Wrapper for commands to be run as root

def root_cmd(command, tty, sudo, allow_failure=False, **kwargs):
    '''
    Wrapper for commands to be run as root
    '''
    logging_command = command
    sudo_password = kwargs.get('sudo_password', None)

    if sudo:
        if sudo_password is None:
            command = 'sudo {0}'.format(command)
            logging_command = command
        else:
            logging_command = 'sudo -S "XXX-REDACTED-XXX" {0}'.format(command)
            command = 'sudo -S {0}'.format(command)

        log.debug('Using sudo to run command %s', logging_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'])

    known_hosts_file = kwargs.get('known_hosts_file', '/dev/null')
    host_key_checking = 'no'
    if known_hosts_file != '/dev/null':
        host_key_checking = 'yes'

    ssh_args.extend([
        # Don't add new hosts to the host key database
        '-oStrictHostKeyChecking={0}'.format(host_key_checking),
        # Set hosts key database path to /dev/null, i.e., non-existing
        '-oUserKnownHostsFile={0}'.format(known_hosts_file),
        # 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',
            # do only use the provided identity file
            '-oIdentitiesOnly=yes',
            # No Keyboard interaction!
            '-oKbdInteractiveAuthentication=no',
            # Also, specify the location of the key file
            '-i {0}'.format(kwargs['key_filename'])
        ])
    if 'ssh_timeout' in kwargs:
        ssh_args.extend(['-oConnectTimeout={0}'.format(kwargs['ssh_timeout'])])

    ssh_args.extend([__ssh_gateway_arguments(kwargs)])

    if 'port' in kwargs:
        ssh_args.extend(['-p {0}'.format(kwargs['port'])])

    cmd = 'ssh {0} {1[username]}@{1[hostname]} '.format(
        ' '.join(ssh_args),
        kwargs
    )
    logging_command = cmd + logging_command
    cmd = cmd + pipes.quote(command)

    hard_timeout = kwargs.get('hard_timeout')
    if hard_timeout is not None:
        logging_command = 'timeout {0} {1}'.format(hard_timeout, logging_command)
        cmd = 'timeout {0} {1}'.format(hard_timeout, cmd)

    log.debug('SSH command: \'%s\'', logging_command)

    retcode = _exec_ssh_cmd(cmd, allow_failure=allow_failure, **kwargs)
    return retcode