我正在尝试编写一个自动化服务来启动 virtualhost.sh在终端中。
使用“服务”上下文菜单打开对话框以询问虚拟主机的名称,然后运行一个 applescript 来启动终端并传入输入文本。
我想要的是将我的用户名和密码传递给管理员权限,这样我就不需要在终端中使用 sudo 传递它。
这可以通过 do shell script
来完成,但是执行 bin/sh
而 virtualhost.sh
是一个 bash 脚本,所以我得到错误 bin/sh: virtualhost.sh command not found
或者,我可以使用 do script with command
但这不允许我传递用户名和密码。
我的代码是这样的:
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
这会产生前面提到的 bin/sh 错误。
使用用命令执行脚本
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
这会产生一个转义错误:Expected end of line, etc. but found property.
有没有办法正确地做到这一点?
最佳答案
不是特别熟悉 AppleScript Studio,但如果您提供 virtualhost.sh 的完整路径,您可以使用普通的旧 AppleScript(它似乎有同样的问题)来完成。 (此外,“执行 shell 脚本”不需要终端。)示例:
set vhost to "/usr/local/bin/virtualhost.sh " & input
do shell script vhost user name "user" password "pass" ¬
with administrator privileges
您还可以扩展 $PATH(默认情况下为/usr/bin:/bin:/usr/sbin:/sbin 并使用“do shell script”)以包含 virtualhost.sh 的路径,例如:
set vhost to "{ PATH=$PATH:/usr/local/bin; virtualhost.sh " & input & "; }"
do shell script vhost user name "user" password "pass" ¬
with administrator privileges
如果你想要一个相对路径,你可以将 virtualhost.sh 放在脚本应用程序或包中(例如,在内容/资源中),在终端中或通过按住 control 单击并选择“显示包内容”。然后使用“我的路径”:
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
关于bash - 具有输入和管理权限的 Applescript 执行 Shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23905805/