bash 尝试执行 sudo 命令时,shell 脚本给出“sudo:不存在 tty 且未指定 askpass 程序”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37022551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:35:47  来源:igfitidea点击:

shell script giving "sudo: no tty present and no askpass program specified" when trying to execute sudo command

linuxbashshellubuntu

提问by Pavanan M S

  • I have a shell script which creates a user and executes another script as that user

    sudo useradd -m devops
    sudo passwd devops
    sudo adduser devops sudo  
    su - devops -c "sh /path/to/myscript.sh"
    
  • This script creates the user,sets the password and adds user to sudo group as expected.

  • myscript.sh contains commands which uses sudo previlages. (sudo apt-get update, sudo apt-get install software-properties-common etc.). And other commands like ssh-keygen,curl and wget.
  • All commands except the one's with sudo are executed correctly and producing results as excepted.
  • But commands having sudo fails by giving the error "no tty present and no askpass program specified"
  • Why does this happen in this case and how can I overcome this?
  • I have seen similiar questions but will be thankful if I get a clear explanation in this context,thank you.
  • 我有一个 shell 脚本,它创建一个用户并以该用户身份执行另一个脚本

    sudo useradd -m devops
    sudo passwd devops
    sudo adduser devops sudo  
    su - devops -c "sh /path/to/myscript.sh"
    
  • 此脚本按预期创建用户、设置密码并将用户添加到 sudo 组。

  • myscript.sh 包含使用 sudo previlages 的命令。(sudo apt-get update,sudo apt-get install software-properties-common 等)。以及其他命令,如 ssh-keygen、curl 和 wget。
  • 除了带有 sudo 的命令之外的所有命令都被正确执行并产生例外的结果。
  • 但是具有 sudo 的命令会因给出错误“不存在 tty 且未指定 askpass 程序”而失败
  • 为什么在这种情况下会发生这种情况,我该如何克服?
  • 我见过类似的问题,但如果我在这方面得到明确的解释,我将不胜感激,谢谢。

回答by Ruslan Osmanov

Try to replace this:

尝试替换这个:

su - devops -c "sh /path/to/myscript.sh"

with this:

有了这个:

sudo -u devops -H sh -c "sh /path/to/myscript.sh"

The -coption of sudoesn't support interactive mode:

不支持交互模式的-c选项su

-c, --command COMMANDSpecify a command that will be invoked by the shell using its -c.

The executed command will have no controlling terminal. This option cannot be used to execute interractive programs which need a controlling TTY.

-c, --command COMMAND指定将由 shell 使用其 -c 调用的命令。

执行的命令将没有控制终端。此选项不能用于执行需要控制 TTY 的交互式程序。

(man su)

( man su)

By the way, I wouldn't use sudowithin a script everywhere. The script might simply require rootpermissions. Within the script you might drop privileges where necessary by means of the above-mentioned sudocommand.

顺便说一下,我不会sudo在脚本中到处使用。该脚本可能只需要root权限。在脚本中,您可以在必要时通过上述sudo命令删除权限。