I think something that is a key factor here is that because a script is run with sudo, it can do everything root can do. The problem is that other sudo commands within that script don't necessarily inherit root permissions, but are executed as the controlling user. This can often produce the error you see from sudo, even if the parent script itself is allowed via sudo but the subcommands are not.
What's happening is the nested sudo call within that script is failing because sudo would normally prompt for a password, but there's no controlling shell so it can't. This generates the slightly ambiguous
sudo: no tty present and no askpass program specified error that you see.
An easy way to illustrate this is if, like your example, an init script contains internal calls using sudo. Running:
can fail if your own user doesn't have sudo rights to all the sudo calls within, and might give you the sudo tty error. However, running it like this:
sudo sh /etc/init.d/startvpn
would probably work. In the latter case,
sudo sh creates a command shell as root, so anything that is run within that shell actually does execute as root. Root generally has unrestricted sudo permissions so it no longer matters if a command is run with sudo or not.
Some things worth mentioning:
- As others have pointed out, most of this mess can be avoided by not using sudo within scripts. Often sub-commands that fail when run with sudo can work fine without it (when the parent script is run with sudo).
- While running the script with
sudo sh may solve the issue, again there are security implications to doing so. Consider that sudo behaves this way as a sanity check, to ensure that the contents of the script are not doing something they shouldn't, even if the script itself is allowed.
- If the user you are running sudo as also has sufficient blanket permissions, you may not see any of these problems. But they can surface later, say if you develop a script with your own privileged account, and in production it's ran as a non-privileged service account.
- In general you should avoid granting broad sudo permissions to user accounts as a way to solve this kind of issue. If really needed, limit the account access rules to that user and that specific command.