forked from itzg/rcon-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
223 lines (188 loc) · 4.88 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
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
223
package main
import (
"bufio"
"errors"
"fmt"
"io"
"net"
"os"
"runtime"
"strings"
"github.com/hamburghammer/rcon"
flags "github.com/spf13/pflag"
)
const (
defaultHost = "localhost"
defaultPort = "25575"
defaultPassword = ""
envVarPrefix = "RCON_CLI_"
)
// resetColor is the ASCII code for resetting the color.
const resetColor = "\u001B[0m"
// colors a map with the ASCII color codes for Unix terms.
var colors = map[string]string{
"0": "\u001B[30m", // black
"1": "\u001B[34m", // dark blue
"2": "\u001B[32m", // dark green
"3": "\u001B[36m", // dark aqua
"4": "\u001B[31m", // dark red
"5": "\u001B[35m", // dark purple
"6": "\u001B[33m", // gold
"7": "\u001B[37m", // gray
"8": "\u001B[30m", // dark gray
"9": "\u001B[34m", // blue
"a": "\u001B[32m", // green
"b": "\u001B[32m", // aqua
"c": "\u001B[31m", // red
"d": "\u001B[35m", // light purple
"e": "\u001B[33m", // yellow
"f": "\u001B[37m", // white
"k": "", // random
"m": "\u001B[9m", // strikethrough
"o": "\u001B[3m", // italic
"l": "\u001B[1m", // bold
"n": "\u001B[4m", // underline
"r": resetColor, // reset
}
// vars holding the parsed configuration
var (
host string
port string
password string
help bool
)
func main() {
commands, _ := parseArgs(os.Args[1:])
loadEnvIfNotSet()
if help {
printHelp()
os.Exit(0)
return
}
err := run(strings.Join(commands, " "))
if err != nil {
_, err = fmt.Fprintln(os.Stderr, err.Error())
if err != nil {
panic(err)
}
os.Exit(1)
}
}
func parseArgs(args []string) ([]string, error) {
flags.StringVar(&host, "host", defaultHost, "RCON server's hostname.")
flags.StringVar(&port, "port", defaultPort, "RCON server's port.")
flags.StringVar(&password, "password", defaultPassword, "RCON server's password.")
flags.BoolVarP(&help, "help", "h", false, "Prints this help message and exits.")
err := flags.CommandLine.Parse(args)
if err != nil {
return []string{}, err
}
command := flags.Args()
return command, nil
}
func loadEnvIfNotSet() {
envHost := os.Getenv(fmt.Sprintf("%sHOST", envVarPrefix))
if envHost != "" && host == defaultHost {
host = envHost
}
envPort := os.Getenv(fmt.Sprintf("%sPORT", envVarPrefix))
if envPort != "" && port == defaultPort {
port = envPort
}
envPassword := os.Getenv(fmt.Sprintf("%sPASSWORD", envVarPrefix))
if envPassword != "" && password == defaultPassword {
password = envPassword
}
}
func run(cmd string) error {
hostPort := net.JoinHostPort(host, port)
remoteConsole, err := rcon.Dial(hostPort, password)
if err != nil {
return fmt.Errorf("failed to connect to RCON server: %w", err)
}
defer remoteConsole.Close()
if len(cmd) == 0 {
err = executeInteractive(remoteConsole)
} else {
resp, err := execute(cmd, remoteConsole)
if err != nil {
return err
}
_, err = fmt.Println(resp)
}
return err
}
func printHelp() {
_, _ = fmt.Println(`rcon-cli is a CLI to interact with a RCON server.
It can be run in an interactive mode or to execute a single command.
USAGE:
rcon-cli [FLAGS] [RCON command ...]
FLAGS:`)
flags.PrintDefaults()
fmt.Printf(`
ENVIRONMENT VARIABLE:
All flags can be set through the flag name in capslock with the %s prefix (see examples).
Flags have allways priority over env vars!
EXAMPLES:
rcon-cli --host 127.0.0.1 --port 25575
rcon-cli --password admin123 stop
%sPORT=25575 rcon-cli stop
`, envVarPrefix, envVarPrefix)
}
func executeInteractive(remoteConsole *rcon.RemoteConsole) error {
scanner := bufio.NewScanner(os.Stdin)
_, _ = fmt.Println("To quit the session type 'exit'.")
_, _ = fmt.Print("> ")
for scanner.Scan() {
cmd := scanner.Text()
if cmd == "exit" {
return nil
}
resp, err := execute(cmd, remoteConsole)
if err != nil {
return err
}
_, _ = fmt.Println(resp)
_, _ = fmt.Print("> ")
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("reading standard input: %w", err)
}
return nil
}
func execute(cmd string, remoteConsole *rcon.RemoteConsole) (string, error) {
resp := ""
reqID, err := remoteConsole.Write(cmd)
if err != nil {
return resp, fmt.Errorf("failed to send command: %w", err)
}
resp, respID, err := remoteConsole.Read()
if err != nil {
if err == io.EOF {
return resp, nil
}
return resp, fmt.Errorf("failed to read command: %w", err)
}
if reqID != respID {
return resp, errors.New("the response id didn't match the request id")
}
resp = colorize(resp)
return resp, nil
}
// colorize tries to add the color codes for the terminal.
// works on none windows machines.
func colorize(str string) string {
const sectionSign = "§"
for code := range colors {
if runtime.GOOS == "windows" {
str = strings.ReplaceAll(str, sectionSign+code, "")
} else {
str = strings.ReplaceAll(str, sectionSign+code, colors[code])
}
}
// reset color after each new line
if runtime.GOOS != "windows" {
return strings.ReplaceAll(str, "\n", "\n"+resetColor)
}
return str
}