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.
Asked
Active
Viewed 1.8k times
2

Pavanan M S
- 157
- 1
- 2
- 13
1 Answers
3
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, --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.
(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.

Ruslan Osmanov
- 20,486
- 7
- 46
- 60
-
Thanks, now the script works. But I didnt understand the last part of your answer. Yes many of the command needs root privilages. What is the problem with using sudo? – Pavanan M S May 04 '16 at 09:59
-
@user3356760, it's not quite a problem. If the "master" script is written mostly on root's behalf, then it might be better idea to omit `sudo` for root, and require the user to run the script with root permissions. Besides, `sudo` caches user's credentials for 5 minutes(if not overridden by `timeout` in `/etc/sudoers`); then the user has to enter password again. So if a process launched with `sudo` runs more than the `timeout`, the next `sudo` invocation will ask for password again. – Ruslan Osmanov May 04 '16 at 10:17
-
oh. I though that the credentials would kept for a session until user exits. Thanks again. – Pavanan M S May 04 '16 at 11:08