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
shell script giving "sudo: no tty present and no askpass program specified" when trying to execute sudo command
提问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 -c
option of su
doesn't support interactive mode:
不支持交互模式的-c
选项su
:
-c, --command COMMAND
Specify 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 sudo
within a script everywhere. The script might simply require root
permissions. Within the script you might drop privileges where necessary by means of the above-mentioned sudo
command.
顺便说一下,我不会sudo
在脚本中到处使用。该脚本可能只需要root
权限。在脚本中,您可以在必要时通过上述sudo
命令删除权限。