2010-08-06 56 views
0

我想寫一個AppleScript,它將通過名稱和絕對路徑添加新的虛擬主機。AppleScript創建VirtualHost

它在我嘗試測試文件(桌面上的txt文件)時工作,但當我嘗試真正的文件(/ private/etc/hosts和/private/etc/apache2/extras/httpd-vhosts.conf)它只是做不行。

該問題似乎圍繞用戶權限的某處,但我不知道如何打開文件以管理員身份進行書寫。我嘗試了我做的方式「做shell腳本」,但它不工作(AR可能是我使用不正確的語法)

我的代碼:

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 [email protected] 
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 

或者:有沒有其他辦法simlpe創建虛擬主機?

回答

1

不是在AppleScript中執行大部分工作,而是在shell腳本中執行此操作。將虛擬主機名&文檔根作爲命令行參數傳遞給您使用管理權限執行的shell腳本。