-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
73 lines (60 loc) · 1.39 KB
/
conn.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
package sync
import (
"fmt"
"log"
"os"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
type SyncClient struct {
SftpClient *sftp.Client
Conn *ssh.Client
Config SyncConfig
}
func NewClient(cfg SyncConfig) (SyncClient, error) {
var c SyncClient
key, err := os.ReadFile(cfg.PrivateKeyPath)
if err != nil {
log.Println("Error reading ssh key")
return c, err
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
log.Println("Error parsing private key")
return c, err
}
sshConfig := &ssh.ClientConfig{
User: cfg.User,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(), // WARN: replace this in prod
}
// Connect to the SSH server
conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), sshConfig)
if err != nil {
fmt.Println("Failed to connect to SSH server:", err)
return c, err
}
// Open SFTP session
sftpClient, err := sftp.NewClient(conn)
if err != nil {
fmt.Println("Failed to open SFTP session:", err)
return c, err
}
return SyncClient{
SftpClient: sftpClient,
Conn: conn,
Config: cfg,
}, nil
}
func (c SyncClient) Close() error {
if err := c.SftpClient.Close(); err != nil {
log.Println("Failed to close sftp connection: ", err)
}
if err := c.Conn.Close(); err != nil {
log.Println("Failed to close ssh connection: ", err)
return err
}
return nil
}