运行SUDO命令时Python脚本引发TTY Sudo错误

时间:2020-05-15 08:51:04

标签: python python-3.x python-2.7 python-requests sudo

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))

我正在对此Python脚本执行SUDO命令,但抛出错误“ sudo:抱歉,您必须具有tty才能运行sudo”。

2 个答案:

答案 0 :(得分:0)

  1. 在终端中输入以下内容:

sudo visudo / etc / sudoers

  1. 找到这一行:

默认必填

并使用'#'注释掉该行,即#Defaults requiretty。

  1. 保存并关闭文件:

在vi / vim中:输入“:wq” –意思是先按:激活命令模式,然后输入wq并按Enter。此顺序将保存文件并退出编辑器。

在nano中:按Ctrl + X,然后按y确认要保存更改。然后按Enter键而不更改默认文件名。

答案 1 :(得分:0)

尝试使用

运行脚本

sudo -S python {script_name} {args}

在某些情况下对我有用。