-
Notifications
You must be signed in to change notification settings - Fork 1
/
ssh_client.go
93 lines (77 loc) 路 1.94 KB
/
ssh_client.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
package helper
import (
"context"
"fmt"
"os"
"strconv"
"time"
"golang.org/x/crypto/ssh"
)
type SSHClient struct {
client *ssh.Client
}
const CustomSSHPort = 2222
func NewSSHClient(privateKeyStr, serverIP string, port uint16) (*SSHClient, error) {
client, err := connectSSH(privateKeyStr, serverIP, port)
if err != nil {
return nil, err
}
return &SSHClient{client}, nil
}
func connectSSH(privateKeyStr, serverIP string, port uint16) (*ssh.Client, error) {
// Parse the private key
privateKey, err := ssh.ParsePrivateKey([]byte(privateKeyStr))
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %w", err)
}
// Create an SSH client configuration
config := &ssh.ClientConfig{
User: "root",
Auth: []ssh.AuthMethod{
ssh.PublicKeys(privateKey),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 500 * time.Millisecond,
}
// Connect to the SSH server
client, err := ssh.Dial("tcp", serverIP+":"+strconv.Itoa(int(port)), config)
if err != nil {
return nil, fmt.Errorf("cannot connect to SSH server: %w", err)
}
return client, nil
}
func (c *SSHClient) RunCommand(ctx context.Context, command string) error {
// Create a session
session, err := c.client.NewSession()
if err != nil {
return fmt.Errorf("failed to create session: %w", err)
}
defer session.Close()
session.Stdout = os.Stdout
session.Stderr = os.Stderr
// Run the command
err = session.Start(command)
if err != nil {
return fmt.Errorf("failed to run command: %w", err)
}
var waiter = make(chan error)
// Wait for the command to finish or the context to be cancelled
go func() {
sessionError := session.Wait()
waiter <- sessionError
}()
select {
case <-ctx.Done():
session.Signal(ssh.SIGTERM)
fmt.Println("")
return ctx.Err()
case err := <-waiter:
if err != nil {
return fmt.Errorf("failed to wait for session: %w", err)
}
}
return nil
}
func (c *SSHClient) Close() error {
return c.client.Close()
}