forked from evergreen-ci/evergreen
/
sftp.go
53 lines (40 loc) · 1.16 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
package remote
import (
"fmt"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
// SFTPGateway wraps an SFTP client.
type SFTPGateway struct {
// the sftp client that the gateway is managing
Client *sftp.Client
// the remote host
Host string
// the user we'll access the file as on the remote machine
User string
// the file containing the private key we'll use to connect
Keyfile string
}
// Connect to the other side, and initialize the SFTP client.
func (gateway *SFTPGateway) Init() error {
// configure appropriately
clientConfig, err := createClientConfig(gateway.User, gateway.Keyfile)
if err != nil {
return fmt.Errorf("error configuring ssh: %v", err)
}
// connect to the other side
conn, err := ssh.Dial("tcp", gateway.Host, clientConfig)
if err != nil {
return fmt.Errorf("error connecting to ssh server at `%v`: %v", gateway.Host, err)
}
// create the sftp client
gateway.Client, err = sftp.NewClient(conn)
if err != nil {
return fmt.Errorf("error creating sftp client to `%v`: %v", gateway.Host, err)
}
return nil
}
// Close frees any necessary resources.
func (gateway *SFTPGateway) Close() error {
return gateway.Client.Close()
}