forked from bhendo/go-powershell
/
session.go
47 lines (36 loc) · 1.15 KB
/
session.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
// Copyright (c) 2017 Gorillalabs. All rights reserved.
package middleware
import (
"fmt"
"strings"
"github.com/EnclaveData/go-powershell/utils"
"github.com/juju/errors"
)
type session struct {
upstream Middleware
name string
}
func NewSession(upstream Middleware, config *SessionConfig) (Middleware, error) {
asserted, ok := config.Credential.(credential)
if ok {
credentialParamValue, err := asserted.prepare(upstream)
if err != nil {
return nil, errors.Annotate(err, "Could not setup credentials")
}
config.Credential = credentialParamValue
}
name := "goSess" + utils.CreateRandomString(8)
args := strings.Join(config.ToArgs(), " ")
_, _, err := upstream.Execute(fmt.Sprintf("$%s = New-PSSession %s", name, args))
if err != nil {
return nil, errors.Annotate(err, "Could not create new PSSession")
}
return &session{upstream, name}, nil
}
func (s *session) Execute(cmd string) (string, string, error) {
return s.upstream.Execute(fmt.Sprintf("Invoke-Command -Session $%s -Script {%s}", s.name, cmd))
}
func (s *session) Exit() {
s.upstream.Execute(fmt.Sprintf("Disconnect-PSSession -Session $%s", s.name))
s.upstream.Exit()
}