-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
67 lines (55 loc) · 1.56 KB
/
run.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
package windurs
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
"github.com/masterzen/winrm/winrm"
"github.com/mitchellh/packer/common/uuid"
)
func runCmd(client *winrm.Client, stdout, stderr io.Writer, arguments ...string) (int, error) {
shell, err := client.CreateShell()
if err != nil {
return -1, err
}
defer shell.Close()
args := []string{"/c"}
args = append(args, arguments...)
cmd, err := shell.Execute("cmd.exe", args...)
if err != nil {
return -1, err
}
go io.Copy(stdout, cmd.Stdout)
go io.Copy(stderr, cmd.Stderr)
cmd.Wait()
return cmd.ExitCode(), nil
}
func runElevatedCmd(client *winrm.Client, user, pass string, stdout, stderr io.Writer, arguments ...string) (int, error) {
// generate command
command := strings.Join(arguments, " ")
var buffer bytes.Buffer
err := elevatedTemplate.Execute(&buffer, elevatedOptions{
User: user,
Password: pass,
TaskDescription: "Command: " + command,
TaskName: fmt.Sprintf("windurs-%s", uuid.TimeOrderedUUID()),
EncodedCommand: psencode([]byte(command + "; exit $LASTEXITCODE")),
})
if err != nil {
return -1, errors.New(fmt.Sprintf("Couldn't compile elevated command: %v", err))
}
shell, err := client.CreateShell()
if err != nil {
return -1, err
}
defer shell.Close()
cmd, err := shell.Execute("powershell", "-EncodedCommand", psencode(buffer.Bytes()))
if err != nil {
return -1, errors.New(fmt.Sprintf("Couldn't execute elevated command: %v", err))
}
go io.Copy(stdout, cmd.Stdout)
go io.Copy(stderr, cmd.Stderr)
cmd.Wait()
return cmd.ExitCode(), nil
}