/
sshclient.go
61 lines (47 loc) · 1.12 KB
/
sshclient.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
package sshclient
import (
"bytes"
"golang.org/x/crypto/ssh"
"io/ioutil"
"time"
)
func RunOneCommand(host string, command string, timeout int, key ssh.Signer) (string, error) {
cuser := "root"
config := &ssh.ClientConfig{
User: cuser,
Timeout: time.Duration(timeout) * time.Second,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(key),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", host+":22", config)
if err != nil {
return "Failed to dial: " + err.Error(), err
}
session, err := client.NewSession()
if err != nil {
return "Failed to create session", err
}
defer session.Close()
var stdoutBuf bytes.Buffer
var stderrBuf bytes.Buffer
session.Stdout = &stdoutBuf
session.Stderr = &stderrBuf
if err = session.Run(command); err != nil {
return stderrBuf.String(), err
}
return stdoutBuf.String(), nil
}
func GetKeyFile(encfile string) (key ssh.Signer, err error) {
file := "/root/.ssh/" + encfile //id_rsa"
buf, err := ioutil.ReadFile(file)
if err != nil {
return
}
key, err = ssh.ParsePrivateKey(buf)
if err != nil {
return
}
return
}