-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsshclient.go
67 lines (58 loc) · 1.27 KB
/
sshclient.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
package sshts
import (
"fmt"
"os"
"golang.org/x/crypto/ssh"
)
type SSHConn struct {
sshConf *ssh.ClientConfig
sshClient *ssh.Client
serverAddr string
status int64
}
// New("user", "/home/user/.ssh/id_rsa", "1.1.1.1:22")
func New(user, rsaKeyfile, serverAddr string) (*SSHConn, error) {
key, err := os.ReadFile(rsaKeyfile)
if err != nil {
return nil, fmt.Errorf("unable to read private key: %v", err)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, fmt.Errorf("unable to parse private key: %v", err)
}
sshConf := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
return &SSHConn{
sshConf: sshConf,
serverAddr: serverAddr,
status: 0,
sshClient: nil,
}, nil
}
func (s *SSHConn) Connect() error {
client, err := ssh.Dial("tcp", s.serverAddr, s.sshConf)
if err != nil {
return fmt.Errorf("error connect to ssh server: %v", err)
}
s.sshClient = client
s.status = 1
return nil
}
func (s *SSHConn) GetStatus() int64 {
return s.status
}
func (s *SSHConn) Close() error {
if s.sshClient != nil {
err := s.sshClient.Close()
if err != nil {
return fmt.Errorf("error close ssh connection: %v", err)
}
}
s.status = 0
return nil
}