runsequence.ps1 14.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# Copyright (c) 2012 University of Utah and the Flux Group.
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}

23 24 25 26 27 28
#
# Script for preparing a vanilla Windows 7 installation for Emulab
#

# First, grab script arguments - I really hate that this must come first
# in a powershell script (before any other executable lines).
Kirk Webb's avatar
Kirk Webb committed
29
param([string]$actionfile, [switch]$debug, [string]$logfile, [switch]$quiet)
30 31 32 33

#
# Constants
#
34
$MAXSLEEP = 1800
35
$DEFLOGFILE="C:\Windows\Temp\runsequence.log"
36 37 38
$FAIL = "fail"
$SUCCESS = "success"
$REG_TYPES = @("String", "Dword")
Kirk Webb's avatar
Kirk Webb committed
39 40
$BASH = "C:\Cygwin\bin\bash.exe"
$BASHARGS = "-l -c"
41
$CMDTMP = "C:\Windows\Temp\_tmpout-basesetup"
42
$VAR_RE = '[a-zA-Z]\w{1,30}'
43
$REGENVPATHKEY = "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
44
$REGENVPATHVAL = "Path"
45 46
$REGENVPATHTYPE = "ExpandString"
$MAXPASSLEN = 32
47
$USERRE = '^\w{4,30}$'
48

49 50 51 52
#
# Global Variables
#
$outlog = $DEFLOGFILE
53
$uservars = @{}
54 55 56 57 58 59 60

#
# Utility functions
#

# Log to $LOGFILE
Function log($msg) {
61
	$time = Get-Date -format g
Kirk Webb's avatar
Kirk Webb committed
62 63 64 65 66
	$outmsg = $time + ": " + $msg
	$outmsg | Out-File -encoding "ASCII" -append $outlog
	if (!$quiet) {
		$outmsg | Out-Host
	}
67 68
}

69 70 71 72 73 74
Function debug($msg) {
	if ($debug) {
		log("DEBUG: $msg")
	}
}

75
Function lograw($msg) {
76
	$msg | Out-File -encoding "ASCII" -append $outlog
77 78
}

79 80 81 82
Function logfilecontents($fname) {
	Get-Content $fname | Out-File -encoding "ASCII" -append $outlog
}

83
Function isNumeric ($x) {
84 85 86
	$x2 = 0
	$isNum = [System.Int32]::TryParse($x, [ref]$x2)
	return $isNum
87 88
}

89 90 91 92 93
Function replace_uservars($cmdstr) {
	$uservars.getenumerator() | % {
		$key = $_.key
		$value = $_.value
		$cmdstr = [regex]::Replace($cmdstr, "%$key%", $value)
94
	}
95
	return $cmdstr
96 97
}

98 99 100 101 102 103 104 105 106
# black magic
Function decode_secstring($secstr) {
	$marshall = [System.Runtime.InteropServices.Marshal]
	$Ptr = $marshall::SecureStringToCoTaskMemUnicode($secstr)
	$result = $marshall::PtrToStringUni($Ptr)
	$marshall::ZeroFreeCoTaskMemUnicode($Ptr)
	return $result 
}

107 108 109 110
#
# Action execution functions
#

111 112 113 114 115 116 117 118
Function log_func($cmdarr) {
	foreach ($logline in $cmdarr) {
		log($logline)
	}

	return $SUCCESS
}

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
Function defvar_func($cmdarr) {
	debug("defvar called with: $cmdarr")

	if (!$cmdarr -or $cmdarr.count -ne 2) {
		log("Must supply variable and value to defvar.")
		return $FAIL
	}
	$myvar, $myval = $cmdarr
	# check variable name for sanity
	if ($myvar -notmatch "^$VAR_RE$") {
		log("Invalid variable token: $myvar")
		return $FAIL
	}

	$uservars.Add($myvar, $myval)
	return $SUCCESS
}

Function readvar_func($cmdarr) {
	debug("readvar called with: $cmdarr")

140
	if (!$cmdarr -or $cmdarr.count -lt 2) {
141 142 143
		log("Must supply variable name and prompt string to readvar.")
		return $FAIL
	}
144
	$myvar, $myprompt, $secure = $cmdarr
145 146 147 148 149 150
	# check variable name for sanity
	if ($myvar -notmatch "^$VAR_RE$") {
		log("Invalid variable token: $myvar")
		return $FAIL
	}

151
	if ($secure) {
152 153
		$myval = decode_secstring(Read-Host -assecurestring $myprompt)
		$verf  = decode_secstring(Read-Host -assecurestring "$myprompt (verify)")
154
		if ($myval -ne $verf) {
155 156 157 158 159 160
			log("ERROR: strings do not match.")
			return $FAIL
		}
	} else {
		$myval = Read-Host $myprompt
	}
161

162
	if (!$myval) {
163
		log("ERROR: No input provided for value.")
164 165 166 167 168 169 170
		return $FAIL
	}

	$uservars.Add($myvar, $myval)
	return $SUCCESS	
}

171 172 173
# Create or set an existing registry value.  Create entire key path as required.
# XXX: Update to return powershell errors
Function addreg_func($cmdarr) {
174
	debug("addreg called with: $cmdarr")
175 176 177 178 179 180 181

	# set / check args
	if (!$cmdarr -or $cmdarr.count -ne 4) {
		log("addreg called with improper argument list")
		return $FAIL
	}
	$path, $vname, $type, $value = $cmdarr
182
	$regpath = "Registry::$path"
183 184 185 186
	if ($REG_TYPES -notcontains $type) {
		log("ERROR: Unknown registry value type specified: $type")
		return $FAIL
	}
187 188
	if (!(Test-Path -IsValid -Path $regpath)) {
		log("Invalid registry key specified: '$path'")
189 190 191 192
		return $FAIL
	}
	
	# Set the value, creating the full key path if necessary
193 194 195
	if (!(Test-Path -Path $regpath)) {
		if (!(New-Item -Path $regpath -Force)) {
			log("Couldn't create registry key path: '$path'")
196 197 198
			return $FAIL
		}
	}
199
	if (!(New-ItemProperty -Path $regpath -Name $vname `
200
	      -PropertyType $type -Value $value -Force)) {
201
		    log("ERROR: Could not set registry value: '$vname' to '$value'")
202 203 204 205 206 207
		    return $FAIL
	    }

	return $SUCCESS
}

Kirk Webb's avatar
Kirk Webb committed
208 209
# XXX: Expands variables in path value.  Need to figure out how to get it to 
#      not do this.
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
Function modpathenv_func($cmdarr) {
	debug("appendpath called with: $cmdarr")

	if ($cmdarr.count -ne 2) {
		log("Must supply a string to append and operation.")
		return $FAIL
	}

	$path,$op = $cmdarr

	if (!(Test-Path -IsValid -Path $path)) {
		log("Invalid path given: $path")
		return $FAIL
	}

	$envobj = Get-ItemProperty -Path $REGENVPATHKEY -Name $REGENVPATHVAL
	$envstr = $envobj.$REGENVPATHVAL
	if ($op -eq "append") {
		$envstr += ";${path}"
	} elseif ($op -eq "prepend") {
		$envstr = "${path};${envstr}"
	} else {
		log("ERROR: Bad operation provided: $op")
		return $FAIL
	}

	New-ItemProperty -Path $REGENVPATHKEY -Name $REGENVPATHVAL `
	    -PropertyType $REGENVPATHTYPE -Value $envstr -Force
	
	return $SUCCESS
}

242
Function reboot_func($cmdarr) {
243 244
	debug("reboot called with: $cmdarr")

245
	if ($cmdarr) {
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
		$force = $cmdarr
	}

	# Reboot ...
	if ($force) {
		"force reboot..." | Out-Host
		#Retart-Computer -Force
	} else {
		"reboot..." | Out-Host
		#Restart-Computer
	}

	return $SUCCESS
}

Function sleep_func($cmdarr) {
262 263
	debug("sleep called with: $cmdarr")

264 265 266
	if ($cmdarr.count -lt 1) {
		log("ERROR: Must supply a time to sleep!")
		return $FAIL
267 268
	}

269 270 271
	$wtime = $cmdarr[0]
	if (!(isNumeric($wtime)) -or `
	    (0 -gt $wtime) -or `
272
	    ($MAXSLEEP -lt $wtime))
273 274 275 276
	{
		log("ERROR: Invalid sleep time: $wtime")
		return $FAIL
	}
277

278 279 280
	# Sleep...
	Start-Sleep -s $wtime
	
281 282 283 284
	return $SUCCESS
}

Function runcmd_func($cmdarr) {
285 286
	debug("runcmd called with: $cmdarr")

287 288 289 290 291
	if ($cmdarr.count -lt 1) {
		log("No command given to run.")
		return $FAIL
	}

292 293 294
	$cmd, $cmdargs, $expret = $cmdarr
	
	# XXX: Implement timeout?
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
	$procargs = @{
		FilePath = $cmd
		ArgumentList = $cmdargs
		RedirectStandardOutput = $CMDTMP
		NoNewWindow = $true
		PassThru = $true
		Wait = $true
	}
	$proc = $null
	try {
		$proc = Start-Process @procargs
	} catch {
		log("ERROR: failed to execute command: $cmd: $_")
		Remove-Item -Path $CMDTMP
		return $FAIL
	}
311
	
312 313
	if ($debug) {
		debug("Command output:")
314
		logfilecontents($CMDTMP)
315
	}
316 317 318
	
	Remove-Item -Path $CMDTMP

319
	# $null is a special varibale in PS - always null!
320
	if ($expret -ne $null -and $proc.ExitCode -ne $expret) {
Kirk Webb's avatar
Kirk Webb committed
321
		log("Command returned unexpected code: " + $proc.ExitCode)
322 323 324
		return $FAIL
	}

325 326 327
	return $SUCCESS
}

Kirk Webb's avatar
Kirk Webb committed
328
# XXX: still doesn't seem to process Cygwin exit codes properly.
329 330 331 332 333 334 335 336 337 338 339 340 341
Function runcyg_func($cmdarr) {
	debug("runcyg called with: $cmdarr")

	if ($cmdarr.count -lt 1) {
		log("No command given to run.")
		return $FAIL
	}

	if (!(Test-Path $BASH)) {
		log("Bash not present - Is Cygwin installed?")
		return $FAIL
	}

342
	# Push the bash args, command + args into place as 
343 344
	# the new argument string and insert bash as the command to run.  
	# Pass this to runcmd_func.
345
	$cmdarr[1] = $BASHARGS + ' "' + $cmdarr[0] + '"'
346 347
	$cmdarr[0] = $BASH
	return runcmd_func($cmdarr)
348 349
}

350
Function getfile_func($cmdarr) {
351 352 353
	debug("getfile called with: $cmdarr")
	$retcode = $FAIL

354 355 356 357 358
	if ($cmdarr.count -lt 2) {
		log("URL and local file must be provided.")
		return $FAIL
	}

359
	$url, $filename = $cmdarr
360 361 362
	if (Test-Path -Path $filename) {
		log("WARNING: Overwriting existing file: $filename")
	}
363
	
364 365 366 367 368 369 370
	try {
		$webclient = New-Object System.Net.WebClient
		$webclient.DownloadFile($url,$filename)
		$retcode = $SUCCESS
	} catch {
		log("Error Trying to download file: $filename: $_")
		$retcode = $FAIL
371
		continue
372 373 374
	}

	return $retcode
375 376
}

377 378 379 380 381 382 383 384 385
Function mkdir_func($cmdarr) {
	debug("mkdir called with: $cmdarr")
	if ($cmdarr.count -ne 1) {
		log("Must specify directory to create and nothing else!")
		return $FAIL
	}

	$dir = $cmdarr[0]
	if (Test-Path -Path $dir) {
386
		if (Test-Path -PathType Leaf -Path $dir) {
387 388 389 390 391
			log("ERROR: Path already exists, but is not a directory!")
			return $FAIL
		} else {
			log("WARNING: Path already exists: $dir")
		}
Kirk Webb's avatar
Kirk Webb committed
392
	} elseif (!(Test-Path -IsValid -Path $dir)) {
393 394 395 396 397 398 399 400 401 402 403 404 405 406
		log("ERROR: Invalid path specified: $dir")
		return $FAIL
	} else {
		try {
			New-Item -ItemType Directory -Path $dir
		} catch {
			log("Error creating new directory: $dir: $_")
			return $FAIL
		}
	}

	return $SUCCESS
}

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
Function waitproc_func($cmdarr) {
	debug("waitproc called with: $cmdarr")

	if ($cmdarr.count -lt 2) {
		log("Must specify process name and timeout.")
		return $FAIL
	}

	$procname, $timeout, $excode = $cmdarr

	$proc = $null
	try {
		$proc = get-process -name $procname
	} catch {
		log("WARNING: Process not found: $procname")
	} 

	if ($proc) {
		if (!($proc.WaitForExit(1000 * $timeout))) {
			log("ERROR: timeout waiting for process: $procname")
			return $FAIL
		}

		if ($excode -and $proc.ExitCode -ne $excode) {
			log("ERROR: process exited with unexpected code: $proc.ExCode")
			return $FAIL
		}
	}
	
	return $SUCCESS

}

Kirk Webb's avatar
Kirk Webb committed
440 441
# XXX: Doesn't support Unix-style line endings or output encodings other than
#      ASCII.
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
Function edfile_func($cmdarr) {
	debug("edfile called with $cmdarr")

	if ($cmdarr.count -ne 3) {
		log("Must specify file to edit, a match pattern, and a replacement pattern.")
		return $FAIL
	}
	$efile, $mpat, $rpat = $cmdarr

	if (!(Test-Path -Path $efile)) {
		log("ERROR: $efile does not exist or can't be accessed.")
		return $FAIL
	}

	$dname = Split-Path -Parent $efile
	$fname = Split-Path -Leaf $efile
	$tmpfile = "${dname}\__${fname}.tmp"

	Get-Content -Path $efile | % {
		$_ -replace $mpat, $rpat
	} | Set-Content -Force -Encoding "ASCII" -Path $tmpfile

	Move-Item -Force -Path $tmpfile -Destination $efile
	return $SUCCESS
}

Kirk Webb's avatar
Kirk Webb committed
468 469
# XXX: Doesn't support Unix-style line endings or output encodings other than
#      ASCII.
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
Function appendfile_func($cmdarr) {
	debug("appendfile called with $cmdarr")

	if ($cmdarr.count -ne 2) {
		log("Must specify file to edit, and a line to append to it.")
		return $FAIL
	}
	$efile, $nline = $cmdarr

	if (!(Test-Path -Path $efile)) {
		log("ERROR: $efile does not exist or can't be accessed.")
		return $FAIL
	}

	if ($nline) {
		Add-Content -Force -Encoding "ASCII" -Path $efile -Value $nline
	}
	return $SUCCESS
}

490 491 492 493 494 495 496 497 498
Function adduser_func($cmdarr) {
	debug("adduser called with $cmdarr")

	if ($cmdarr.count -lt 2) {
		log("Must pass in username and password.")
		return $FAIL
	}
	$user, $pass, $admin = $cmdarr

499
	if ($user -notmatch $USERRE) {
500 501 502 503 504 505 506 507
		log("ERROR: Bad username: $user")
		return $FAIL
	}
	if ($pass.length -gt $MAXPASSLEN) {
		log("ERROR: Password is too long")
		return $FAIL
	}

508
	# This ADSI stuff is just weird.
509 510 511 512 513
	try {
		$objUser = [ADSI]"WinNT://$env:computername/$user,user"
		$objUser.refreshcache() # throws exception if no user.
		log("WARNING: User already exists on local machine: $user")
		return $SUCCESS
514
	} catch {}
515 516 517 518 519 520 521 522 523 524 525 526 527 528

	$objOU = [ADSI]"WinNT://$env:computername"
	$objUser = $objOU.Create("User", $user)
	$objUser.setpassword($pass)
	$objUser.SetInfo()

	if ($admin) {
		$objGrp = [ADSI]"WinNT://$env:computername/Administrators,group"
		$objGrp.add($objUser.Path)
	}

	return $SUCCESS
}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
Function removeuser_func($cmdarr) {
	debug("removeuser called with $cmdarr")

	if ($cmdarr.count -ne 1) {
		log("Must pass in username to remove.")
		return $FAIL
	}
	$user = $cmdarr[0]

	if ($user -notmatch $USERRE) {
		log("ERROR: Bad username: $user")
		return $FAIL
	}

	try {
		$objUser = [ADSI]"WinNT://$env:computername/$user,user"
		$objUser.refreshcache() # throws exception if no user.
	}
	catch {
		log("WARNING: User does not exist on local machine: $user")
		return $SUCCESS
	}

	$objOU = [ADSI]"WinNT://$env:computername"
	$objUser = [ADSI]"WinNT://$env:computername/$user,user"
	$objUser = $objOU.Delete("User", $objUser.name.value)

	return $SUCCESS
}

559
# Main starts here
560 561 562 563 564 565 566 567 568
if ($logfile) {
	if (Test-Path -IsValid -Path $logfile) {
		$outlog = $logfile
	} else {
		Write-Host "ERROR: Can't use logfile specified: $logfile"
		exit 1
	}
}

569 570 571 572 573 574 575 576 577
if ($actionfile -and !(Test-Path -pathtype leaf $actionfile)) {
	log("Specified action sequence file does not exist: $actionfile")
	exit 1;
} else {
	log("Executing action sequence: $actionfile")
}

# Parse and run through the actions in the input sequence
foreach ($cmdline in (Get-Content -Path $actionfile)) {
578
	if (!$cmdline -or ($cmdline.startswith("#"))) {
579 580 581 582 583 584
		continue
	}
	$cmd, $argtoks = $cmdline.split()
	$cmdarr = @()
	if ($argtoks) {
		$cmdargs = [string]::join(" ", $argtoks)
585
		$cmdargs = replace_uservars($cmdargs)
586 587 588
		$cmdarr = [regex]::split($cmdargs, '\s*;;\s*')
	}
	$result = $FAIL
589
	# XXX: Maybe refactor all of this with OOP at some point.
590
	switch($cmd) {
591 592 593
		"log" {
			$result = log_func($cmdarr)
		}
594 595 596 597 598 599
		"addreg" {
			$result = addreg_func($cmdarr)
		}
		"runcmd" {
			$result = runcmd_func($cmdarr)
		}
600 601 602
		"runcyg" {
			$result = runcyg_func($cmdarr)
		}
603 604 605
		"reboot" {
			$result = reboot_func($cmdarr)
		}
606 607 608
		"sleep" {
			$result = sleep_func($cmdarr)
		}
609 610 611
		"getfile" {
			$result = getfile_func($cmdarr)
		}
612 613 614
		"mkdir" {
			$result = mkdir_func($cmdarr)
		}
615 616 617
		"waitproc" {
			$result = waitproc_func($cmdarr)
		}
618 619 620 621 622 623
		"defvar" {
			$result = defvar_func($cmdarr)
		}
		"readvar" {
			$result = readvar_func($cmdarr)
		}
624 625 626 627 628 629 630 631 632
		"edfile" {
			$result = edfile_func($cmdarr)
		}
		"appendfile" {
			$result = appendfile_func($cmdarr)
		}
		"modpathenv" {
			$result = modpathenv_func($cmdarr)
		}
633 634 635
		"adduser" {
			$result = adduser_func($cmdarr)
		}
636 637 638
		"removeuser" {
			$result = removeuser_func($cmdarr)
		}
639 640 641 642 643 644
		default {
			log("WARNING: Skipping unknown action: $cmd")
			$result = $SUCCESS
		}
	}
	if ($result -eq $FAIL) {
Kirk Webb's avatar
Kirk Webb committed
645
		log("ERROR: Action failed: $cmdline")
646 647 648 649
		log("Exiting!")
		exit 1
	}
}
650

Kirk Webb's avatar
Kirk Webb committed
651
log("Action sequence finished successfully." )
652
exit 0