· 6 years ago · Mar 26, 2019, 02:24 PM
1# -------------------------------------------------------------------------- #
2# Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs #
3# #
4# Licensed under the Apache License, Version 2.0 (the "License"); you may #
5# not use this file except in compliance with the License. You may obtain #
6# a copy of the License at #
7# #
8# http://www.apache.org/licenses/LICENSE-2.0 #
9# #
10# Unless required by applicable law or agreed to in writing, software #
11# distributed under the License is distributed on an "AS IS" BASIS, #
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
13# See the License for the specific language governing permissions and #
14# limitations under the License. #
15#--------------------------------------------------------------------------- #
16
17# Original work by:
18
19#################################################################
20##### Windows Powershell Script to configure OpenNebula VMs #####
21##### Created by andremonteiro@ua.pt and tsbatista@ua.pt #####
22##### DETI/IEETA Universidade de Aveiro 2011 #####
23#################################################################
24
25Start-Transcript -Append -Path "$env:SystemDrive\.opennebula-context.out" | Out-Null
26
27Write-Output "Running Script: $($MyInvocation.InvocationName)"
28Get-Date
29Write-Output ""
30
31Set-ExecutionPolicy unrestricted -force # not needed if already done once on the VM
32[string]$computerName = "$env:computername"
33[string]$ConnectionString = "WinNT://$computerName"
34
35function getContext($file) {
36 Write-Host "Loading Context File"
37 $context = @{}
38 switch -regex -file $file {
39 "^([^=]+)='(.+?)'$" {
40 $name, $value = $matches[1..2]
41 $context[$name] = $value
42 }
43 }
44 return $context
45}
46
47function envContext($context) {
48 ForEach ($h in $context.GetEnumerator()) {
49 $name = "Env:"+$h.Name
50 Set-Item $name $h.Value
51 }
52}
53
54function addLocalUser($context) {
55 # Create new user
56 $username = $context["USERNAME"]
57 $password = $context["PASSWORD"]
58
59 if ($username -Or $password) {
60
61 if ($username -eq $null) {
62 # ATTENTION - Language/Regional settings have influence on the naming
63 # of this user. Use the User SID instead (S-1-5-21domain-500)
64 $username = (Get-WmiObject -Class "Win32_UserAccount" |
65 where { $_.SID -like "S-1-5-21[0-9-]*-500" } |
66 select -ExpandProperty Name)
67 }
68
69 Write-Output "Creating Account for $username"
70
71 $ADSI = [adsi]$ConnectionString
72
73 if(!([ADSI]::Exists("WinNT://$computerName/$username"))) {
74 # User does not exist, Create the User
75 Write-Output "- Creating account"
76 $user = $ADSI.Create("user",$username)
77 $user.setPassword($password)
78 $user.SetInfo()
79 } else {
80 # User exists, Set Password
81 Write-Output "- Setting Password"
82 $admin = [ADSI]"WinNT://$env:computername/$username"
83 $admin.psbase.invoke("SetPassword", $password)
84 }
85
86 # Set Password to Never Expire
87 Write-Output "- Setting password to never expire"
88 $admin = [ADSI]"WinNT://$env:computername/$username"
89 $admin.UserFlags.value = $admin.UserFlags.value -bor 0x10000
90 $admin.CommitChanges()
91
92 # Add user to local Administrators
93 # ATTENTION - Language/Regional settings have influence on the naming
94 # of this group. Use the Group SID instead (S-1-5-32-544)
95 $groups = (Get-WmiObject -Class "Win32_Group" |
96 where { $_.SID -like "S-1-5-32-544" } |
97 select -ExpandProperty Name)
98
99 ForEach ($grp in $groups) {
100
101 # Make sure the Group exists
102 If([ADSI]::Exists("WinNT://$computerName/$grp,group")) {
103
104 # Check if the user is a Member of the Group
105 $group = [ADSI] "WinNT://$computerName/$grp,group"
106 $members = @($group.psbase.Invoke("Members"))
107
108 $memberNames = @()
109 $members | ForEach-Object {
110 # https://p0w3rsh3ll.wordpress.com/2016/06/14/any-documented-adsi-changes-in-powershell-5-0/
111 $memberNames += ([ADSI]$_).psbase.InvokeGet('Name')
112 }
113
114 If (-Not ($memberNames -Contains $username)) {
115
116 # Make sure the user exists, again
117 if([ADSI]::Exists("WinNT://$computerName/$username")) {
118
119 # Add the user
120 Write-Output "- Adding to $grp"
121 $group.Add("WinNT://$computerName/$username")
122 }
123 }
124 }
125 }
126 }
127 Write-Output ""
128}
129
130function configureNetwork($context) {
131
132 # Get the NIC in the Context
133 $nicIds = ($context.Keys | Where {$_ -match '^ETH\d+_IP6?$'} | ForEach-Object {$_ -replace '(^ETH|_IP$|_IP6$)',''} | Sort-Object -Unique)
134
135 $nicId = 0;
136
137 foreach ($nicId in $nicIds) {
138 # Retrieve data from Context
139 $nicIpKey = "ETH" + $nicId + "_IP"
140 $nicIp6Key = "ETH" + $nicId + "_IP6"
141 $nicPrefix = "ETH" + $nicId + "_"
142
143 $ipKey = $nicPrefix + "IP"
144 $netmaskKey = $nicPrefix + "MASK"
145 $macKey = $nicPrefix + "MAC"
146 $dnsKey = $nicPrefix + "DNS"
147 $dnsSuffixKey = $nicPrefix + "SEARCH_DOMAIN"
148 $gatewayKey = $nicPrefix + "GATEWAY"
149 $networkKey = $nicPrefix + "NETWORK"
150
151 $ip6Key = $nicPrefix + "IP6"
152 $ip6ULAKey = $nicPrefix + "IP6_ULA"
153 $ip6PrefixKey = $nicPrefix + "IP6_PREFIX_LENGTH"
154 $gw6Key = $nicPrefix + "GATEWAY6"
155 $mtuKey = $nicPrefix + "MTU"
156
157 $ip = $context[$ipKey]
158 $netmask = $context[$netmaskKey]
159 $mac = $context[$macKey]
160 $dns = (($context[$dnsKey] -split " " | Where {$_ -match '^(([0-9]*).?){4}$'}) -join ' ')
161 $dns6 = (($context[$dnsKey] -split " " | Where {$_ -match '^(([0-9A-F]*):?)*$'}) -join ' ')
162 $dnsSuffix = $context[$dnsSuffixKey]
163 $gateway = $context[$gatewayKey]
164 $network = $context[$networkKey]
165 $mtu = $context[$mtuKey]
166
167 $ip6 = $context[$ip6Key]
168 $ip6ULA = $context[$ip6ULAKey]
169 $ip6Prefix = $context[$ip6PrefixKey]
170 $gw6 = $context[$gw6Key]
171
172 $mac = $mac.ToUpper()
173 if (!$netmask) {
174 $netmask = "255.255.255.0"
175 }
176 if (!$ip6Prefix) {
177 $ip6Prefix = "64"
178 }
179 if (!$network) {
180 $network = $ip -replace "\.[^.]+$", ".0"
181 }
182 if ($nicId -eq 0 -and !$gateway) {
183 $gateway = $ip -replace "\.[^.]+$", ".1"
184 }
185
186 # Load the NIC Configuration Object
187 $nic = $false
188 $retry = 30
189 do {
190 $retry--
191 Start-Sleep -s 1
192 $nic = Get-WMIObject Win32_NetworkAdapterConfiguration | `
193 where {$_.IPEnabled -eq "TRUE" -and $_.MACAddress -eq $mac}
194 } while (!$nic -and $retry)
195
196 If (!$nic) {
197 Write-Output ("Configuring Network Settings: " + $mac)
198 Write-Output (" ... Failed: Interface with MAC not found")
199 Continue
200 }
201
202 Write-Output ("Configuring Network Settings: " + $nic.Description.ToString())
203
204 # Release the DHCP lease, will fail if adapter not DHCP Configured
205 Write-Output "- Release DHCP Lease"
206 $ret = $nic.ReleaseDHCPLease()
207 If ($ret.ReturnValue) {
208 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
209 } Else {
210 Write-Output " ... Success"
211 }
212
213 if ($ip) {
214 # set static IP address and retry for few times if there was a problem
215 # with acquiring write lock (2147786788) for network configuration
216 # https://msdn.microsoft.com/en-us/library/aa390383(v=vs.85).aspx
217 Write-Output "- Set Static IP"
218 $retry = 10
219 do {
220 $retry--
221 Start-Sleep -s 1
222 $ret = $nic.EnableStatic($ip , $netmask)
223 } while ($ret.ReturnValue -eq 2147786788 -and $retry);
224 If ($ret.ReturnValue) {
225 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
226 } Else {
227 Write-Output " ... Success"
228 }
229
230 # Set IPv4 MTU
231 if ($mtu) {
232 Write-Output "- Set MTU: ${mtu}"
233 netsh interface ipv4 set interface $nic.InterfaceIndex mtu=$mtu
234
235 If ($?) {
236 Write-Output " ... Success"
237 } Else {
238 Write-Output " ... Failed"
239 }
240 }
241
242 if ($gateway) {
243
244 # Set the Gateway
245 Write-Output "- Set Gateway"
246 $ret = $nic.SetGateways($gateway)
247 If ($ret.ReturnValue) {
248 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
249 } Else {
250 Write-Output " ... Success"
251 }
252
253 If ($dns) {
254
255 # DNS Servers
256 $dnsServers = $dns -split " "
257
258 # DNS Server Search Order
259 Write-Output "- Set DNS Server Search Order"
260 $ret = $nic.SetDNSServerSearchOrder($dnsServers)
261 If ($ret.ReturnValue) {
262 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
263 } Else {
264 Write-Output " ... Success"
265 }
266
267 # Set Dynamic DNS Registration
268 Write-Output "- Set Dynamic DNS Registration"
269 $ret = $nic.SetDynamicDNSRegistration("TRUE")
270 If ($ret.ReturnValue) {
271 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
272 } Else {
273 Write-Output " ... Success"
274 }
275
276 # WINS Addresses
277 # $nic.SetWINSServer($DNSServers[0], $DNSServers[1])
278 }
279
280 if ($dnsSuffix) {
281
282 # DNS Suffixes
283 $dnsSuffixes = $dnsSuffix -split " "
284
285 # Set DNS Suffix Search Order
286 Write-Output "- Set DNS Suffix Search Order"
287 $ret = ([WMIClass]"Win32_NetworkAdapterConfiguration").SetDNSSuffixSearchOrder(($dnsSuffixes))
288 If ($ret.ReturnValue) {
289 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
290 } Else {
291 Write-Output " ... Success"
292 }
293
294 # Set Primary DNS Domain
295 Write-Output "- Set Primary DNS Domain"
296 $ret = $nic.SetDNSDomain($dnsSuffixes[0])
297 If ($ret.ReturnValue) {
298 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
299 } Else {
300 Write-Output " ... Success"
301 }
302 }
303 }
304 }
305
306 if ($ip6) {
307 # We need the connection ID (i.e. "Local Area Connection",
308 # which can be discovered from the NetworkAdapter object
309 $na = Get-WMIObject Win32_NetworkAdapter | `
310 where {$_.deviceId -eq $nic.index}
311
312
313 # Disable router discovery
314 Write-Output "- Disable IPv6 router discovery"
315 netsh interface ipv6 set interface $na.NetConnectionId `
316 advertise=disabled routerdiscover=disabled | Out-Null
317
318 If ($?) {
319 Write-Output " ... Success"
320 } Else {
321 Write-Output " ... Failed"
322 }
323
324 # Remove old IPv6 addresses
325 Write-Output "- Removing old IPv6 addresses"
326 if (Get-Command Remove-NetIPAddress -errorAction SilentlyContinue) {
327 # Windows 8.1 and Server 2012 R2 and up
328 # we want to remove everything except the link-local address
329 Remove-NetIPAddress -InterfaceAlias $na.NetConnectionId `
330 -AddressFamily IPv6 -Confirm:$false `
331 -PrefixOrigin Other,Manual,Dhcp,RouterAdvertisement `
332 -errorAction SilentlyContinue
333
334 If ($?) {
335 Write-Output " ... Success"
336 } Else {
337 Write-Output " ... Nothing to do"
338 }
339 } Else {
340 Write-Output " ... Not implemented"
341 }
342
343 # Set IPv6 Address
344 Write-Output "- Set IPv6 Address"
345 netsh interface ipv6 add address $na.NetConnectionId $ip6/$ip6Prefix
346 If ($? -And $ip6ULA) {
347 netsh interface ipv6 add address $na.NetConnectionId $ip6ULA/64
348 }
349
350 If ($?) {
351 Write-Output " ... Success"
352 } Else {
353 Write-Output " ... Failed"
354 }
355
356 # Set IPv6 Gateway
357 if ($gw6) {
358 Write-Output "- Set IPv6 Gateway"
359 netsh interface ipv6 add route ::/0 $na.NetConnectionId $gw6
360
361 If ($?) {
362 Write-Output " ... Success"
363 } Else {
364 Write-Output " ... Failed"
365 }
366 }
367
368 # Set IPv6 MTU
369 if ($mtu) {
370 Write-Output "- Set IPv6 MTU: ${mtu}"
371 netsh interface ipv6 set interface $nic.InterfaceIndex mtu=$mtu
372
373 If ($?) {
374 Write-Output " ... Success"
375 } Else {
376 Write-Output " ... Failed"
377 }
378 }
379
380 # Remove old IPv6 DNS Servers
381 Write-Output "- Removing old IPv6 DNS Servers"
382 netsh interface ipv6 set dnsservers $na.NetConnectionId source=static address=
383
384 If ($dns6) {
385 # Set IPv6 DNS Servers
386 Write-Output "- Set IPv6 DNS Servers"
387 $dns6Servers = $dns6 -split " "
388 foreach ($dns6Server in $dns6Servers) {
389 netsh interface ipv6 add dnsserver $na.NetConnectionId address=$dns6Server
390 }
391 }
392
393 doPing($ip6)
394 }
395
396 # Get the aliases for the NIC in the Context
397 $aliasIds = ($context.Keys | Where {$_ -match "^ETH${nicId}_ALIAS\d+_IP6?$"} | ForEach-Object {$_ -replace '(^ETH\d+_ALIAS|_IP$|_IP6$)',''} | Sort-Object -Unique)
398
399 foreach ($aliasId in $aliasIds) {
400 $aliasPrefix = "ETH${nicId}_ALIAS${aliasId}"
401 $aliasIp = $context[$aliasPrefix + '_IP']
402 $aliasNetmask = $context[$aliasPrefix + '_MASK']
403 $aliasIp6 = $context[$aliasPrefix + '_IP6']
404 $aliasIp6ULA = $context[$aliasPrefix + '_IP6_ULA']
405 $aliasIp6Prefix = $context[$aliasPrefix + '_IP6_PREFIX_LENGTH']
406
407 if (!$aliasNetmask) {
408 $aliasNetmask = "255.255.255.0"
409 }
410
411 if (!$aliasIp6Prefix) {
412 $aliasIp6Prefix = "64"
413 }
414
415 if ($aliasIp) {
416 Write-Output "- Set Additional Static IP (${aliasPrefix})"
417 netsh interface ipv4 add address $nic.InterfaceIndex $aliasIp $aliasNetmask
418
419 If ($?) {
420 Write-Output " ... Success"
421 } Else {
422 Write-Output " ... Failed"
423 }
424 }
425
426 if ($aliasIp6) {
427 Write-Output "- Set Additional IPv6 Address (${aliasPrefix})"
428 netsh interface ipv6 add address $nic.InterfaceIndex $aliasIp6/$aliasIp6Prefix
429 If ($? -And $aliasIp6ULA) {
430 netsh interface ipv6 add address $nic.InterfaceIndex $aliasIp6ULA/64
431 }
432
433 If ($?) {
434 Write-Output " ... Success"
435 } Else {
436 Write-Output " ... Failed"
437 }
438 }
439 }
440
441 If ($ip) {
442 doPing($ip)
443 }
444 }
445
446 Write-Output ""
447}
448
449function renameComputer($context) {
450
451 # Initialize Variables
452 $current_hostname = hostname
453 $context_hostname = $context["SET_HOSTNAME"]
454 $logged_hostname = "Unknown"
455
456 if (! $context_hostname) {
457 return
458 }
459
460 $splitted_hostname = $context_hostname.split('.')
461 $context_hostname = $splitted_hostname[0]
462 $context_domain = $splitted_hostname[1..$splitted_hostname.length] -join '.'
463
464 If ($context_domain) {
465 Write-Output "Changing Domain to $context_domain"
466
467 $networkConfig = Get-WmiObject Win32_NetworkAdapterConfiguration -filter "ipenabled = 'true'"
468 $ret = $networkConfig.SetDnsDomain($context_domain)
469
470 If ($ret.ReturnValue) {
471
472 # Returned Non Zero, Failed, No restart
473 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
474 } Else {
475
476 # Returned Zero, Success
477 Write-Output "... Success"
478 }
479 }
480
481 # Check for the .opennebula-renamed file
482 If (Test-Path "$env:SystemDrive\.opennebula-renamed") {
483
484 # Grab the JSON content
485 $json = Get-Content -Path "$env:SystemDrive\.opennebula-renamed" `
486 | Out-String
487
488 # Convert to a Hash Table and set the Logged Hostname
489 try {
490 $status = $json | ConvertFrom-Json
491 $logged_hostname = $status.ComputerName
492 }
493 # Invalid JSON
494 catch [System.ArgumentException] {
495 Write-Output "Invalid JSON:"
496 Write-Output $json.ToString()
497 }
498 }
499
500 If ((!(Test-Path "$env:SystemDrive\.opennebula-renamed")) -or `
501 ($context_hostname.ToLower() -ne $logged_hostname.ToLower())) {
502
503 # .opennebula-renamed not found or the logged_name does not match the
504 # context_name, rename the computer
505
506 Write-Output "Changing Hostname to $context_hostname"
507 # Load the ComputerSystem Object
508 $ComputerInfo = Get-WmiObject -Class Win32_ComputerSystem
509
510 # Rename the computer
511 $ret = $ComputerInfo.rename($context_hostname)
512
513 $contents = @{}
514 $contents["ComputerName"] = $context_hostname
515 ConvertTo-Json $contents | Out-File "$env:SystemDrive\.opennebula-renamed"
516
517 # Check success
518 If ($ret.ReturnValue) {
519
520 # Returned Non Zero, Failed, No restart
521 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
522 Write-Output " Check the computername."
523 Write-Output "Possible Issues: The name cannot include control" `
524 "characters, leading or trailing spaces, or any of" `
525 "the following characters: `" / \ [ ] : | < > + = ; , ?"
526
527 } Else {
528
529 # Returned Zero, Success
530 Write-Output "... Success"
531
532 # Restart the Computer
533 Write-Output "... Rebooting"
534 Restart-Computer -Force
535
536 # Exit here so the script doesn't continue to run
537 Exit 0
538 }
539 } else {
540 If ($current_hostname -eq $context_hostname) {
541 Write-Output "Computer Name already set: $context_hostname"
542 }
543 ElseIf (($current_hostname -ne $context_hostname) -and `
544 ($context_hostname -eq $logged_hostname)) {
545 Write-Output "Computer Rename Attempted but failed:"
546 Write-Output "- Current: $current_hostname"
547 Write-Output "- Context: $context_hostname"
548 }
549 }
550 Write-Output ""
551}
552
553function enableRemoteDesktop()
554{
555 Write-Output "Enabling Remote Desktop"
556 # Windows 7 only - add firewall exception for RDP
557 Write-Output "- Enable Remote Desktop Rule Group"
558 netsh advfirewall Firewall set rule group="Remote Desktop" new enable=yes
559
560 # Enable RDP
561 Write-Output "- Enable Allow Terminal Services Connections"
562 $ret = (Get-WmiObject -Class "Win32_TerminalServiceSetting" -Namespace root\cimv2\terminalservices).SetAllowTsConnections(1)
563 If ($ret.ReturnValue) {
564 Write-Output (" ... Failed: " + $ret.ReturnValue.ToString())
565 } Else {
566 Write-Output " ... Success"
567 }
568 Write-Output ""
569}
570
571function enablePing()
572{
573 Write-Output "Enabling Ping"
574 #Create firewall manager object
575 $fwm=new-object -com hnetcfg.fwmgr
576
577 # Get current profile
578 $pro=$fwm.LocalPolicy.CurrentProfile
579
580 Write-Output "- Enable Allow Inbound Echo Requests"
581 $ret = $pro.IcmpSettings.AllowInboundEchoRequest=$true
582 If ($ret) {
583 Write-Output " ... Success"
584 } Else {
585 Write-Output " ... Failed"
586 }
587
588 Write-Output ""
589}
590
591function doPing($ip, $retries=20)
592{
593 Write-Output "- Ping Interface IP $ip"
594
595 $ping = $false
596 $retry = 0
597 do {
598 $retry++
599 Start-Sleep -s 1
600 $ping = Test-Connection -ComputerName $ip -Count 1 -Quiet -ErrorAction SilentlyContinue
601 } while (!$ping -and ($retry -lt $retries))
602
603 If ($ping) {
604 Write-Output " ... Success ($retry tries)"
605 } Else {
606 Write-Output " ... Failed ($retry tries)"
607 }
608}
609
610function runScripts($context, $contextLetter)
611{
612 Write-Output "Running Scripts"
613
614 # Get list of scripts to run, " " delimited
615 $initscripts = $context["INIT_SCRIPTS"]
616
617 if ($initscripts) {
618
619 # Parse each script and run it
620 ForEach ($script in $initscripts.split(" ")) {
621
622 $script = $contextLetter + $script
623 If (Test-Path $script) {
624 Write-Output "- $script"
625 envContext($context)
626 & $script
627 }
628
629 }
630 }
631
632 # Execute START_SCRIPT or START_SCRIPT_64
633 $startScript = $context["START_SCRIPT"]
634 $startScript64 = $context["START_SCRIPT_BASE64"]
635
636 If ($startScript64) {
637 $startScript = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($startScript64))
638 }
639
640 If ($startScript) {
641
642 # Save the script as .opennebula-startscript.ps1
643 $startScriptPS = "$env:SystemDrive\.opennebula-startscript.ps1"
644 $startScript | Out-File $startScriptPS "UTF8"
645
646 # Launch the Script
647 Write-Output "- $startScriptPS"
648 envContext($context)
649 & $startScriptPS
650
651 }
652 Write-Output ""
653}
654
655function extendPartition($disk, $part)
656{
657 "select disk $disk","select partition $part","extend" | diskpart | Out-Null
658}
659
660function extendPartitions()
661{
662 Write-Output "- Extend partitions"
663
664 "rescan" | diskpart
665
666 #$diskIds = ((wmic diskdrive get Index | Select-String "[0-9]+") -replace '\D','')
667 $diskId = 0
668
669 #$partIds = ((wmic partition where DiskIndex=$diskId get Index | Select-String "[0-9]+") -replace '\D','' | %{[int]$_ + 1})
670 $partIds = "select disk $diskId", "list partition" | diskpart |
671 Select-String -Pattern "^ Partition \d" -AllMatches |
672 %{$_.matches} | %{$_.value.replace(" Partition ", "") }
673
674 ForEach ($partId in $partIds) {
675 extendPartition $diskId $partId
676 }
677}
678
679function reportReady()
680{
681 $reportReady = $context['REPORT_READY']
682 $oneGateEndpoint = $context['ONEGATE_ENDPOINT']
683 $vmId = $context['VMID']
684
685 if ($reportReady -and $reportReady.ToUpper() -eq 'YES') {
686 Write-Output 'Report Ready to OneGate'
687
688 if (!$oneGateEndpoint) {
689 Write-Output ' ... Failed: ONEGATE_ENDPOINT not set'
690 return
691 }
692
693 if (!$vmId) {
694 Write-Output ' ... Failed: VMID not set'
695 return
696 }
697
698 try {
699 $tokenPath = $contextLetter + 'token.txt'
700 if (Test-Path $tokenPath) {
701 $token = Get-Content $tokenPath
702 } else {
703 Write-Output " ... Failed: Token file not found"
704 return
705 }
706
707 $body = 'READY = YES'
708 $target= $oneGateEndpoint + '/vm'
709
710 [System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create($target)
711 $webRequest.Timeout = 10000
712 $webRequest.Method = 'PUT'
713 $webRequest.Headers.Add('X-ONEGATE-TOKEN', $token)
714 $webRequest.Headers.Add('X-ONEGATE-VMID', $vmId)
715 $buffer = [System.Text.Encoding]::UTF8.GetBytes($body)
716 $webRequest.ContentLength = $buffer.Length
717 Write-Output $oneGateEndpoint
718 if($oneGateEndpoint -ilike "https://*")
719 { #For reporting on HTTPS OneGateEndpoint
720 Write-Output "... Use HTTPS for OneGateEndpoint report: $oneGateEndpoint"
721 $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
722 [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
723 [System.Net.ServicePointManager]::Expect100Continue = $false
724 [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
725 }
726
727 $requestStream = $webRequest.GetRequestStream()
728 $requestStream.Write($buffer, 0, $buffer.Length)
729 $requestStream.Flush()
730 $requestStream.Close()
731
732 $response = $webRequest.getResponse()
733 if ($response.StatusCode -eq 'OK') {
734 Write-Output ' ... Success'
735 } else {
736 Write-Output ' ... Failed'
737 Write-Output $response.StatusCode
738 }
739 }
740 catch {
741 $errorMessage = $_.Exception.Message
742
743 Write-Output ' ... Failed'
744 Write-Output $errorMessage
745 }
746 }
747}
748
749################################################################################
750# Main
751################################################################################
752
753# Check the working WMI
754if (-Not (Get-WMIObject -ErrorAction SilentlyContinue Win32_Volume)) {
755 Write-Output "WMI not ready, exiting"
756 Stop-Transcript | Out-Null
757 exit 1
758}
759
760Write-Output "Detecting contextualization data"
761Write-Output "- Looking for CONTEXT ISO"
762
763# Get all drives and select only the one that has "CONTEXT" as a label
764$contextDrive = Get-WMIObject Win32_Volume | ? { $_.Label -eq "CONTEXT" }
765
766if ($contextDrive) {
767 Write-Output " ... Found"
768
769 # At this point we can obtain the letter of the contextDrive
770 $contextLetter = $contextDrive.Name
771 Write-Output $contextLetter
772 $contextScriptPath = "C:\" + "context.sh"
773} else {
774 Write-Output " ... Not found"
775 Write-Output "- Looking for VMware tools"
776
777 # Try the VMware API
778 foreach ($pf in ${env:ProgramFiles}, ${env:ProgramFiles(x86)}, ${env:ProgramW6432}) {
779 $vmtoolsd = "${pf}\VMware\VMware Tools\vmtoolsd.exe"
780 if (Test-Path $vmtoolsd) {
781 Write-Output " ... Found in ${vmtoolsd}"
782 break
783 } else {
784 Write-Output " ... Not found in ${vmtoolsd}"
785 }
786 }
787
788 $vmwareContext = ""
789 if (Test-Path $vmtoolsd) {
790 $vmwareContext = & $vmtoolsd --cmd "info-get guestinfo.opennebula.context" | Out-String
791 }
792
793 if ("$vmwareContext" -eq "") {
794 Write-Host "No contextualization data found"
795 Stop-Transcript | Out-Null
796 exit 1
797 }
798
799 [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($vmwareContext)) | Out-File "$env:SystemDrive\context.sh" "UTF8"
800 $contextScriptPath = "C:\context.sh"
801}
802
803# Execute script
804if(Test-Path $contextScriptPath) {
805 $context = getContext $contextScriptPath
806 extendPartitions
807 renameComputer $context
808 addLocalUser $context
809 enableRemoteDesktop
810 enablePing
811 configureNetwork $context
812 runScripts $context $contextLetter
813 reportReady
814}
815
816Stop-Transcript | Out-Null