forked from dynport/gossh
/
client.go
212 lines (186 loc) · 4.68 KB
/
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package gossh
import (
"bytes"
"code.google.com/p/go.crypto/ssh"
"compress/gzip"
"crypto/sha256"
"encoding/base64"
"fmt"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"time"
)
func New(host, user string) (c *Client) {
return &Client{
User: user,
Host: host,
}
}
type Client struct {
User string
Host string
Port int
Agent net.Conn
password string
Conn *ssh.ClientConn
DebugWriter Writer
ErrorWriter Writer
InfoWriter Writer
}
func (c *Client) Password(user string) (password string, e error) {
if c.password != "" {
return c.password, nil
}
return "", fmt.Errorf("password must be set with SetPassword()")
}
func (c *Client) Close() {
if c.Conn != nil {
c.Conn.Close()
}
if c.Agent != nil {
c.Agent.Close()
}
}
func (client *Client) Attach() error {
options := []string{"-o", "UserKnownHostsFile=/dev/null", "-o", "StrictHostKeyChecking=no"}
if client.User != "" {
options = append(options, "-l", client.User)
}
options = append(options, client.Host)
log.Printf("executing %#v", options)
cmd := exec.Command("/usr/bin/ssh", options...)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Env = os.Environ()
return cmd.Run()
}
func (c *Client) SetPassword(password string) {
c.password = password
}
func (c *Client) Connection() (*ssh.ClientConn, error) {
if c.Conn != nil {
return c.Conn, nil
}
e := c.Connect()
if e != nil {
return nil, e
}
return c.Conn, nil
}
func (c *Client) ConnectWhenNotConnected() (e error) {
if c.Conn != nil {
return nil
}
return c.Connect()
}
func (c *Client) Connect() (e error) {
if c.Port == 0 {
c.Port = 22
}
var auths []ssh.ClientAuth
if c.password != "" {
auths = append(auths, ssh.ClientAuthPassword(c))
}
if c.Agent, e = net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); e == nil {
auths = append(auths, ssh.ClientAuthAgent(ssh.NewAgentClient(c.Agent)))
}
config := &ssh.ClientConfig{
User: c.User,
Auth: auths,
}
c.Conn, e = ssh.Dial("tcp", fmt.Sprintf("%s:%d", c.Host, c.Port), config)
if e != nil {
return e
}
return nil
}
func (c *Client) Execute(s string) (r *Result, e error) {
started := time.Now()
if e = c.ConnectWhenNotConnected(); e != nil {
return nil, e
}
ses, e := c.Conn.NewSession()
if e != nil {
return nil, e
}
defer ses.Close()
tmodes := ssh.TerminalModes{
53: 0, // disable echoing
128: 14400, // input speed = 14.4kbaud
129: 14400, // output speed = 14.4kbaud
}
if e := ses.RequestPty("xterm", 80, 40, tmodes); e != nil {
return nil, e
}
r = &Result{
StdoutBuffer: &LogWriter{LogTo: c.Debug},
StderrBuffer: &LogWriter{LogTo: c.Error},
}
ses.Stdout = r.StdoutBuffer
ses.Stderr = r.StderrBuffer
c.Info(fmt.Sprintf("[EXEC ] %s", s))
r.Error = ses.Run(s)
c.Info(fmt.Sprintf("=> %.06f", time.Now().Sub(started).Seconds()))
if exitError, ok := r.Error.(*ssh.ExitError); ok {
r.ExitStatus = exitError.ExitStatus()
}
r.Runtime = time.Now().Sub(started)
if !r.Success() {
r.Error = fmt.Errorf("process exited with %d", r.ExitStatus)
}
return r, r.Error
}
func (c *Client) Debug(args ...interface{}) {
c.Write(c.DebugWriter, args)
}
func (c *Client) Error(args ...interface{}) {
c.Write(c.ErrorWriter, args)
}
func (c *Client) Info(args ...interface{}) {
c.Write(c.InfoWriter, args)
}
var b64 = base64.StdEncoding
func (c *Client) WriteFile(path, content, owner string, mode int) (res *Result, e error) {
return c.Execute(c.WriteFileCommand(path, content, owner, mode))
}
func (c *Client) WriteFileCommand(path, content, owner string, mode int) string {
buf := &bytes.Buffer{}
zipper := gzip.NewWriter(buf)
zipper.Write([]byte(content))
zipper.Flush()
zipper.Close()
encoded := b64.EncodeToString(buf.Bytes())
hash := sha256.New()
hash.Write([]byte(content))
checksum := fmt.Sprintf("%x", hash.Sum(nil))
tmpPath := "/tmp/gossh." + checksum
dir := filepath.Dir(path)
cmd := fmt.Sprintf("sudo mkdir -p %s && echo %s | base64 -d | gunzip | sudo tee %s", dir, encoded, tmpPath)
if owner != "" {
cmd += " && sudo chown " + owner + " " + tmpPath
}
if mode > 0 {
cmd += fmt.Sprintf(" && sudo chmod %o %s", mode, tmpPath)
}
cmd = cmd + " && sudo mv " + tmpPath + " " + path
return cmd
}
func (c *Client) Write(writer Writer, args []interface{}) {
if writer != nil {
writer(args...)
}
}
// Returns an HTTP client that sends all requests through the SSH connection (aka tunnelling).
func NewHttpClient(sshClient *Client) (httpClient *http.Client, e error) {
if e = sshClient.ConnectWhenNotConnected(); e != nil {
return nil, e
}
httpClient = &http.Client{}
httpClient.Transport = &http.Transport{Proxy: http.ProxyFromEnvironment, Dial: sshClient.Conn.Dial}
return httpClient, nil
}