Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running sudo command in bash script and running it with launchd

I have a bash script that I would like to run with a launchd plist file on OS X. The problem I have is is that the bash script contains sudo commands and it is stopping it from running. So for example my bash script looks like this:

#!/bin/bash
sudo /opt/local/bin/bindfs -u user1 /Library/WebServer/Documents/user1 /vhosts/user1/public_html
sudo /opt/local/bin/bindfs -u user2 /Library/WebServer/Documents/user2 /vhosts/user2/public_html

and my com.test.bindfs.plist file looks like this (created with Lingon):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>GroupName</key>
    <string>admin</string>
    <key>Label</key>
    <string>com.jamespayne.bindfs</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/bindfs.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

I have checked to see that the script works by running it after startup and entering a password but it wont run at startup. The launchd plist is running but it comes up with the following error:

sudo: no tty present and no askpass program specified

Anybody know how to get this working or why I might get that error. Thanks.

like image 249
jpayne Avatar asked Oct 11 '12 08:10

jpayne


3 Answers

You can probably just move the property list to /Library/LaunchDaemons/ and remove the sudo commands from the script.

See man launchd, man launchd.plist, and this blog post.

like image 148
Lri Avatar answered Oct 11 '22 08:10

Lri


sudo is an interactive command, requiring the user the enter their password in order to proceed. I would imagine that sudo, being unable to find a tty, simply exits with an error.

The command you want is su, which is non-interactive, with the only exception being you need to be root to run it. However in your case you probably don't need it at all given the script is being run by an privileged user anyway?

Also why are you putting scripts into /usr/bin? Bad idea; use /usr/local/bin instead (or /usr/local/sbin if it exists).

like image 23
trojanfoe Avatar answered Oct 11 '22 09:10

trojanfoe


If you've come here from Google looking to run a user login LaunchAgent with sudo/root privileges you can do the following:

  • Put the plist in /Library/LaunchAgents if running for all users or ~/Library/LaunchAgents if running for just a single user
  • Have the first ProgramArguments be sudo, and the remaining be the command you are running
  • Set the NOPASSWORD configuration in a /etc/sudoers.d file to allow launchctl to escalate your specific command without an interactive password prompt.

See this answer for a more detailed step-by-step walkthrough.

like image 33
Cory Klein Avatar answered Oct 11 '22 09:10

Cory Klein