-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommond.go
88 lines (75 loc) · 1.7 KB
/
commond.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
package gocmd
import (
"fmt"
"os"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
)
// checkClientNewSession
func (gcmd *Gocmd) checkClientNewSession() (*ssh.Session, error) {
if gcmd.Client == nil {
return nil, fmt.Errorf("gocmd-> client is nil...")
}
// new session
return gcmd.Client.NewSession()
}
// Run non output
func (gcmd *Gocmd) Run(cmd string) error {
session, err := gcmd.checkClientNewSession()
if err != nil {
return err
}
defer session.Close()
return session.Run(cmd)
}
// CombinedOutput exec command and has output
func (gcmd *Gocmd) CombinedOutput(cmd string) (string, error) {
session, err := gcmd.checkClientNewSession()
if err != nil {
return "", err
}
defer session.Close()
// exec
buf, err := session.CombinedOutput(cmd)
if err != nil {
return "", err
}
return string(buf), nil
}
// RequestPty terminal pty
func (gcmd *Gocmd) RequestPty(cmd string) error {
session, err := gcmd.checkClientNewSession()
if err != nil {
return err
}
defer session.Close()
// /dev/stdin flag
fd := int(os.Stdin.Fd())
oldState, err := terminal.MakeRaw(fd)
if err != nil {
return err
}
defer terminal.Restore(fd, oldState)
// stdin and stdout
session.Stdout = os.Stdout
session.Stderr = os.Stderr
session.Stdin = os.Stdin
// terminal whidth anf height
termWidth, termHeight, err := terminal.GetSize(fd)
if err != nil {
return err
}
// TerminalModes
modes := ssh.TerminalModes{
// enable echo
ssh.ECHO: 1,
// input speed = 14.4kbaud
ssh.TTY_OP_ISPEED: 14400,
// output speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400,
}
if err := session.RequestPty("xterm-256color", termHeight, termWidth, modes); err != nil {
return err
}
return session.Run(cmd)
}