From 521ab3cdd5afec25cecf7a1f8b92c390e126aef3 Mon Sep 17 00:00:00 2001 From: Will Anderson Date: Thu, 29 May 2014 07:41:59 -0700 Subject: [PATCH] Add Windows privilege elevation handling --- lib/vagrant-hostsupdater/HostsUpdater.rb | 17 +++++++++++++++-- .../fallbacks/win32-append.cmd | 1 + .../fallbacks/win32-sudo.ps1 | 3 +++ 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 lib/vagrant-hostsupdater/fallbacks/win32-append.cmd create mode 100644 lib/vagrant-hostsupdater/fallbacks/win32-sudo.ps1 diff --git a/lib/vagrant-hostsupdater/HostsUpdater.rb b/lib/vagrant-hostsupdater/HostsUpdater.rb index 45ec37a..343f9b7 100644 --- a/lib/vagrant-hostsupdater/HostsUpdater.rb +++ b/lib/vagrant-hostsupdater/HostsUpdater.rb @@ -77,6 +77,18 @@ def addToHosts(entries) content = entries.join("\n").strip if !File.writable?(@@hosts_path) sudo(%Q(sh -c 'echo "#{content}" >> #@@hosts_path')) + elsif Vagrant::Util::Platform.windows? + require 'tmpdir' + uuid = @machine.id || @machine.config.hostsupdater.id + hashedId = Digest::MD5.hexdigest(uuid) + tmpPath = File.join(Dir.tmpdir, 'hosts-' + uuid) + tmpFile = File.open(tmpPath, "w") + tmpFile.write(content) + tmpFile.close() + win32AppendFallback = File.join(File.dirname(__FILE__), "fallbacks", "win32-append.cmd") + win32TmpPath = tmpPath.gsub('/', '\\') + puts win32TmpPath + sudo(%Q(#{win32AppendFallback} #{win32TmpPath} #@@hosts_path)) else content = "\n" + content hostsFile = File.open(@@hosts_path, "a") @@ -88,7 +100,7 @@ def addToHosts(entries) def removeFromHosts(options = {}) uuid = @machine.id || @machine.config.hostsupdater.id hashedId = Digest::MD5.hexdigest(uuid) - if !File.writable?(@@hosts_path) + if !File.writable?(@@hosts_path) || Vagrant::Util::Platform.windows? sudo(%Q(sed -i -e '/#{hashedId}/ d' #@@hosts_path)) else hosts = "" @@ -111,7 +123,8 @@ def signature(name, uuid = self.uuid) def sudo(command) return if !command if Vagrant::Util::Platform.windows? - `#{command}` + win32SudoFallback = File.join(File.dirname(__FILE__), "fallbacks", "win32-sudo.ps1") + puts `powershell -ExecutionPolicy Unrestricted -File #{win32SudoFallback} #{command}` else `sudo #{command}` end diff --git a/lib/vagrant-hostsupdater/fallbacks/win32-append.cmd b/lib/vagrant-hostsupdater/fallbacks/win32-append.cmd new file mode 100644 index 0000000..13a1f54 --- /dev/null +++ b/lib/vagrant-hostsupdater/fallbacks/win32-append.cmd @@ -0,0 +1 @@ +type %1 >> %2 \ No newline at end of file diff --git a/lib/vagrant-hostsupdater/fallbacks/win32-sudo.ps1 b/lib/vagrant-hostsupdater/fallbacks/win32-sudo.ps1 new file mode 100644 index 0000000..967d8a5 --- /dev/null +++ b/lib/vagrant-hostsupdater/fallbacks/win32-sudo.ps1 @@ -0,0 +1,3 @@ +$exe = $args[0] +$argArray = $args[1..($args.length-1)] +Start-Process $exe $argArray -Verb runas \ No newline at end of file