How should I use sudo from an upstart script?
Q: "How should I use sudo
from an upstart (or any other kind of system startup/init) script?"
A: "You shouldn't".
Sudo is really designed to be used interactively (hence the you must have a tty to run sudo
message) -- It's not the right tool to be used in non-interactive startup scripts.
To do what you want requires a little hackery because Upstart doesn't support launching jobs as unprivileged users (yet -- hopefully one day they'll fix this problem). The question was asked and answered over on SuperUser, but I'll reproduce it here as it's equally valuable for sysadmins:
Asking on the #upstart channel on freenode, the official take on the matter is:
A future release of Upstart will have native support for that, but for now, you can use something like:
exec su -s /bin/sh -c 'exec "$0" "$@"' username -- /path/to/command [parameters]
Related videos on Youtube
Justin Moore
Updated on September 18, 2022Comments
-
Justin Moore over 1 year
I am using upstart to run my node.js app on an Amazon Linux AMI EC2 instance. I have had a few issues getting it to work, summarized below.
In my script I had a line like this:
exec sudo -u www /usr/local/bin/node /var/www/foo/app.js >> /var/log/foo.sys.log 2>&1
When run, the job never got passed
stop/waiting
, and when I turned onlog-priority debug
I saw this line:sudo: sorry, you must have a tty to run sudo
I ended up at this post talking about
visudo
and why I shouldn't use it and how it recommends using--session-command
instead. So I changed the line to:exec su --session-command="/usr/local/bin/node /var/www/foo/app.js >> /var/log/foo.sys.log 2>&1" www
The log now says
(sys) Starting
butinitctl status foo
still saysfoo stop/waiting
.It this point I am not sure how what to do to get this working, any help would be appreciated.
Update: I have been over this post from SO and the results are the same.
-
voretaq7 about 12 years(There are also a number of other options mentioned on that SuperUser answer which might be worth investigating. If you find this answer useful please go visit the original question/answer on SuperUser & upvote those as well)