-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathscript.go
78 lines (74 loc) · 1.54 KB
/
script.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
package main
import (
"code.google.com/p/go.crypto/ssh"
"fmt"
"io"
"io/ioutil"
"os/user"
"strconv"
)
type Host struct {
Name string
User string
Password string
Port int
}
type Script struct {
Name string
Host string
Content string
HideBoundaries bool
}
func (self *Script) Execute(host *Host, out io.Writer) error {
usr, err := user.Current()
if err != nil {
return err
}
if host.User == "" {
host.User = usr.Username
}
cfg := &ssh.ClientConfig{
User: host.User,
}
if host.Password != "" {
cfg.Auth = []ssh.AuthMethod{
ssh.Password(host.Password),
}
} else {
content, err := ioutil.ReadFile(usr.HomeDir + "/.ssh/id_rsa")
if err != nil {
content, err = ioutil.ReadFile(usr.HomeDir + "/.ssh/id_dsa")
if err != nil {
return err
}
}
key, err := ssh.ParsePrivateKey(content)
if err != nil {
return err
}
cfg.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)}
}
client, err := ssh.Dial("tcp", host.Name+":"+strconv.Itoa(host.Port), cfg)
if err != nil {
fmt.Fprintln(out, err.Error())
return err
}
session, err := client.NewSession()
if err != nil {
fmt.Fprintln(out, err.Error())
return err
}
defer session.Close()
session.Stdout = out
session.Stderr = out
if !self.HideBoundaries {
fmt.Fprintln(out, "---------------------- script started ----------------------")
}
if err := session.Run(self.Content); err != nil {
return err
}
if !self.HideBoundaries {
fmt.Fprintln(out, "---------------------- script finished ----------------------")
}
return nil
}