/
main.go
108 lines (87 loc) · 2.02 KB
/
main.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
package sftp
import (
"io"
"log"
"os"
"path/filepath"
_sftp "github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
type SFTP struct {
*_sftp.Client
}
type ClientConfig struct {
Username string
Password string
Host string
Port string
}
func NewClient(c *ClientConfig) (*SFTP, error) {
config := &ssh.ClientConfig{
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
User: c.Username,
Auth: []ssh.AuthMethod{ssh.Password(c.Password)},
}
conn, err := ssh.Dial("tcp", c.Host+":"+c.Port, config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
// open an SFTP session over an existing ssh connection.
client, err := _sftp.NewClient(conn)
if err != nil {
log.Fatal(err)
}
srv := &SFTP{client}
return srv, nil
}
// Example
// http://networkbit.ch/golang-sftp-client/
func (s *SFTP) SendFile(localpath, localfilename, remotepath, remotefilename string) (int64, error) {
err := s.MkdirAll(remotepath)
if err != nil {
return 0, err
}
// Create the destination file
dstFile, err := s.Create(filepath.Join(remotepath, remotefilename))
if err != nil {
return 0, err
}
defer dstFile.Close()
// Open the source file
srcFile, err := os.Open(filepath.Join(localpath, localfilename))
if err != nil {
return 0, err
}
defer srcFile.Close()
// copy source file to destination file
bytes, err := io.Copy(dstFile, srcFile)
if err != nil {
return 0, err
}
return bytes, nil
}
func (s *SFTP) GetFile(remotepath, remotefilename, localpath, localfilename string) (int64, error) {
// Create the destination file
dstFile, err := os.Create(localpath + localfilename)
if err != nil {
return 0, err
}
defer dstFile.Close()
// Open the source file
srcFile, err := s.Open(remotepath + remotefilename)
if err != nil {
return 0, err
}
defer srcFile.Close()
// copy source file to destination file
bytes, err := io.Copy(dstFile, srcFile)
if err != nil {
return 0, err
}
// flush in-memory copy
err = dstFile.Sync()
if err != nil {
return bytes, err
}
return bytes, nil
}