0

我正在尝试编写一个 AppleScript,它将按名称和绝对路径添加新的虚拟主机。

当我尝试测试文件(桌面上的 txt 文件)时它可以工作,但是当我尝试真实文件(/private/etc/hosts 和 /private/etc/apache2/extras/httpd-vhosts.conf)时它就不起作用。

问题似乎出在用户权限附近,但我不知道如何以管理员身份打开文件进行写入。我尝试了我正在执行“执行 shell 脚本”的方式,但它不起作用(可能我使用的语法不正确)

我的代码:

on run (input)
display dialog "New VirtualHost name" default answer ""
set VirtualHostName to text returned of result

display dialog "Absolute path to VirtualHost's root" default answer "/Library/Webserver/Documents"
set VirtualHostRoot to text returned of result

try
    set hostsNL to "\n127.0.0.1 " & VirtualHostName

    set httpdVhostNL to "\n<VirtualHost 127.0.0.1:80>
ServerAdmin foo@example.com
ServerName " & VirtualHostName & ".local
DocumentRoot '" & VirtualHostRoot & "'
ErrorLog '/private/var/log/apache2/" & VirtualHostName & "-error_log'
CustomLog '/private/var/log/apache2/" & VirtualHostName & "-access_log' common </VirtualHost>"

    set hosts to open for access (POSIX file "/private/etc/hosts") with write permission
    write hostsNL to hosts starting at eof
    close access hosts

    set httpdVhosts to open for access (POSIX file "/private/etc/apache2/extras/httpd-vhosts.conf") with write permission
    write httpdVhostNL to httpdVhosts starting at eof
    close access httpdVhosts


    do shell script "apachectl graceful" with administrator privileges


    return true
on error
    try
        close access hosts
        close access httpdVhosts
    end try
    return false
end try end run

或者:还有其他创建虚拟主机的简单方法吗?

4

1 回答 1

1

与其在 AppleScript 中执行大部分工作,不如在 shell 脚本中执行。将虚拟主机名和文档根目录作为命令行参数传递给您以管理员权限执行的 shell 脚本。

于 2010-12-11T14:38:14.033 回答