forked from mrgleam/easyssh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
easyssh.go
228 lines (194 loc) · 5.91 KB
/
easyssh.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Package easyssh provides a simple implementation of some SSH protocol
// features in Go. You can simply run a command on a remote server or get a file
// even simpler than native console SSH client. You don't need to think about
// Dials, sessions, defers, or public keys... Let easyssh think about it!
package easyssh
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/user"
"path/filepath"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// Contains main authority information.
// User field should be a name of user on remote server (ex. john in ssh john@example.com).
// Server field should be a remote machine address (ex. example.com in ssh john@example.com)
// Key is a path to private key on your local machine.
// Port is SSH server port on remote machine.
// Note: easyssh looking for private key in user's home directory (ex. /home/john + Key).
// Then ensure your Key begins from '/' (ex. /.ssh/id_rsa)
type MakeConfig struct {
User string
Server string
Key string
Port string
Password string
}
// returns ssh.Signer from user you running app home path + cutted key path.
// (ex. pubkey,err := getKeyFile("/.ssh/id_rsa") )
func getKeyFile(keypath string) (ssh.Signer, error) {
usr, err := user.Current()
if err != nil {
return nil, err
}
file := usr.HomeDir + keypath
buf, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
pubkey, err := ssh.ParsePrivateKey(buf)
if err != nil {
return nil, err
}
return pubkey, nil
}
// connects to remote server using MakeConfig struct and returns *ssh.Session
func (ssh_conf *MakeConfig) connect() (*ssh.Session, error) {
// auths holds the detected ssh auth methods
auths := []ssh.AuthMethod{}
// figure out what auths are requested, what is supported
if ssh_conf.Password != "" {
auths = append(auths, ssh.Password(ssh_conf.Password))
}
if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers))
defer sshAgent.Close()
}
if pubkey, err := getKeyFile(ssh_conf.Key); err == nil {
auths = append(auths, ssh.PublicKeys(pubkey))
}
config := &ssh.ClientConfig{
User: ssh_conf.User,
Auth: auths,
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
client, err := ssh.Dial("tcp", ssh_conf.Server+":"+ssh_conf.Port, config)
if err != nil {
return nil, err
}
session, err := client.NewSession()
if err != nil {
return nil, err
}
return session, nil
}
// Stream returns one channel that combines the stdout and stderr of the command
// as it is run on the remote machine, and another that sends true when the
// command is done. The sessions and channels will then be closed.
func (ssh_conf *MakeConfig) Stream(command string, timeout int) (stdout chan string, stderr chan string, done chan bool, err error) {
// connect to remote host
session, err := ssh_conf.connect()
if err != nil {
return stdout, stderr, done, err
}
// connect to both outputs (they are of type io.Reader)
outReader, err := session.StdoutPipe()
if err != nil {
return stdout, stderr, done, err
}
errReader, err := session.StderrPipe()
if err != nil {
return stdout, stderr, done, err
}
// combine outputs, create a line-by-line scanner
stdoutReader := io.MultiReader(outReader)
stderrReader := io.MultiReader(errReader)
err = session.Start(command)
stdoutScanner := bufio.NewScanner(stdoutReader)
stderrScanner := bufio.NewScanner(stderrReader)
// continuously send the command's output over the channel
stdoutChan := make(chan string)
stderrChan := make(chan string)
done = make(chan bool)
go func(stdoutScanner, stderrScanner *bufio.Scanner, stdoutChan, stderrChan chan string, done chan bool) {
defer close(stdoutChan)
defer close(stderrChan)
defer close(done)
timeoutChan := time.After(time.Duration(timeout) * time.Second)
res := make(chan bool, 1)
go func() {
for stdoutScanner.Scan() {
stdoutChan <- stdoutScanner.Text()
}
for stderrScanner.Scan() {
stderrChan <- stderrScanner.Text()
}
// close all of our open resources
res <- true
}()
select {
case <-res:
stdoutChan <- ""
stderrChan <- ""
done <- true
case <-timeoutChan:
stdoutChan <- ""
stderrChan <- "Run Command Timeout!"
done <- false
}
session.Close()
}(stdoutScanner, stderrScanner, stdoutChan, stderrChan, done)
return stdoutChan, stderrChan, done, err
}
// Runs command on remote machine and returns its stdout as a string
func (ssh_conf *MakeConfig) Run(command string, timeout int) (outStr string, errStr string, isTimeout bool, err error) {
stdoutChan, stderrChan, doneChan, err := ssh_conf.Stream(command, timeout)
if err != nil {
return outStr, errStr, isTimeout, err
}
// read from the output channel until the done signal is passed
stillGoing := true
for stillGoing {
select {
case isTimeout = <-doneChan:
stillGoing = false
case outline := <-stdoutChan:
outStr += outline + "\n"
case errline := <-stderrChan:
errStr += errline + "\n"
}
}
// return the concatenation of all signals from the output channel
return outStr, errStr, isTimeout, err
}
// Scp uploads sourceFile to remote machine like native scp console app.
func (ssh_conf *MakeConfig) Scp(sourceFile string, etargetFile string) error {
session, err := ssh_conf.connect()
if err != nil {
return err
}
defer session.Close()
targetFile := filepath.Base(etargetFile)
src, srcErr := os.Open(sourceFile)
if srcErr != nil {
return srcErr
}
srcStat, statErr := src.Stat()
if statErr != nil {
return statErr
}
go func() {
w, _ := session.StdinPipe()
fmt.Fprintln(w, "C0644", srcStat.Size(), targetFile)
if srcStat.Size() > 0 {
io.Copy(w, src)
fmt.Fprint(w, "\x00")
w.Close()
} else {
fmt.Fprint(w, "\x00")
w.Close()
}
}()
if err := session.Run(fmt.Sprintf("scp -tr %s", etargetFile)); err != nil {
return err
}
return nil
}