Search code examples
pythonpython-3.xpython-2.7python-requestssudo

Python Script throwing TTY Sudo error when running SUDO Command


def execute_cli_locally(command, timeout=CLI_EXECUTION_TIMEOUT,
                    return_output_as_string=True)

try:
    logger.info("Executing commands locally :\n%s", command)
    ssh = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)

    stdout, stderr = ssh.communicate(command)

    if ssh.returncode == 0:
        stdout = stdout.strip()
        if len(stdout) != 0:
            logger.info("Stdout :\n%s", stdout)
        return stdout

    else:
        logger.error("Local command execution failed. Error :\n%s" % stderr)
        print_response_and_exit(STATUS_FAILED,
                                "Local commands [%s] execution failed. Error :\n%s" %
                                (command, stderr))

I am executing SUDO command to this python script, but is throwing error "sudo: sorry, you must have a tty to run sudo".


Solution

  • Try to run your script using

    sudo -S python {script_name} {args}.

    It worked for me in some such cases.