Пример #1
0
func StartElevated() (err error) {
	// The command gets put into an interpolated string in the PS script,
	// so we need to escape any embedded quotes.
	cmd = strings.Replace(cmd, "\"", "`\"", -1)

	elevatedScript, err := createCommandText()

	if err != nil {
		return err
	}

	// Upload the script which creates and manages the scheduled task
	winrmcp, err := winrmcp.New(fmt.Sprintf("%s:%d", hostname, port), &winrmcp.Config{
		Auth:                  winrmcp.Auth{user, pass},
		OperationTimeout:      time.Second * 60,
		MaxOperationsPerShell: 15,
	})
	tmpFile, err := ioutil.TempFile(os.TempDir(), "packer-elevated-shell.ps1")
	log.Printf("Temp file: %s", tmpFile.Name())

	writer := bufio.NewWriter(tmpFile)
	if _, err := writer.WriteString(elevatedScript); err != nil {
		return fmt.Errorf("Error preparing shell script: %s", err)
	}

	if err := writer.Flush(); err != nil {
		return fmt.Errorf("Error preparing shell script: %s", err)
	}

	tmpFile.Close()

	err = winrmcp.Copy(tmpFile.Name(), "${env:TEMP}/packer-elevated-shell.ps1")

	if err != nil {
		log.Printf("Error copying shell script: %s", err)
		return err
	}

	// Run the script that was uploaded
	command := fmt.Sprintf("powershell -executionpolicy bypass -file \"%s\"", "%TEMP%\\packer-elevated-shell.ps1")
	log.Printf("Running script: %s", command)
	client, err = winrm.NewClientWithParameters(&winrm.Endpoint{Host: hostname, Port: port, HTTPS: false, Insecure: true, CACert: nil}, user, pass, winrm.NewParameters(timeout, "en-US", 153600))
	_, err = client.RunWithInput(command, os.Stdout, os.Stderr, os.Stdin)
	return err
}
Пример #2
0
func main() {

	flag.StringVar(&hostname, "hostname", "localhost", "winrm host")
	flag.StringVar(&user, "username", "vagrant", "winrm admin username")
	flag.StringVar(&pass, "password", "vagrant", "winrm admin password")
	flag.StringVar(&timeout, "timeout", "PT36000S", "winrm timeout")
	flag.IntVar(&port, "port", 5985, "winrm port")
	flag.BoolVar(&elevated, "elevated", false, "run as elevated user?")
	flag.BoolVar(&debug, "debug", false, "output debugging info")
	flag.Parse()

	cmdB, _ := ioutil.ReadAll(os.Stdin)
	cmd = string(cmdB)

	if !debug {
		log.SetOutput(ioutil.Discard)
	}

	log.Printf("Command to run: %s", cmd)
	log.Printf("user to run: %s", user)
	log.Printf("pass to run: %s", pass)
	log.Printf("host to run: %s", hostname)
	log.Printf("port to run: %s", port)
	client, err := winrm.NewClientWithParameters(&winrm.Endpoint{Host: hostname, Port: port, HTTPS: false, Insecure: true, CACert: nil}, user, pass, winrm.NewParameters(timeout, "en-US", 153600))

	if !elevated {
		_, err = client.RunWithInput(winrm.Powershell(cmd), os.Stdout, os.Stderr, os.Stdin)
	} else {
		err = StartElevated()
	}

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	os.Exit(0)
}