-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathssh.go
80 lines (71 loc) · 1.6 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
package main
import (
"log"
"os"
"runtime/debug"
"time"
"github.com/opensourcez/logger"
"golang.org/x/crypto/ssh"
)
func NewSSHConfig(user, key string, password string, timeout int, ignoreInsecure bool) (cfg *ssh.ClientConfig) {
cfg = new(ssh.ClientConfig)
cfg.User = user
if password != "" {
cfg.Auth = []ssh.AuthMethod{
ssh.Password(password),
}
}
if key != "" {
cfg.Auth = []ssh.AuthMethod{
PrivateKey(key),
}
}
if ignoreInsecure {
cfg.HostKeyCallback = ssh.InsecureIgnoreHostKey()
}
cfg.Timeout = time.Duration(time.Duration(timeout) * time.Second)
return
}
func PrivateKey(path string) ssh.AuthMethod {
key, err := os.ReadFile(path)
if err != nil {
panic(err)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
panic(err)
}
return ssh.PublicKeys(signer)
}
func (c *CMD) SetBuffersAndOpenShell() {
// THE SHELL NEEDS TO BE LAST!
err := c.Session.Shell()
if err != nil {
log.Println(err, string(debug.Stack()))
}
}
func (c *CMD) NewSessionForCommand(conn *ssh.Client) (err error) {
defer func() {
r := recover()
if r != nil {
logger.GenericError(logger.TypeCastRecoverInterface(r)).Log()
}
}()
session, err := conn.NewSession()
if err != nil {
return err
}
c.Session = session
c.Conn = conn
c.StdOut.Buffer = make(chan []byte, 10000000)
c.StdErr.Buffer = make(chan []byte, 10000000)
c.Session.Stdout = &c.StdOut
c.Session.Stderr = &c.StdErr
newSTDin, err := c.Session.StdinPipe()
if err != nil {
c.Session.Close()
return err
}
c.StdIn = newSTDin
return nil
}