-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh.go
More file actions
107 lines (89 loc) · 2.31 KB
/
ssh.go
File metadata and controls
107 lines (89 loc) · 2.31 KB
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
package main
import (
"context"
"fmt"
"net"
"os"
"time"
"golang.org/x/crypto/ssh"
)
// SSHExecutor runs commands on a remote host via SSH.
type SSHExecutor struct {
client *ssh.Client
}
func NewSSHExecutor(host, user, keyFile, password string, port int) (*SSHExecutor, error) {
if port == 0 {
port = 22
}
var authMethods []ssh.AuthMethod
// Key-based auth
if keyFile != "" {
keyData, err := os.ReadFile(keyFile)
if err != nil {
return nil, fmt.Errorf("reading SSH key: %w", err)
}
signer, err := ssh.ParsePrivateKey(keyData)
if err != nil {
return nil, fmt.Errorf("parsing SSH key: %w", err)
}
authMethods = append(authMethods, ssh.PublicKeys(signer))
}
// Password auth
if password != "" {
authMethods = append(authMethods, ssh.Password(password))
}
if len(authMethods) == 0 {
return nil, fmt.Errorf("no SSH auth method provided: set key_file or password")
}
config := &ssh.ClientConfig{
User: user,
Auth: authMethods,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 10 * time.Second,
}
addr := net.JoinHostPort(host, fmt.Sprintf("%d", port))
client, err := ssh.Dial("tcp", addr, config)
if err != nil {
return nil, fmt.Errorf("SSH connection to %s failed: %w", addr, err)
}
return &SSHExecutor{client: client}, nil
}
func (e *SSHExecutor) Exec(command string, timeout int) (string, error) {
session, err := e.client.NewSession()
if err != nil {
return "", fmt.Errorf("creating SSH session: %w", err)
}
defer session.Close()
if timeout > 0 {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
done := make(chan struct{})
var output []byte
var runErr error
go func() {
output, runErr = session.CombinedOutput(command)
close(done)
}()
select {
case <-done:
if runErr != nil {
return string(output) + "\nError: " + runErr.Error(), nil
}
return string(output), nil
case <-ctx.Done():
session.Signal(ssh.SIGKILL)
return "", fmt.Errorf("command timed out after %d seconds", timeout)
}
}
output, err := session.CombinedOutput(command)
if err != nil {
return string(output) + "\nError: " + err.Error(), nil
}
return string(output), nil
}
func (e *SSHExecutor) Close() error {
if e.client != nil {
return e.client.Close()
}
return nil
}