-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
143 lines (121 loc) · 3.5 KB
/
main.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
package main
import (
"fmt"
"net"
"os"
"os/user"
"strings"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"gopkg.in/alecthomas/kingpin.v2"
)
const TIMEOUT = 3
const VERSION = "1.0.0"
func executeCmd(cmd string, hostport string, config *ssh.ClientConfig) string {
fmt.Println(formatRemoteCallLog(hostport, "executing command '"+cmd+"'"))
if !strings.Contains(hostport, ":") {
hostport = hostport + ":22"
}
client, err := ssh.Dial("tcp", hostport, config)
if err != nil {
halt(formatRemoteCallLog(hostport, "failed to connect: "+err.Error()))
}
session, err := client.NewSession()
if err != nil {
halt(formatRemoteCallLog(hostport, "failed to create session: "+err.Error()))
}
defer session.Close()
output, err := session.Output(cmd)
if err != nil {
fmt.Println(formatRemoteCallLog(hostport, "failed (empty crontab?): "+err.Error()))
}
return string(output[:])
}
func formatRemoteCallLog(hostname, msg string) string {
return fmt.Sprintf("[%s] %s", hostname, msg)
}
func halt(msg string) {
fmt.Println(msg)
os.Exit(1)
}
func getCurrentUser() string {
user, err := user.Current()
if err != nil {
return ""
}
return user.Username
}
var (
app = kingpin.New("cron2html", "Get an overview about all your cronjobs.")
servers = app.Arg("servers", "server (define custom SSH port by adding ':<PORT>')").Required().Strings()
sshUser = app.Flag("user", "SSH user for login").Short('u').Default(getCurrentUser()).String()
cronUser = app.Flag("cron-user", "User of crontab (default is the SSH user)").Short('c').String()
outputFilename = app.Flag("output", "Filename of the output").Short('o').Default("output.html").String()
omitEmptyServers = app.Flag("omit-empty", "Omit servers with empty crontabs").Bool()
)
func main() {
app.Version(templateVersion())
kingpin.MustParse(app.Parse(os.Args[1:]))
conn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
halt("failed connecting to ssh agent: " + err.Error())
}
defer conn.Close()
ag := agent.NewClient(conn)
clientConfig := &ssh.ClientConfig{
User: *sshUser,
Auth: []ssh.AuthMethod{
ssh.PublicKeysCallback(ag.Signers),
},
}
collector := make(chan ServerCrontab)
done := make(chan bool)
for _, hostname := range *servers {
fmt.Println("Collecting from " + hostname + "...")
go func(server string) {
cmd := "crontab -l"
if len(*cronUser) > 0 && *sshUser != *cronUser {
cmd = "sudo " + cmd + " -u " + *cronUser
} else {
*cronUser = *sshUser
}
output := executeCmd(cmd, server, clientConfig)
collector <- ServerCrontab{Server: server, User: *cronUser, rawCrontab: output}
}(hostname)
}
go func() {
results := ServerCrontabs{}
skipped := 0
for {
select {
case result, more := <-collector:
if !more {
done <- true
return
}
result.parseEntries()
if !*omitEmptyServers || (*omitEmptyServers && len(result.Entries) > 0) {
results = append(results, result)
fmt.Println("... collected crontab with", len(result.Entries), "entries from", result.Server)
} else {
skipped++
fmt.Println("... skipped empty server", result.Server)
}
if len(results)+skipped == len(*servers) {
if len(results) > 0 {
writeFile(*outputFilename, &results)
} else {
halt("... stopped, nothing to save")
}
close(collector)
}
case <-time.After(TIMEOUT * time.Second):
writeFile(*outputFilename, &results)
fmt.Println()
halt("... Timeout!")
}
}
}()
<-done
}