Feature #2395

Provide windows guest contextualization scripts

Added by Tino Vázquez over 7 years ago. Updated about 7 years ago.

Status:ClosedStart date:10/21/2013
Priority:NormalDue date:
Assignee:-% Done:

0%

Category:Context
Target version:Release 4.8
Resolution:fixed Pull request:

Description

Provide means to contextualize (at least networking) Windows based virtual machines. The best way would be to base the contextualization scripts on [1].

Comments in the users list by Martin Alfke

--
We only assign IP address, hostname and enable RDP
Hostname is set as contextualisation variable: HOSTNAME = $name
(We use the VM name as fqdn).

We now only miss setting the DNS according to contextualisation (we need to split the variable into an array).

This is the diff to the one_context.ps1 file:

--- one-context_orig.ps1 2013-10-21 08:43:14.000000000 0200
+
+ one-contextWin8.ps1 2013-10-18 14:35:34.000000000 +0200
@ -4,14 +4,14 @ ##### DETI/IEETA Universidade de Aveiro 2011 ##### #################################################################

-Set-ExecutionPolicy unrestricted -force # not needed if already done once on the VM
+Set-ExecutionPolicy Unrestricted -force # not needed if already done once on the VM
[string]$computerName = "$env:computername"
[string]$ConnectionString = "WinNT://$computerName"

function getContext($file) {
$context = {}
switch -regex -file $file {
- '(.+)="(.+)"' {
+ "(.+)='(.+)'" {
$name,$value = $matches[1..2]
$context[$name] = $value
}
@ -77,13 +77,14 @
function configureNetwork($context) {
$Nics = Get-WMIObject Win32_NetworkAdapterConfiguration | where {$_.IPEnabled -eq "TRUE" -and ($_.MACAddress)}
foreach ($nic in $Nics) {
- [String]$mac = $nic.MACAddress
- [String]$ip = getIp($mac)
- [String]$gw = getGateway($mac)
+ [String]$ip = $context["ETH0_IP"]
+ [String]$gw = $context["ETH0_GATEWAY"]
+ [String]$mask = $context["ETH0_MASK"]
$nic.ReleaseDHCPLease()
- $nic.EnableStatic($ip , "255.255.255.0")
+ $nic.EnableStatic($ip , $mask)
$nic.SetGateways($gw)
- $DNSServers = "193.136.172.20", "193.136.171.21"
+ $DNSServers = "10.175.4.11", "10.175.4.12"
+ # $DNSServers = $context["ETH0_DNS"]
$nic.SetDNSServerSearchOrder($DNSServers)
$nic.SetDynamicDNSRegistration("TRUE")
$nic.SetWINSServer($DNSServers[0], $DNSServers[1])
@ -91,8 +92,10 @@
}
function renameComputer($context) {
- $ComputerInfo = Get-WmiObject Class Win32_ComputerSystem
$ComputerInfo.rename($context["HOSTNAME"])
+ $fullName = $context["HOSTNAME"]
+ $computerName = $fullName.Split(".")[0]
+ $computerInfo = Get-WmiObject -Class Win32_ComputerSystem
+ $computerInfo.rename($computerName)
}
function enableRemoteDesktop()
--

Related issues

Duplicated by Feature #2049: Better Windows contextualization scripts Closed 05/15/2013

History

#1 Updated by Martin Alfke over 7 years ago

These are all the scripts we are using:

1. Windows Autostart script: SetupComplete.cmd

cscript //b e:/startup.vbs

2. Wrapper Script for PowerShell call with super privileges: startup.vbs

Set objShell = CreateObject("Wscript.Shell")
objShell.Run("powershell -NonInteractive -NoProfile -NoLogo -ExecutionPolicy Unrestricted -command E:\one-context.ps1")
Dim objFSO, objFolder
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.CreateFolder("C:\executedVBScript")

3. PowerShell Script which actually does the work: one-context.ps1

#################################################################
##### Windows Powershell Script to configure OpenNebula VMs #####
#####   Created by andremonteiro@ua.pt and tsbatista@ua.pt  #####
#####        DETI/IEETA Universidade de Aveiro 2011         #####
#################################################################
# adopted to Win7/8 - Martin Alfke <tuxmea@gmail.com

Set-ExecutionPolicy Unrestricted -force # not needed if already done once on the VM
[string]$computerName = "$env:computername" 
[string]$ConnectionString = "WinNT://$computerName" 

function getContext($file) {
    $context = @{}
    switch -regex -file $file {
        # proper regexp for context.sh file
        "(.+)='(.+)'" {
            $name,$value = $matches[1..2]
            $context[$name] = $value
        }
    }
    return $context
}

function addLocalUser($context) {
    # Create new user
        $username =  $context["username"]
        $ADSI = [adsi]$ConnectionString

        if(!([ADSI]::Exists("WinNT://$computerName/$username"))) {
           $user = $ADSI.Create("user",$username)
           $user.setPassword($context["password"])
           $user.SetInfo()
        }
        # Already exists, change password
        else{
           $admin = [ADSI]"WinNT://$env:computername/$username" 
           $admin.psbase.invoke("SetPassword", $context["PASSWORD"])
        }

    # Set Password to Never Expires
    $admin = [ADSI]"WinNT://$env:computername/$username" 
    $admin.UserFlags.value = $admin.UserFlags.value -bor 0x10000
    $admin.CommitChanges()

    # Add user to local Administrators
    $groups = "Administrators", "Administradores" 

    foreach ($grp in $groups) {
    if([ADSI]::Exists("WinNT://$computerName/$grp,group")) {
                $group = [ADSI] "WinNT://$computerName/$grp,group" 
                        if([ADSI]::Exists("WinNT://$computerName/$username")) {
                                $group.Add("WinNT://$computerName/$username")
                        }
                }
        }
}

function getIp($mac) {
    $mac = $mac.Replace("-",":")
    $octet = $mac.Split(":")
    [String] $ip = "" 
    $ip += [convert]::toint32($octet[2],16)
    $ip += "."+[convert]::toint32($octet[3],16)
    $ip += "."+[convert]::toint32($octet[4],16)
    $ip += "."+[convert]::toint32($octet[5],16)
    return $ip
}

function getGateway($mac) {
    $octet = $mac.Split(":")
    [String] $ip = "" 
    $ip += [convert]::toint32($octet[2],16)
    $ip += "."+[convert]::toint32($octet[3],16)
    $ip += "."+[convert]::toint32($octet[4],16)
    $ip += ".254" 
    return $ip
}

function configureNetwork($context) {
    $Nics = Get-WMIObject Win32_NetworkAdapterConfiguration | where {$_.IPEnabled -eq "TRUE" -and ($_.MACAddress)}
    foreach ($nic in $Nics) {
        [String]$ip = $context["ETH0_IP"]
        [String]$gw = $context["ETH0_GATEWAY"]
        [String]$mask = $context["ETH0_MASK"]
        $nic.ReleaseDHCPLease()
        $nic.EnableStatic($ip , $mask)
        $nic.SetGateways($gw)
        $DNSServer = $context["ETH0_DNS"]
        $DNSServers = $DNSServer.Split(" ")
        $nic.SetDNSServerSearchOrder($DNSServers)
        $nic.SetDynamicDNSRegistration("TRUE")
        $nic.SetWINSServer($DNSServers[0], $DNSServers[1])
    }
}

function renameComputer($context) {
    $fullName = $context["HOSTNAME"]
    $computerName = $fullName.Split(".")[0]
    $computerInfo = Get-WmiObject -Class Win32_ComputerSystem
    $computerInfo.rename($computerName)
}

function enableRemoteDesktop()
{
    # Windows 7 only - add firewall exception for RDP
    netsh advfirewall Firewall set rule group="Remote Desktop" new enable=yes

    # Enable RDP
    $Terminal = (Get-WmiObject -Class "Win32_TerminalServiceSetting" -Namespace root\cimv2\terminalservices).SetAllowTsConnections(1)
    return $Terminal
}

function enablePing()
{
    #Create firewall manager object
    $FWM=new-object -com hnetcfg.fwmgr

    # Get current profile
    $pro=$fwm.LocalPolicy.CurrentProfile
    $pro.IcmpSettings.AllowInboundEchoRequest=$true
}

function addReadme($context) {
    $username =  $context["USERNAME"]
        Copy-Item E:\README.txt C:\Users\$username\Desktop\README.txt
}

# If folder context doesn't exist create it
if (-not (Test-Path "c:\context\")) {
    New-Item "C:\context\" -type directory
    }

# Execute script
if( -not(Test-Path "c:\context\contextualized") -and (Test-Path "E:\context.sh")) {
    $context = @{}
    $context = getContext('E:\context.sh')
#    addLocalUser($context)
    renameComputer($context)
    enableRemoteDesktop
    enablePing
#    addReadme($context)
#    Start-Sleep -s 30
    configureNetwork($context)
    echo "contextualized" |Out-File ("c:\context\contextualized")
    echo $context |Out-File ("c:\context\contextvar")
    restart-computer -force
}
 ## Restart a second time to ensure network connection
elseif( -not(Test-Path "c:\context\contextualizedNetwork") -and (Test-Path "E:\context.sh"))
{
    $context = @{}
    $context = getContext('E:\context.sh')
    configureNetwork($context)

    #addReadme($context)
    echo "contextualizedNetwork:" |Out-File ("c:\context\contextualizedNetwork")
    $context["ETH0_IP"] |Out-File ("c:\context\contextNetworkVar")
}

#2 Updated by Ruben S. Montero over 7 years ago

  • Duplicated by Feature #2049: Better Windows contextualization scripts added

#3 Updated by Jaime Melis over 7 years ago

  • Target version changed from Release 4.6 to Release 4.8

#4 Updated by Ruben S. Montero about 7 years ago

  • Status changed from New to Closed
  • Resolution set to fixed

Also available in: Atom PDF