This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
/
communicator.go
244 lines (189 loc) · 5.97 KB
/
communicator.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package powershell
import (
// "bufio"
"fmt"
"bytes"
"github.com/mitchellh/packer/packer"
"io"
// "io/ioutil"
"log"
"path/filepath"
"os/exec"
"os"
"strings"
"container/list"
)
type comm struct {
config *Config
}
type Config struct {
Username string
Password string
RemoteHostIP string
VmName string
Ui packer.Ui
}
// Creates a new packer.Communicator implementation over SSH. This takes
// an already existing TCP connection and SSH configuration.
func New(config *Config) (result *comm, err error) {
// Establish an initial connection and connect
result = &comm{
config: config,
}
return
}
func (c *comm) Start(cmd *packer.RemoteCmd) (err error) {
username := c.config.Username
password := c.config.Password
remoteHost := c.config.RemoteHostIP
// ui := c.config.Ui
var blockBuffer bytes.Buffer
blockBuffer.WriteString("Invoke-Command -scriptblock { ")
blockBuffer.WriteString("$ip4 = '" + remoteHost + "';")
blockBuffer.WriteString("$username = '" + username + "';")
blockBuffer.WriteString("$password = '" + password + "';")
blockBuffer.WriteString("$secstr = New-Object -TypeName System.Security.SecureString;")
blockBuffer.WriteString("$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)};")
blockBuffer.WriteString("$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr;")
// blockBuffer.WriteString("Invoke-Command -ComputerName $ip4 -ScriptBlock { " + cmd.Command + " } -credential $cred")
blockBuffer.WriteString("Invoke-Command -ComputerName $ip4 ")
blockBuffer.WriteString(cmd.Command)
blockBuffer.WriteString(" -credential $cred")
blockBuffer.WriteString("}")
log.Printf("Start blockBuffer: %s", blockBuffer.String())
script := exec.Command("powershell", blockBuffer.String())
script.Stdin = cmd.Stdin
script.Stdout = cmd.Stdout
script.Stderr = cmd.Stderr
log.Printf(fmt.Sprintf("Executing remote script..."))
err = script.Run()
//TODO: remove the next line
// err = nil
return
}
func (c *comm) Upload(string, io.Reader, *os.FileInfo) error {
panic("not implemented for powershell")
}
func (c *comm) UploadDir(dst string, src string, excl []string) error {
info, err := os.Stat(src)
if err != nil {
return err
}
ui := c.config.Ui
if info.IsDir() {
ui.Say(fmt.Sprintf("Uploading folder to the VM '%s' => '%s'...", src, dst))
err := c.uploadFolder(dst, src)
if err != nil {
return err
}
} else {
target_file := filepath.Join(dst,filepath.Base(src))
ui.Say(fmt.Sprintf("Uploading file to the VM '%s' => '%s'...", src, target_file))
err := c.uploadFile(target_file, src)
if err != nil {
return err
}
}
return err
}
func (c *comm) Download(string, io.Writer) error {
panic("not implemented yet")
}
// region private helpers
/*
func (c *comm) executeScriptFileOnVm(scriptPath string) error {
username := c.config.Username
password := c.config.Password
remoteHost := c.config.RemoteHostIP
var blockBuffer bytes.Buffer
blockBuffer.WriteString("Invoke-Command -scriptblock { ")
blockBuffer.WriteString("$ip4 = '" + remoteHost + "';")
blockBuffer.WriteString("$username = '" + username + "';")
blockBuffer.WriteString("$password = '" + password + "';")
blockBuffer.WriteString("$secstr = New-Object -TypeName System.Security.SecureString;")
blockBuffer.WriteString("$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)};")
blockBuffer.WriteString("$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr;")
blockBuffer.WriteString("Invoke-Command -ComputerName $ip4 -filepath " + scriptPath + " -credential $cred")
blockBuffer.WriteString("}")
// ui.Say(fmt.Sprintf("Executing the script on the VM..."))
script := exec.Command("powershell", blockBuffer.String())
var stdout, stderr bytes.Buffer
script.Stdout = &stdout
script.Stderr = &stderr
err := script.Run()
// stdoutString := strings.TrimSpace(stdout.String())
// ui.Say(stdoutString)
return err
}
*/
func (c *comm) uploadFile(dscPath string, srcPath string) error {
dscPath = filepath.FromSlash(dscPath)
srcPath = filepath.FromSlash(srcPath)
vmName := c.config.VmName
var blockBuffer bytes.Buffer
blockBuffer.WriteString("Invoke-Command -scriptblock { ")
blockBuffer.WriteString("Copy-VMFile ")
blockBuffer.WriteString("'" + vmName + "' ")
blockBuffer.WriteString("-SourcePath ")
blockBuffer.WriteString("'" + srcPath + "' ")
blockBuffer.WriteString("-DestinationPath ")
blockBuffer.WriteString("'" + dscPath + "' ")
blockBuffer.WriteString("-CreateFullPath -FileSource Host -Force ")
blockBuffer.WriteString("}")
log.Printf("uploadFile blockBuffer: %s", blockBuffer.String())
script := exec.Command("powershell", blockBuffer.String())
var stdout, stderr bytes.Buffer
script.Stdout = &stdout
script.Stderr = &stderr
err := script.Run()
stderrString := strings.TrimSpace(stdout.String())
stdoutString := strings.TrimSpace(stdout.String())
log.Printf("stdout: %s", stdoutString)
log.Printf("stderr: %s", stderrString)
if _, ok := err.(*exec.ExitError); ok {
err = fmt.Errorf("uploadFile error: %s", stderrString)
}
if len(stderrString) > 0 {
err = fmt.Errorf("uploadFile error: %s", stderrString)
}
return err
}
func (c *comm) uploadFolder(dscPath string, srcPath string ) error {
l := list.New()
type dstSrc struct {
src string
dst string
}
treeWalk := func(path string, info os.FileInfo, prevErr error) error {
// If there was a prior error, return it
if prevErr != nil {
return prevErr
}
// Skip directories
if info.IsDir() {
return nil
}
rel, err := filepath.Rel(srcPath, path)
if err != nil {
return err
}
l.PushBack(
dstSrc{
src: path,
dst: filepath.Join(dscPath,rel),
})
return nil
}
filepath.Walk(srcPath, treeWalk)
var err error
for e := l.Front(); e != nil; e = e.Next() {
// do something with e.Value
pair := e.Value.(dstSrc)
log.Printf("'%s' ==> '%s'\n", pair.src, pair.dst)
err = c.uploadFile(pair.dst, pair.src)
if err != nil {
return err
}
}
return err
}