/
send.go
222 lines (208 loc) · 6.21 KB
/
send.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"log/syslog"
"os"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
var (
conf = flag.String("conf", "", "json config location")
cmd = flag.String("c", "", "specify command")
user = flag.String("user", "", "username")
keyFile = flag.String("key", "", "path to key if not default")
hosts = flag.String("hosts", "", "multiple hosts inside quotes")
fromFile = flag.String("file", "", "specify a file separated by newline")
logPath = flag.String("log", "", "for flat file: /path/name.ext, syslog: `PROTO@ADDR:PORT`")
uniq = flag.String("uniq", "_SEND_", "a unique string")
timeout = flag.Int("timeout", 90, "timeout in seconds")
port = flag.Int("port", 22, "port number")
fatal = flag.Bool("fatal", false, "return failed exit codes")
ordered = flag.Bool("ordered", false, "run in order instead of async")
usr string
dest string
cfg Config
)
// Config gets datafilled by either 1. cli args, or 2. a specified json config
type Config struct {
User string `json:"user"`
Key string `json:"key"`
LogPath string `json:"logpath"`
Hosts string `json:"hosts"`
Command string `json:"cmd"`
FromFile string `json:"fromfile"`
Timeout int `json:"timeout"`
Port int `json:"port"`
Fatal bool `json:"fatal"`
Ordered bool `json:"ordered"`
}
func main() {
response := make(chan string)
// parse the flags before anything
flag.Parse()
// if automated using a json config
if *conf != "" {
configFromJSON(*conf)
} else {
configFromArgs(&cfg)
}
if strings.Contains(cfg.LogPath, "@") {
addr := strings.Split(cfg.LogPath, "@")
logger, e := syslog.Dial(addr[0], addr[1],
syslog.LOG_WARNING|syslog.LOG_DAEMON, *uniq) // anything else here
check(e)
log.SetOutput(logger)
} else {
// otherwise user supplied a path (or fat fingered something)
// -log /path/to/flatFile.txt
logger, e := os.OpenFile(cfg.LogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
check(e)
defer logger.Close()
log.SetOutput(logger)
}
// log for records should this be DEBUG?
log.Printf("%v -> using the following config | %v", *uniq, cfg)
// hosts should be supplied like -host "host1 user2@host2 roooooot@topCkid"
for _, host := range strings.Split(cfg.Hosts, " ") {
// if they added a username@host, disregard c.User
if strings.Contains(host, "@") {
usr = strings.Split(host, "@")[0]
dest = strings.Split(host, "@")[1]
} else {
usr = cfg.User
dest = host
}
if cfg.Ordered {
response := sendCmd(&cfg, usr, dest)
fmt.Println(response)
} else {
go func(dest, usr string) {
response <- sendCmd(&cfg, usr, dest)
}(dest, usr)
}
}
if !cfg.Ordered {
for i := 0; i < len(strings.Split(cfg.Hosts, " ")); i++ {
select {
case results := <-response:
fmt.Println(results)
case <-time.After(time.Duration(cfg.Timeout) * time.Second):
log.Printf("%v: TIMEOUT -> %v timed out; timeout: %v", *uniq, dest, cfg.Timeout)
return
}
}
}
}
func sendCmd(c *Config, usr, dest string) string {
// init some vars to hold our stdour/err later
var stdout bytes.Buffer
var stderr bytes.Buffer
// create an ssh conf using our loadKey function / user key
sshConf := &ssh.ClientConfig{
User: cfg.User,
Auth: []ssh.AuthMethod{loadKey(c.Key)}, HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%v", dest, cfg.Port), sshConf)
if err != nil {
connErrMsg := fmt.Sprintf("error connecting to %v on port %v as %v: %v", dest, cfg.Port, usr, err)
fmt.Println(connErrMsg)
log.Println(*uniq, connErrMsg)
}
session, sessionErr := conn.NewSession()
if sessionErr != nil {
// TODO: need to add silent mode for procs running in BG
fmt.Printf("session error! with %v on %v as user %v\n", dest, cfg.Port, usr)
log.Printf("%v: session error! with %v on %v as user %v\n", *uniq, dest, cfg.Port, usr)
}
defer session.Close()
// store the results of the command that was sent
session.Stdout = &stdout
session.Stderr = &stderr
// log what we did for our records
log.Printf("%v: RUNNING -> %v on %v as user %v", *uniq, cfg.Command, dest, usr)
session.Run(cfg.Command)
// if there was stderr, something went wrong
if len(stderr.String()) > 0 {
// whether we care or not is determined here. If set to fatal,
// any stderr returned will terminate the program and return failed (os exit 1)
if cfg.Fatal {
fmt.Printf("Cant recover, fatal set to true. host affected: %v ->%v\n", dest, stderr.String())
log.Printf("Cant recover, fatal set to true. host affected: %v ->%v", dest, stderr.String())
os.Exit(1)
}
// otherwise tell us what failed and carry on with work
log.Printf("%v: FAILED -> command failed on %v: %v", *uniq, dest, stderr.String())
return fmt.Sprintf("%v\n%v", dest, stderr.String())
}
return fmt.Sprintf("%v\n%v", dest, stdout.String())
}
func configFromJSON(conf string) {
contents, e := ioutil.ReadFile(conf)
check(e)
// this is where we unmarshal the contents into cfg (Config)
e = json.Unmarshal(contents, &cfg)
check(e)
}
func configFromArgs(c *Config) {
defaultDir, e := os.UserHomeDir()
check(e)
c.Port = *port
c.Timeout = *timeout
c.Ordered = *ordered
c.Fatal = *fatal
if *user == "" {
c.User = strings.Split(defaultDir, "/")[2]
} else {
c.User = *user
}
if *keyFile == "" {
// we could probably loop over an array and concat the algo name to `id_`
// for now we only support RSA
c.Key = fmt.Sprintf("%v/.ssh/id_rsa", defaultDir)
} else {
c.Key = *keyFile
}
if *logPath == "" {
c.LogPath = "send.log"
} else {
c.LogPath = *logPath
}
if *hosts == "" {
log.Printf("no hosts were provided in cli args! --> %v", *hosts)
getHelp()
} else {
c.Hosts = *hosts
}
if *cmd != "" {
c.Command = *cmd
} else {
c.Command = "whoami;hostname;w;uptime"
}
if *fromFile != "" {
c.FromFile = *fromFile
}
}
func check(e error) {
if e != nil {
log.Fatalf("send encountered an error!\t%+v", e)
}
}
func getHelp() {
fmt.Fprintf(os.Stderr, "usage of send:\n")
flag.PrintDefaults()
os.Exit(1)
}
func loadKey(path string) ssh.AuthMethod {
// contents is a bytes array
contents, e := ioutil.ReadFile(path)
check(e)
key, err := ssh.ParsePrivateKey(contents)
check(err)
return ssh.PublicKeys(key)
}