-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssh.go
229 lines (188 loc) · 5.49 KB
/
ssh.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package storm
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
type Ssh struct{}
type AuthenticateArgs struct {
User string
Password string
Host string
Port int
PrivateSshKey string
}
func (s *Ssh) Authenticate(args AuthenticateArgs) (*ssh.Client, error) {
signers := make([]ssh.AuthMethod, 0)
if args.PrivateSshKey == "" && args.Password == "" {
return nil, errors.New("ssh key or password is required")
}
if args.PrivateSshKey != "" {
privateKey, err := ssh.ParsePrivateKey([]byte(args.PrivateSshKey))
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %w", err)
}
signers = append(signers, ssh.PublicKeys(privateKey))
} else {
signers = append(signers, ssh.Password(args.Password))
}
sshConfig := &ssh.ClientConfig{
User: args.User,
Auth: signers,
// TODO: For production, use a more secure host key callback
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// Connect to the SSH server
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", args.Host, args.Port), sshConfig)
if err != nil {
log.Printf("Failed to dial: %v\n", err)
return nil, errors.Join(errors.New("ssh authentication failed"), err)
}
// TODO: close connection when finished
return client, nil
}
// Copy file from local server to remote server
//
// @example
//
// ssh := NewSsh()
// sshClient, err := ssh.Authenticate(AuthenticateArgs{
// Host: "10.211.55.12",
// Port: 22,
// User: "ubuntu",
// Password: "1234567890",
// })
// fmt.Println(err)
// ssh.CopyTo(sshClient, "./from/one/place.yaml", "/to/another.yaml")
func (s *Ssh) CopyTo(client *ssh.Client, source string, destination string) error {
// Create an SFTP client
sftpClient, err := sftp.NewClient(client)
if err != nil {
log.Printf("Failed to create SFTP client: %v\n", err)
return err
}
defer sftpClient.Close()
// Ensure the destination directory exists
destDir := filepath.Dir(destination)
if err := s.CreateDirectory(sftpClient, destDir); err != nil {
return fmt.Errorf("failed to ensure destination directory exists: %w", err)
}
// Open the local file
localFile, err := os.Open(source)
if err != nil {
log.Printf("Failed to open local file: %v\n", err)
return err
}
defer localFile.Close()
// Create the remote file
remoteFile, err := sftpClient.Create(destination)
if err != nil {
log.Printf("Failed to create remote file: %v\n", err)
return err
}
defer remoteFile.Close()
// Copy the file from local to remote
if _, err := localFile.WriteTo(remoteFile); err != nil {
log.Printf("Failed to write file to remote server: %v\n", err)
return err
}
return nil
}
func (s *Ssh) CreateDirectory(sftpClient *sftp.Client, dirPath string) error {
// Check if the directory exists
_, err := sftpClient.Stat(dirPath)
if err == nil {
// Directory exists
return nil
}
if os.IsNotExist(err) {
// Directory does not exist, create it
if err := s.CreateDirectory(sftpClient, filepath.Dir(dirPath)); err != nil {
return err
}
// Create the directory
if err := sftpClient.Mkdir(dirPath); err != nil {
return fmt.Errorf("failed to create directory %s: %w", dirPath, err)
}
} else {
return err
}
return nil
}
// writerFunc is a helper that turns a callback function into an io.Writer.
func writerFunc(callback func(string)) io.Writer {
return writerFuncImpl{callback: callback}
}
type writerFuncImpl struct {
callback func(string)
}
func (w writerFuncImpl) Write(p []byte) (n int, err error) {
trimmedLine := strings.TrimSpace(string(p))
w.callback(string(trimmedLine))
return len(p), nil
}
type ExecuteCommandArgs struct {
Client *ssh.Client
Command string
OutputCallback func(string)
ErrorCallback func(string)
}
func (s *Ssh) ExecuteCommand(args ExecuteCommandArgs) (string, string, error) {
// Create a new SSH session
session, err := args.Client.NewSession()
if err != nil {
return "", "", fmt.Errorf("failed to create SSH session: %w", err)
}
defer session.Close()
// Set up pipes for stdout and stderr
stdoutPipe, err := session.StdoutPipe()
if err != nil {
return "", "", fmt.Errorf("failed to create stdout pipe: %w", err)
}
stderrPipe, err := session.StderrPipe()
if err != nil {
return "", "", fmt.Errorf("failed to create stderr pipe: %w", err)
}
var stdoutBuf, stderrBuf bytes.Buffer
// Create channels to signal completion of stdout and stderr streaming
doneOut := make(chan error)
doneErr := make(chan error)
// Stream stdout
go func() {
multiWriter := io.MultiWriter(&stdoutBuf, writerFunc(args.OutputCallback))
_, err := io.Copy(multiWriter, stdoutPipe)
doneOut <- err
}()
// Stream stderr
go func() {
multiWriter := io.MultiWriter(&stderrBuf, writerFunc(args.ErrorCallback))
_, err := io.Copy(multiWriter, stderrPipe)
doneErr <- err
}()
// Run the command
if err := session.Start(args.Command); err != nil {
return "", "", fmt.Errorf("failed to start command: %w", err)
}
// Wait for stdout and stderr to finish streaming
if err := <-doneOut; err != nil {
return "", "", fmt.Errorf("error while streaming stdout: %w", err)
}
if err := <-doneErr; err != nil {
return "", "", fmt.Errorf("error while streaming stderr: %w", err)
}
// Wait for the session to complete
if err := session.Wait(); err != nil {
return stdoutBuf.String(), stderrBuf.String(), fmt.Errorf("failed to execute command: %w", err)
}
return stdoutBuf.String(), stderrBuf.String(), nil
}
func NewSsh() *Ssh {
return &Ssh{}
}