-
Notifications
You must be signed in to change notification settings - Fork 3
/
ssh.go
96 lines (76 loc) · 1.84 KB
/
ssh.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
package main
import (
"code.google.com/p/go.crypto/ssh"
"code.google.com/p/gopass"
"errors"
"github.com/skynetservices/skynet/log"
)
type SSHConn struct {
host string
user string
client *ssh.ClientConn
env map[string]string
}
// SSH logic
func (c *SSHConn) Connect(host, user string) error {
c.host = host
c.user = user
config := &ssh.ClientConfig{
User: c.user,
Auth: []ssh.ClientAuth{
ssh.ClientAuthPassword(c),
},
}
var err error
c.client, err = ssh.Dial("tcp", c.host, config)
if err != nil {
return err
}
return nil
}
func (c *SSHConn) ExecPath(cmd, path string) (out []byte, err error) {
var session *ssh.Session
session, err = c.client.NewSession()
if err != nil {
log.Fatal("Failed to create session: " + err.Error())
}
defer session.Close()
envVars := ""
if c.env != nil {
for name, value := range c.env {
envVars = envVars + name + "=\"" + value + "\" "
/*
TODO: This should be the proper way to set the environment, but fails for some reason
* Investigate why and possibly send pull-request to maintainer
err = session.Setenv(name, value)
if err != nil {
log.Fatal("Failed to set environment: " + err.Error())
}
*/
}
}
cmd = envVars + cmd
if path != "" {
cmd = "cd " + path + " && " + cmd
}
return session.CombinedOutput(cmd)
}
func (c *SSHConn) Exec(cmd string) (out []byte, err error) {
return c.ExecPath(cmd, "")
}
func (c *SSHConn) Password(user string) (string, error) {
pass, err := gopass.GetPass("Password for " + user + ": ")
if err != nil {
return "", errors.New("Failed to collect password: " + err.Error())
}
return pass, err
}
func (c *SSHConn) Close() {
c.client.Close()
}
func (c *SSHConn) SetEnv(name, value string) {
if c.env == nil {
c.env = make(map[string]string, 5)
}
c.env[name] = value
}