-
Notifications
You must be signed in to change notification settings - Fork 0
/
scp.go
278 lines (235 loc) · 5.84 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
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
package storage
import (
"context"
"fmt"
"os"
"os/user"
"path"
"path/filepath"
"strings"
"time"
"github.com/bramvdbogaerde/go-scp"
"github.com/bramvdbogaerde/go-scp/auth"
"golang.org/x/crypto/ssh"
"github.com/itgcloud/gobackup/helper"
"github.com/itgcloud/gobackup/logger"
)
// SSH
//
// host:
// port: 22
// username:
// password:
// timeout: 300
// private_key: ~/.ssh/id_rsa
// passpharase:
type SSH struct {
host string
port string
privateKey string
passpharase string
username string
password string
}
// SCP storage
//
// type: scp
type SCP struct {
Base
SSH
path string
client *ssh.Client
}
func (s *SCP) open() (err error) {
s.viper.SetDefault("port", "22")
s.viper.SetDefault("timeout", 300)
s.viper.SetDefault("private_key", "~/.ssh/id_rsa")
s.host = s.viper.GetString("host")
s.port = s.viper.GetString("port")
s.path = s.viper.GetString("path")
s.username = s.viper.GetString("username")
s.password = s.viper.GetString("password")
s.privateKey = helper.ExplandHome(s.viper.GetString("private_key"))
s.passpharase = s.viper.GetString("passpharase")
if len(s.host) == 0 {
return fmt.Errorf("host is required")
}
if len(s.username) == 0 {
user, err := user.Current()
if err == nil {
s.username = user.Username
} else {
return fmt.Errorf("username is required and it is not able to get current user: %v", err)
}
}
sc := sshConfig{
username: s.username,
password: s.password,
privateKey: s.privateKey,
passpharase: s.passpharase,
}
clientConfig := newSSHClientConfig(sc)
clientConfig.Timeout = s.viper.GetDuration("timeout") * time.Second
sshClient, err := ssh.Dial("tcp", s.host+":"+s.port, &clientConfig)
if err != nil {
return fmt.Errorf("failed to ssh %s@%s -p %s: %v", s.username, s.host, s.port, err)
}
s.client = sshClient
// mkdir
if err := s.run(fmt.Sprintf("mkdir -p %s", s.path)); err != nil {
return err
}
return nil
}
func (s *SCP) run(cmd string) error {
session, err := s.client.NewSession()
if err != nil {
return fmt.Errorf("failed to create session: %v", err)
}
defer session.Close()
if err := session.Run(cmd); err != nil {
return fmt.Errorf("failed to run %s: %v", cmd, err)
}
return nil
}
func (s *SCP) close() {
s.client.Close()
}
func (s *SCP) upload(fileKey string) error {
logger := logger.Tag("SCP")
var fileKeys []string
if len(s.fileKeys) != 0 {
// directory
// 2022.12.04.07.09.47/2022.12.04.07.09.47.tar.xz-000
fileKeys = s.fileKeys
} else {
// file
// 2022.12.04.07.09.25.tar.xz
fileKeys = append(fileKeys, fileKey)
}
for _, key := range fileKeys {
sourcePath := filepath.Join(filepath.Dir(s.archivePath), key)
remotePath := filepath.Join(s.path, key)
// mkdir
if err := s.run(fmt.Sprintf("mkdir -p %s", filepath.Dir(remotePath))); err != nil {
return err
}
// upload file
if err := s.up(sourcePath, remotePath); err != nil {
return err
}
}
logger.Info("Store succeeded")
return nil
}
func (s *SCP) up(localPath, remotePath string) error {
logger := logger.Tag("SCP")
client, err := scp.NewClientBySSH(s.client)
if err != nil {
return err
}
if err := client.Connect(); err != nil {
return err
}
defer client.Close()
file, err := os.Open(localPath)
if err != nil {
return err
}
defer file.Close()
progress := helper.NewProgressBar(logger, file)
if err := client.CopyFile(context.Background(), progress.Reader, remotePath, "0644"); err != nil {
return progress.Errorf("store %s failed: %v", remotePath, err)
}
progress.Done(remotePath)
return nil
}
func (s *SCP) delete(fileKey string) (err error) {
logger := logger.Tag("SCP")
remotePath := path.Join(s.path, fileKey)
logger.Info("-> remove", remotePath)
rmCmd := "rm"
if strings.HasSuffix(fileKey, "/") {
rmCmd = "rmdir"
}
if err := s.run(fmt.Sprintf("%s %s", rmCmd, remotePath)); err != nil {
return err
}
return
}
type sshConfig struct {
username string
password string
privateKey string
passpharase string
}
func newSSHClientConfig(c sshConfig) ssh.ClientConfig {
logger := logger.Tag("SSH")
var auths []ssh.AuthMethod
keyCallBack := ssh.InsecureIgnoreHostKey()
// PrivateKeyWithPassphrase, PrivateKey
logger.Debugf("PrivateKey: %s", c.privateKey)
if len(c.passpharase) != 0 {
if cc, err := auth.PrivateKeyWithPassphrase(
c.username,
[]byte(c.passpharase),
c.privateKey,
keyCallBack,
); err != nil {
logger.Debugf("PrivateKey with passpharase failed: %v", err)
} else {
auths = append(auths, cc.Auth...)
logger.Debug("Added passpharase private key")
}
} else {
if cc, err := auth.PrivateKey(
c.username,
c.privateKey,
keyCallBack,
); err != nil {
logger.Debugf("PrivateKey failed: %v", err)
} else {
auths = append(auths, cc.Auth...)
logger.Debug("Added private key")
}
}
// private key has higher priority than SSH agent here since crypto/ssh will only try the first instance of a particular RFC 4252 method.
// https://pkg.go.dev/golang.org/x/crypto/ssh#ClientConfig
if len(auths) == 0 {
// SshAgent
if cc, err := auth.SshAgent(
c.username,
keyCallBack,
); err != nil {
logger.Debugf("SSH agent failed: %v", err)
} else {
auths = append(auths, cc.Auth...)
logger.Debug("Added SSH agent")
}
}
// PasswordKey
if len(c.password) != 0 {
if cc, err := auth.PasswordKey(
c.username,
c.password,
keyCallBack,
); err != nil {
logger.Debugf("SSH agent failed: %v", err)
} else {
auths = append(auths, cc.Auth...)
logger.Debug("Added password key")
}
}
logger.Debugf("Auths: %#v", auths)
return ssh.ClientConfig{
User: c.username,
Auth: auths,
HostKeyCallback: keyCallBack,
}
}
func (s *SCP) list(parent string) ([]FileItem, error) {
return nil, fmt.Errorf("SCP not support list")
}
func (s *SCP) download(fileKey string) (string, error) {
return "", fmt.Errorf("SCP not support download")
}