-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscp.go
76 lines (61 loc) · 1.36 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
package scp
import (
"golang.org/x/crypto/ssh"
)
const defaultRemoteBinary = "/usr/bin/scp"
type SCP struct {
remoteBinary string
useSFTP bool
cli *ssh.Client
}
type Option func(s *SCP)
func WithSFTP(enable bool) Option {
return func(s *SCP) {
s.useSFTP = enable
}
}
func WithRemoteSShBinaryPath(path string) Option {
return func(s *SCP) {
s.remoteBinary = path
}
}
func New(addr string, cfg *ssh.ClientConfig, ops ...Option) (*SCP, error) {
cli, err := ssh.Dial("tcp", addr, cfg)
if err != nil {
return nil, err
}
res := &SCP{remoteBinary: defaultRemoteBinary, cli: cli}
for _, op := range ops {
op(res)
}
return res, nil
}
func (s *SCP) Close() error {
return s.cli.Close()
}
func (s *SCP) Upload(local string, remote string) error {
ses, err := s.newSession()
if err != nil {
return err
}
defer ses.Close()
return ses.Send(local, remote)
}
func (s *SCP) Download(remote string, local string) error {
return s.DownloadWithHandler(remote, local, localFileHandler)
}
func (s *SCP) DownloadWithHandler(remote string, local string, handler FileHandler) error {
ses, err := s.newSession()
if err != nil {
return err
}
defer ses.Close()
return ses.Recv(remote, local, handler)
}
func (s *SCP) newSession() (Session, error) {
if s.useSFTP {
return NewSFTPSession(s.cli)
} else {
return NewScpSession(s.cli, s.remoteBinary)
}
}