-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathomssh.go
104 lines (88 loc) · 1.83 KB
/
omssh.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
94
95
96
97
98
99
100
101
102
103
104
package omssh
import (
"log"
"net"
"os"
"golang.org/x/crypto/ssh"
)
var (
modes = ssh.TerminalModes{
ssh.ECHO: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
)
// Device : device interface
type Device interface {
SSHConnect(config *ssh.ClientConfig) error
SetupIO()
StartShell() error
Close() error
}
// SSHDevice : ssh device
type SSHDevice struct {
Host string
Port string
client *ssh.Client
session *ssh.Session
}
// NewDevice : new SSH device
func NewDevice(host, port string) Device {
return &SSHDevice{
Host: host,
Port: port,
}
}
// ConfigureSSHClient : configure ssh client
func ConfigureSSHClient(user string, signer ssh.Signer) *ssh.ClientConfig {
return &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
}
// SSHConnect : ssh connect
func (d *SSHDevice) SSHConnect(config *ssh.ClientConfig) error {
target := net.JoinHostPort(d.Host, d.Port)
client, err := ssh.Dial("tcp", target, config)
if err != nil {
return err
}
d.client = client
session, err := client.NewSession()
if err != nil {
return err
}
d.session = session
return nil
}
// SetupIO : set I/O
func (d *SSHDevice) SetupIO() {
d.session.Stdout = os.Stdout
d.session.Stderr = os.Stderr
d.session.Stdin = os.Stdin
}
// StartShell : requests a pseudo terminal and starts the remote shell.
func (d *SSHDevice) StartShell() error {
defer func() {
if err := d.session.Close(); err != nil {
log.Fatal(err)
}
}()
if err := d.session.RequestPty(os.Getenv("TERM"), 25, 80, modes); err != nil {
return err
}
if err := d.session.Shell(); err != nil {
return err
}
if err := d.session.Wait(); err != nil {
return err
}
return nil
}
// Close : close client
func (d *SSHDevice) Close() error {
return d.client.Close()
}