/
data-server-connect.go
73 lines (60 loc) · 1.41 KB
/
data-server-connect.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
// send data to a remote server using sftp
package main
import (
"fmt"
"log"
//"bytes"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"os"
)
type serverParams struct {
server string
login string
passwd string
}
// copy a localfile to remote sftp server
// TODO: replace localFile by a []string
func Send_data_to_ftp_server(localFile string, dstPath string, param serverParams) error {
config := &ssh.ClientConfig{
User: param.login,
Auth: []ssh.AuthMethod{
ssh.Password(param.passwd),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
connection, err := ssh.Dial("tcp", param.server, config)
if err != nil {
return fmt.Errorf("ssh.dial %s", err)
}
defer connection.Close()
sftp, err := sftp.NewClient(connection)
if err != nil {
log.Fatalf("sftp.newclient %s",err)
}
defer sftp.Close()
// Open the source file
srcFile, err := os.Open(localFile)
if err != nil {
fmt.Println("open src ", err)
}
defer srcFile.Close()
// Create the destination file
dstFile, err := sftp.Create(dstPath)
if err != nil {
fmt.Println("sftp.Create ", err)
}
defer dstFile.Close()
// write to file
if _, err := dstFile.ReadFrom(srcFile); err != nil {
fmt.Println("transf")
fmt.Println(err)
}
return nil
}
func main() {
var params = serverParams{"localhost:22", "xxxxxx", "yyyyyy"}
if err := Send_data_to_ftp_server("datafile.txt", "dstdatafile.txt", params); err != nil {
fmt.Println(err)
}
}