forked from PortOfPortland/goPSRemoting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
66 lines (50 loc) · 1.99 KB
/
main.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
package goPSRemoting
import (
"os/exec"
"bytes"
"runtime"
"strings"
"errors"
)
func runCommand(args ...string) (string, error) {
cmd := exec.Command(args[0], args[1:]...)
var out bytes.Buffer
var err bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &err
cmd.Run()
// convert err to an error type if there is an error returned
var e error
if err.String() != "" {
e = errors.New(err.String())
}
return strings.TrimRight(out.String(), "\r\n"), e
}
func RunPowershellCommand(username string, password string, server string, command string, usessl bool, usessh bool) (string, error) {
var pscommand string
if runtime.GOOS == "windows" {
pscommand = "powershell.exe"
} else {
pscommand = "pwsh"
}
var winRMPre string
if (usessh == true) {
winRMPre = "$s = New-PSSession -HostName " + server + " -Username " + username + " -SSHTransport"
} else {
winRMPre = "$SecurePassword = '" + password + "' | ConvertTo-SecureString -AsPlainText -Force; $cred = New-Object System.Management.Automation.PSCredential -ArgumentList '" + username + "', $SecurePassword; $s = New-PSSession -ComputerName " + server + " -Credential $cred"
}
var winRMPost string
if runtime.GOOS == "windows" {
winRMPost = "; Invoke-Command -Session $s -Scriptblock { " + command + " }; Remove-PSSession $s"
} else {
winRMPost = "; Invoke-Command -Session $s -Scriptblock { powershell '" + command + "' }; Remove-PSSession $s"
}
var winRMCommand string
if (usessl == true) {
winRMCommand = winRMPre + " -UseSSL" + winRMPost
} else {
winRMCommand = winRMPre + winRMPost
}
out, err := runCommand(pscommand, "-command", winRMCommand)
return out, err
}