bash - 具有输入和管理权限的 Applescript 执行 Shell

标签 bash shell applescript

我正在尝试编写一个自动化服务来启动 virtualhost.sh在终端中。

使用“服务”上下文菜单打开对话框以询问虚拟主机的名称,然后运行一个 applescript 来启动终端并传入输入文本。

我想要的是将我的用户名和密码传递给管理员权限,这样我就不需要在终端中使用 sudo 传递它。

这可以通过 do shell script 来完成,但是执行 bin/shvirtualhost.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/

相关文章:

cocoa - Applescript 和 Cocoa

bash - bash 脚本中的 mkdir 问题

python - 在 python 中创建具有权限的文件夹的最有效方法是什么(与运行 bash/shell 命令相比)?

applescript - 如何通过 AppleScript 获得 IKEv2 VPN 连接?

python - 退出python程序后调用bash脚本

python - Python 的 IDLE 与其命令行之间的区别

Applescript 中的 Javascript

通过管道传输到 grep 的 python 版本返回代码 1

linux - 如何替换文件中的字符串

bash - 将文件从一个位置复制到另一个位置并重命名的 Shell 脚本将当前日期添加到每个文件