forked from docker/machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
powershell.go
114 lines (89 loc) · 2.39 KB
/
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
package hyperv
import (
"bufio"
"bytes"
"errors"
"os/exec"
"strings"
"fmt"
"github.com/docker/machine/libmachine/log"
)
var powershell string
var (
ErrPowerShellNotFound = errors.New("Powershell was not found in the path")
ErrNotAdministrator = errors.New("Hyper-v commands have to be run as an Administrator")
ErrNotInstalled = errors.New("Hyper-V PowerShell Module is not available")
)
func init() {
powershell, _ = exec.LookPath("powershell.exe")
}
func cmdOut(args ...string) (string, error) {
args = append([]string{"-NoProfile", "-NonInteractive"}, args...)
cmd := exec.Command(powershell, args...)
log.Debugf("[executing ==>] : %v %v", powershell, strings.Join(args, " "))
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
log.Debugf("[stdout =====>] : %s", stdout.String())
log.Debugf("[stderr =====>] : %s", stderr.String())
return stdout.String(), err
}
func cmd(args ...string) error {
_, err := cmdOut(args...)
return err
}
func parseLines(stdout string) []string {
resp := []string{}
s := bufio.NewScanner(strings.NewReader(stdout))
for s.Scan() {
resp = append(resp, s.Text())
}
return resp
}
func hypervAvailable() error {
stdout, err := cmdOut("@(Get-Command Get-VM).ModuleName")
if err != nil {
return err
}
resp := parseLines(stdout)
if resp[0] != "Hyper-V" {
return ErrNotInstalled
}
return nil
}
func isAdministrator() (bool, error) {
hypervAdmin := isHypervAdministrator()
if hypervAdmin {
return true, nil
}
windowsAdmin, err := isWindowsAdministrator()
if err != nil {
return false, err
}
return windowsAdmin, nil
}
func isHypervAdministrator() bool {
stdout, err := cmdOut(`@([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole("Hyper-V Administrators")`)
if err != nil {
log.Debug(err)
return false
}
resp := parseLines(stdout)
return resp[0] == "True"
}
func isWindowsAdministrator() (bool, error) {
stdout, err := cmdOut(`@([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")`)
if err != nil {
return false, err
}
resp := parseLines(stdout)
return resp[0] == "True", nil
}
func quote(text string) string {
return fmt.Sprintf("'%s'", text)
}
func toMb(value int) string {
return fmt.Sprintf("%dMB", value)
}