Code Bug Fix: Python Script throwing TTY Sudo error when running SUDO Command

Original Source Link

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”.

  1. Type this in terminal:

sudo visudo /etc/sudoers

  1. find this line:

Defaults requiretty

and comment out the line using ‘#’ i.e. #Defaults requiretty.

  1. Save and close the file:

In vi/vim: type “:wq” – this means pressing : first, which activates the command mode, then typing wq and pressing Enter. This sequence will save the file and exit the editor.

In nano: press Ctrl+X, then y to confirm you want to save changes. Then press Enter without changing the default filename.

Try to run your script using

sudo -S python {script_name} {args}.

It worked for me in some such cases.

Tagged : / / / /

Leave a Reply

Your email address will not be published. Required fields are marked *