Applescript to create VirtualHost on Apache

Hi

I’m trying to write an AppleScript which will add new virtualhost by name and absolute path.

It works when I try on test files (txt files on desktop) but when I try real files (/private/etc/hosts and /private/etc/apache2/extras/httpd-vhosts.conf) it just does not work.

The problem seems to be somewhere around user permissions, but I have no idea how to open file for writing as administrator. I tried just the way I’m doing ‘do shell script’ but it does not work (ar probably I’m using incorrect syntax)

My code:



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 "
127.0.0.1 " & VirtualHostName
		
		set httpdVhostNL to "
<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


Or: is there other simple way to create virtual hosts?

You can append text to the end of that file like this. “>>” means append text to the end of the file versus “>” which means overwrite the file contents. Note: your path to the file was wrong… the folder is just “extra”.

set vhostsFile to "/private/etc/apache2/extra/httpd-vhosts.conf"
set modifiedText to return & "whatever you want" & return

do shell script "echo " & quoted form of modifiedText & " >> " & quoted form of vhostsFile with administrator privileges

EDIT:
Fixed my use of “>>” as Craig pointed out in his post below.

Hey Hank,

You have those two reversed.

‘>’ is the overwrite command
‘>>’ is the append command

Cheers,

Craig

thanks.
It works - just enough for me, but I wonder if Applescript enables editing files as administrator

Oooops! Thanks.