forked from mefellows/winrm-powershell
/
winrm-powershell.go
158 lines (128 loc) · 4.15 KB
/
winrm-powershell.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package main
import (
"bufio"
"bytes"
"encoding/base64"
"flag"
"fmt"
"github.com/masterzen/winrm/winrm"
"github.com/mitchellh/packer/common/uuid"
"github.com/packer-community/winrmcp/winrmcp"
"io/ioutil"
"log"
"os"
"strings"
"time"
)
var (
hostname string
user string
pass string
cmd string
port int
elevated bool
debug bool
client *winrm.Client
timeout string
)
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)
}
type elevatedShellOptions struct {
Command string
User string
Password string
}
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
}
func createCommandText() (command string, err error) {
// doesn't take well to the flattened env vars
cmd = fmt.Sprintf(`$env:FOO="bar"; %s`, cmd)
log.Printf("Building elevated command for: %s", cmd)
// generate command
var buffer bytes.Buffer
err = elevatedTemplate.Execute(&buffer, elevatedOptions{
User: user,
Password: pass,
TaskDescription: "Packer elevated task",
TaskName: fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID()),
EncodedCommand: powershellEncode([]byte(cmd + "; exit $LASTEXITCODE")),
})
if err != nil {
return "", err
}
log.Printf("ELEVATED SCRIPT: %s\n\n", string(buffer.Bytes()))
return string(buffer.Bytes()), nil
}
func powershellEncode(buffer []byte) string {
// 2 byte chars to make PowerShell happy
wideCmd := ""
for _, b := range buffer {
wideCmd += string(b) + "\x00"
}
// Base64 encode the command
input := []uint8(wideCmd)
return base64.StdEncoding.EncodeToString(input)
}