Applescript Execute Shell with Input and Admin Privileges

applescript, bash, shell

Solution

Not specifically familiar with AppleScript Studio, but you can do it in plain old AppleScript (which appears to have the same issue) if you provide a full path to virtualhost.sh. (Also, Terminal is not required with "do shell script".) Example:

set vhost to "/usr/local/bin/virtualhost.sh " & input
do shell script vhost user name "user" password "pass" ¬
    with administrator privileges

You can also extend $PATH (which is by default /usr/bin:/bin:/usr/sbin:/sbin with "do shell script") to include the path to virtualhost.sh, e.g.:

set vhost to "{ PATH=$PATH:/usr/local/bin; virtualhost.sh " & input & "; }"
do shell script vhost user name "user" password "pass" ¬
    with administrator privileges

If you want a relative path, you can put virtualhost.sh inside the script application or bundle (e.g. in Contents/Resources), either in Terminal or by control-clicking and choosing "Show Package Contents". Then use "path to me":

set vhostPath to "'" & POSIX path of (path to me) & ¬
    "/Contents/Resources/virtualhost.sh" & "'"
set vhost to vhostPath & space & input
do shell script vhost user name "user" password "pass" ¬
    with administrator privileges

Problem

I'm trying to write an automator service to fire up virtualhost.sh in a terminal. Using the Services context menu the dialog opens to ask for the name of virtual host, then runs an applescript to launch terminal and pass in the input text. What I want is to pass in my username and password to admin privileges so that I don't need to pass it in the terminal with sudo. This can be done with `do shell script` but that executes a `bin/sh` and the `virtualhost.sh` is a bash script so I get the error `bin/sh: virtualhost.sh command not found` Alternately I can use `do script with command` but this doesn't allow me to pass in the user name and password. My code looks like so: ``` on run {input, parameters} set vhost to "virtualhost.sh " & input tell application "Terminal" activate do shell script vhost user name "user" password "pass" with administrator privileges end tell end run ``` This produces the bin/sh error previously mentioned. With `do script with command` ``` on run {input, parameters} set vhost to "virtualhost.sh " & input tell application "Terminal" activate do script with command vhost user name "user" password "pass" with administrator privileges end tell end run ``` This produces an escaping error: Expected end of line, etc. but found property. Is there a way to do this correctly?

Original source