运行 shell 管理员脚本在 OS X 上使用 expect

Running shell script as admin using expect on OS X

我正在尝试让非管理员用户 运行 在需要 root 权限的共享环境中使用脚本。我打算构建一个调用 expect 以传递登录凭据的 AppleScript 或 Automator 应用程序(是的,我知道危险,它只会全部执行)。但是我可以登录,但是我尝试 运行 的 shell 脚本似乎没有执行,因为它 returns 立即执行。我是新手,我相信我的脚本有错误。有人有想法吗?

#!/usr/bin/expect
set timeout 60
set password "MyPass"
set command "bash /Applications/mampstack-5.4.36-0/ctlscript.sh start"
eval spawn login admin
expect "assword:"
send "$password\n"
expect "$"
send  "$command\n"
expect "$"
send exit
expect "$"
send exit

不要那样做。相反,编辑 /etc/sudoers 以添加以下行(或者,在 MacOS 的默认配置中,您可以在 /etc/sudoers.d 中创建一个包含以下内容的文件):

# allow use by GUI apps (AppleScript, Automator), which don't have a TTY
Defaults:%staff !requiretty

# on MacOS, all humans are members of the staff group
%staff ALL=(ALL) NOPASSWD: /Applications/mampstack-5.4.36-0/ctlscript.sh start

...然后,让您的 AppleScript 或 Automator 代码 运行:

sudo -u admin /Applications/mampstack-5.4.36-0/ctlscript.sh start

...根本不需要密码。