-
Notifications
You must be signed in to change notification settings - Fork 0
/
scp.go
219 lines (185 loc) · 4.45 KB
/
scp.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
/*
This package provides simple SCP client for copying data recursively to remote server. It's built
on top of x/crypto/ssh
*/
package scp // import "github.com/aedavelli/go-scp"
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/kballard/go-shellquote"
"golang.org/x/crypto/ssh"
)
type Client struct {
SshClient *ssh.Client
PreseveTimes bool
Quiet bool
}
// Form send command based on client configuration
func (c *Client) getSendCommand(dst string) string {
cmd := "scp -rt"
if c.PreseveTimes {
cmd += "p"
}
if c.Quiet {
cmd += "q"
}
return fmt.Sprintf("%s %s", cmd, shellquote.Join(dst))
}
// Send the files dst directory on remote side. The paths can be regular files or directories.
func (c *Client) Send(dst string, paths ...string) error {
// Create an SSH session
session, err := c.SshClient.NewSession()
if err != nil {
return errors.New("Failed to create SSH session: " + err.Error())
}
defer session.Close()
// Setup Input strem
w, err := session.StdinPipe()
if err != nil {
return errors.New("Unable to get stdin: " + err.Error())
}
defer w.Close()
// Setup Output strem
r, err := session.StdoutPipe()
if err != nil {
return errors.New("Unable to get Stdout: " + err.Error())
}
fmt.Println(c.getSendCommand(dst))
if err := session.Start(c.getSendCommand(dst)); err != nil {
return errors.New("Failed to start: " + err.Error())
}
errors := make(chan error)
go func() {
errors <- session.Wait()
}()
for _, p := range paths {
if err := c.walkAndSend(w, p); err != nil {
return err
}
}
w.Close()
io.Copy(os.Stdout, r)
<-errors
return nil
}
// send regular file
func (c *Client) sendRegularFile(w io.Writer, path string, fi os.FileInfo) error {
if c.PreseveTimes {
_, err := fmt.Fprintf(w, "T%d 0 %d 0\n", fi.ModTime().Unix(), time.Now().Unix())
if err != nil {
return err
}
}
_, err := fmt.Fprintf(w, "C%#o %d %s\n", fi.Mode().Perm(), fi.Size(), fi.Name())
if err != nil {
return errors.New("Copy failed: " + err.Error())
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
io.Copy(w, f)
fmt.Fprint(w, "\x00")
if !c.Quiet {
fmt.Println("Copied: ", path)
}
return nil
}
// Walk and Send directory
func (c *Client) walkAndSend(w io.Writer, src string) error {
cleanedPath := filepath.Clean(src)
fi, err := os.Stat(cleanedPath)
if err != nil {
return err
}
if fi.Mode().IsRegular() {
if err = c.sendRegularFile(w, cleanedPath, fi); err != nil {
return err
}
}
// It is a directory need to walk and copy
dirStack := strings.Split(cleanedPath, fmt.Sprintf("%c", os.PathSeparator))
startStackLen := len(dirStack)
dirStack = dirStack[:startStackLen-1]
startStackLen--
err = filepath.Walk(cleanedPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
tmpDirStack := strings.Split(path, fmt.Sprintf("%c", os.PathSeparator))
i, di, ci := 0, 0, 0
dl, cl := len(dirStack), len(tmpDirStack)
if info.Mode().IsRegular() {
tmpDirStack = tmpDirStack[:cl-1]
cl--
}
for i = 0; i < dl && i < cl; i++ {
if dirStack[i] != tmpDirStack[i] {
break
}
di++
ci++
}
for di < dl { // We need to pop
fmt.Fprintf(w, "E\n")
di++
}
for ci < cl { // We need to push
if c.PreseveTimes {
_, err := fmt.Fprintf(w, "T%d 0 %d 0\n", info.ModTime().Unix(), time.Now().Unix())
if err != nil {
return err
}
}
fmt.Fprintf(w, "D%#o 0 %s\n", info.Mode().Perm(), tmpDirStack[ci])
ci++
}
dirStack = tmpDirStack
if info.Mode().IsRegular() {
if err = c.sendRegularFile(w, path, info); err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
dl := len(dirStack) - 1
for dl >= startStackLen {
fmt.Fprintf(w, "E\n")
dl--
}
return nil
}
// Creates a new SCP client. Use this only with trusted servers, as the host key verification
// is bypassed. It enables preserve time stamps
func NewDumbClient(username, password, server string) (*Client, error) {
client, err := ssh.Dial("tcp", server, &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
if err != nil {
return nil, err
}
return &Client{
SshClient: client,
PreseveTimes: true,
}, nil
}
// Creates a new SCP client form ssh.Client and preserve time stamps
func NewClient(c *ssh.Client, pt bool) *Client {
return &Client{
SshClient: c,
PreseveTimes: pt,
}
}