-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsftp.go
332 lines (283 loc) · 6.65 KB
/
sftp.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// ftpServer.go
package main
import (
"errors"
"fmt"
"io"
"log"
"os"
"path"
"path/filepath"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
type Client struct {
IP string //IP地址
Username string //用户名
InitDir string
Password string
Port int //端口号
client *sftp.Client //ssh客户端
}
func newClient() *Client {
return nil
return &Client{
IP: "192.168.18.102",
Username: "root",
Password: "jhadmin",
Port: 22,
}
}
func (c *Client) Title() string {
return c.Username + "@" + c.IP
}
func (c *Client) isClose() bool {
if c.client == nil {
return true
}
if _, e := c.client.Getwd(); e != nil {
c.client = nil
return true
}
return false
}
func (c *Client) Link() (*sftp.Client, error) {
if c.isClose() {
client, err := connect(c.Username, c.Password, c.IP, c.Port)
if err != nil {
log.Println("Link:", err)
return nil, err
}
c.client = client
}
return c.client, nil
}
func (c *Client) IsDir(path string) bool {
info, err := c.client.Stat(path)
if err == nil && info.IsDir() {
return true
}
return false
}
func (c *Client) IsFile(path string) bool {
info, err := c.client.Stat(path)
if err == nil && !info.IsDir() {
return true
}
return false
}
func (c *Client) IsExist(path string) bool {
_, err := c.client.Stat(path)
return err == nil
}
func connect(user, password, host string, port int) (*sftp.Client, error) {
var (
auth []ssh.AuthMethod
addr string
clientConfig *ssh.ClientConfig
sshClient *ssh.Client
client *sftp.Client
err error
)
// get auth method
auth = make([]ssh.AuthMethod, 0)
auth = append(auth, ssh.Password(password))
clientConfig = &ssh.ClientConfig{
User: user,
Auth: auth,
Timeout: 2 * time.Second,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// connet to ssh
addr = fmt.Sprintf("%s:%d", host, port)
if sshClient, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
return nil, err
}
// create sftp client
if client, err = sftp.NewClient(sshClient); err != nil {
return nil, err
}
return client, nil
}
func (c *Client) Upload(local string, remote string) (err error) {
info, err := os.Stat(local)
if err != nil {
return errors.New("上传(\"" + local + "\"):" + err.Error())
}
if info.IsDir() {
return c.UploadDir(local, remote)
}
return c.UploadFile(local, remote)
}
func (c *Client) UploadFile(localFile, remote string) error {
info, err := os.Stat(localFile)
if err != nil || info.IsDir() {
return errors.New("sftp: 本地文件不是文件 UploadFile(\"" + localFile + "\") 跳过上传")
}
l, err := os.Open(localFile)
if err != nil {
return errors.New("Upload Open " + localFile + ":" + err.Error())
}
defer l.Close()
var remoteFile, remoteDir string
if remote[len(remote)-1] == '/' {
remoteFile = filepath.ToSlash(filepath.Join(remote, filepath.Base(localFile)))
remoteDir = remote
} else {
remoteFile = remote
remoteDir = filepath.ToSlash(filepath.Dir(remoteFile))
}
log.Println("Upload:", localFile, "-->", remoteFile)
if _, err := c.client.Stat(remoteDir); err != nil {
log.Println("Mkdir:", remoteDir)
c.MkdirAll(remoteDir)
}
r, err := c.client.Create(remoteFile)
if err != nil {
c.client = nil
c.Link()
r, err = c.client.Create(remoteFile)
if err != nil {
return errors.New("Upload Create " + remoteFile + ":" + err.Error())
}
}
_, err = io.Copy(r, l)
return err
}
// UploadDir files without checking diff status
func (c *Client) UploadDir(localDir string, remoteDir string) (err error) {
log.Println("sftp: UploadDir", localDir, "-->", remoteDir)
rootLocal := filepath.Dir(localDir)
if c.IsFile(remoteDir) {
log.Println("sftp: Remove File:", remoteDir)
c.client.Remove(remoteDir)
}
walkFunc := func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Println("err:", err)
return err
}
relSrc, err := filepath.Rel(rootLocal, path)
if err != nil {
return err
}
finalDst := filepath.Join(remoteDir, relSrc)
finalDst = filepath.ToSlash(finalDst)
if info.IsDir() {
if c.IsExist(finalDst) {
return nil
}
err := c.MkdirAll(finalDst)
if err != nil {
log.Println("Mkdir failed:", err)
}
} else {
return c.UploadFile(path, finalDst)
}
return nil
}
return filepath.Walk(localDir, walkFunc)
}
func (c *Client) MkdirAll(dirpath string) error {
parentDir := filepath.ToSlash(filepath.Dir(dirpath))
_, err := c.client.Stat(parentDir)
if err != nil {
if err.Error() == "file does not exist" {
err := c.MkdirAll(parentDir)
if err != nil {
return err
}
} else {
return err
}
}
if c.isClose() {
c.Link()
}
err = c.client.Mkdir(filepath.ToSlash(dirpath))
if err != nil {
return err
}
return nil
}
func (c *Client) Download(remote string, local string) (err error) {
if c.IsDir(remote) {
return c.downloadDir(remote, local)
}
return c.downloadFile(remote, local)
}
// downloadFile a file from the remote server like cp
func (c *Client) downloadFile(remoteFile, local string) error {
if !c.IsFile(remoteFile) {
return errors.New("文件不存在或不是文件, 跳过目录下载 downloadFile(" + remoteFile + ")")
}
localFile := filepath.ToSlash(local)
if err := os.MkdirAll(filepath.Dir(localFile), os.ModePerm); err != nil {
log.Println(err)
return err
}
r, err := c.client.Open(remoteFile)
if err != nil {
return err
}
defer r.Close()
l, err := os.Create(localFile)
if err != nil {
return err
}
defer l.Close()
_, err = io.Copy(l, r)
return err
}
func (c *Client) downloadDir(remote, local string) error {
var localDir, remoteDir string
if !c.IsDir(remote) {
return errors.New("目录不存在或不是目录, 跳过 downloadDir(" + remote + ")")
}
remoteDir = remote
if remote[len(remote)-1] == '/' {
localDir = local
} else {
localDir = path.Join(local, path.Base(remote))
}
walker := c.client.Walk(remoteDir)
for walker.Step() {
if err := walker.Err(); err != nil {
log.Println(err)
continue
}
info := walker.Stat()
relPath, err := filepath.Rel(remoteDir, walker.Path())
if err != nil {
return err
}
localPath := filepath.ToSlash(filepath.Join(localDir, relPath))
localInfo, err := os.Stat(localPath)
if os.IsExist(err) {
if localInfo.IsDir() {
if info.IsDir() {
continue
}
err = os.RemoveAll(localPath)
if err != nil {
return err
}
} else if info.IsDir() {
err = os.Remove(localPath)
if err != nil {
return err
}
}
}
if info.IsDir() {
err = os.MkdirAll(localPath, os.ModePerm)
if err != nil {
return err
}
continue
}
c.downloadFile(walker.Path(), localPath)
}
return nil
}