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

17,851

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.

Share:
17,851

Related videos on Youtube

Pavanan M S
Author by

Pavanan M S

Updated on September 15, 2022

Comments

  • Pavanan M S
    Pavanan M S over 1 year
    • 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.
  • Pavanan M S
    Pavanan M S almost 8 years
    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?
  • Ruslan Osmanov
    Ruslan Osmanov almost 8 years
    @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.
  • Pavanan M S
    Pavanan M S almost 8 years
    oh. I though that the credentials would kept for a session until user exits. Thanks again.