-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh.go
108 lines (98 loc) · 1.89 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
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"bytes"
// "fmt"
"io/ioutil"
"log"
// "net"
"os"
"os/user"
"strconv"
// "strings"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
// "golang.org/x/crypto/ssh/knownhosts"
)
var (
sshKey = getLocalSSHKey()
usr = getUser()
)
type (
host struct {
Host string
Port int
}
)
func runScript(script string, args []string, host host, sudo bool) (string, string, error) {
hkcb, err := knownhosts.New(getHome()+"/.ssh/known_hosts")
if err != nil {
return "", "", err
}
signer, err := ssh.ParsePrivateKey(sshKey)
if err != nil {
return "", "", err
}
cfg := &ssh.ClientConfig{
User: getUser(),
Auth: []ssh.AuthMethod{
ssh.Password(os.Getenv("SSHPASS")),
ssh.PublicKeys(signer),
// ssh.PublicKeys(signers ...ssh.Signer)
},
HostKeyCallback: hkcb,
}
conn, err := ssh.Dial("tcp", host.String(), cfg)
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
session, err := conn.NewSession()
if err != nil {
log.Fatalln(err)
}
defer session.Close()
stderr := &bytes.Buffer{}
stdout := &bytes.Buffer{}
session.Stdin = bytes.NewReader([]byte(script))
session.Stderr = stderr
session.Stdout = stdout
cmd := "env bash -s --"
if sudo {
cmd = "sudo " + cmd
}
if len(args) > 0 {
for _, arg := range args {
cmd = cmd + " " + arg
}
}
err = session.Run(cmd)
return stdout.String(), stderr.String(), err
}
func getLocalSSHKey() []byte {
u, err := user.Current()
if err != nil {
log.Fatalln(err)
}
b, err := ioutil.ReadFile(u.HomeDir + "/.ssh/id_rsa")
if err != nil {
log.Fatalln(err)
}
return b
}
func getUser() string {
u, err := user.Current()
if err != nil {
log.Fatalln(err)
}
return u.Username
}
func getHome() string {
u, err := user.Current()
if err != nil {
log.Fatalln(err)
}
return u.HomeDir
}
func (h host) String() string {
return h.Host + ":" + strconv.Itoa(h.Port)
}