-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathssh_client.go
More file actions
68 lines (59 loc) · 1.43 KB
/
ssh_client.go
File metadata and controls
68 lines (59 loc) · 1.43 KB
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
package sshkeymanager
import (
"bytes"
"log"
"os"
"strings"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
func NewClient(host, port, user string, config *ssh.ClientConfig) (*Client, error) {
client := Client{host: host, port: port, SSHConfig: config}
if user != "root" {
client.useSudo = true
client.user = user
config.User = user
}
err := client.Connect()
if err != nil {
return nil, err
}
return &client, nil
}
func (c *Client) Prefix() string {
if c.useSudo {
return "sudo "
} else {
return ""
}
}
func (c *Client) Connect() error {
client, err := ssh.Dial("tcp", c.host+":"+c.port, c.SSHConfig)
if err != nil {
return err
}
c.SSHClient = client
return nil
}
func (c *Client) Execute(command string) (string, string, error) {
session, err := c.SSHClient.NewSession()
if err != nil {
return "", "", errors.Wrap(err, "ssh NewSession")
}
defer session.Close()
var so, se bytes.Buffer
session.Stdout = &so
session.Stderr = &se
err = session.Run(c.Prefix() + command)
if err != nil {
log.Println("execute:", command, "result:", so.String(), se.String(), "error:", err)
return strings.TrimSuffix(so.String(), "\n"), strings.TrimSuffix(se.String(), "\n"), err
}
if os.Getenv("DEBUG") == "YES" {
log.Println("execute:", command)
log.Println("result:")
log.Println(so.String())
log.Println(se.String())
}
return strings.TrimSuffix(so.String(), "\n"), strings.TrimSuffix(se.String(), "\n"), nil
}