-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlslsh.py
executable file
·261 lines (214 loc) · 8.55 KB
/
lslsh.py
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#!/usr/bin/env python3
import cmd
import readline
import sys
import warnings
from json.decoder import JSONDecodeError
from typing import Dict, List, Union
import requests
from colorama import Back, Fore, Style, deinit, init # type: ignore
from tabulate import tabulate
from urllib3.connectionpool import InsecureRequestWarning # type: ignore
from lib import ErrorReceived, connect, disconnect, get_available_commands, send_cmd
SECRET_KEY: str = "29731e5170353a8b235098c43cd2099a4e805c55fb4395890e81f437c17334a9"
INTRO_TEXT: str = 'lslsh 0.0.1\nType "help" for more information.'
warnings.filterwarnings("ignore", category=InsecureRequestWarning)
class Shell(cmd.Cmd):
prompt = "> "
default_prompt = "> "
url = None
ruler = "-"
doc_header = "Available built-in commands (type help <topic>):"
undoc_header = "Undocumented built-in commands:"
doc_remote_header = "Available endpoint commands (type help <topic>):"
undoc_remote_header = "Undocumented endpoint commands:"
remote_commands: List[str] = []
def get_names(self):
return dir(self)
def precmd(self, line):
if line == "EOF":
print()
return "disconnect" if self.url else "exit"
return line
def emptyline(self):
return None
def pretty_print(self, data: Union[str, Dict, List]) -> Union[str, Dict, List]:
"""Attempt to pretty-print the input data."""
try:
if isinstance(data, list) and isinstance(data[0], dict):
# List of dicts; no header
rows = []
for item in data:
rows.append(list(item.keys()) + list(item.values()))
return tabulate(rows, tablefmt="plain")
elif isinstance(data, list) and isinstance(data[0], list):
# List of lists; use first row as header
# Style the header items
for i, item in enumerate(data[0]):
data[0][i] = f"\033[4m{Style.BRIGHT}{item}{Style.NORMAL}\033[0m"
return tabulate(data, headers="firstrow", tablefmt="plain")
elif isinstance(data, dict) and len(data.values()) == 1:
# Dict with one list; return a single column with header
header: str = next(iter(data.keys()))
values: list = next(iter(data.values()))
result = [f"\033[4m{Style.BRIGHT}{header}{Style.NORMAL}\033[0m"]
result.extend(values)
return "\n".join(result)
except TypeError:
pass
return data
def _send_cmd(self, command: str) -> str:
if not self.url:
return f"{Fore.RED}Error{Fore.RESET}: Not connected to an endpoint."
try:
result = send_cmd(self.url, SECRET_KEY, command).get("result")
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
print(f"{Fore.RED}Error{Fore.RESET}: Endpoint no longer available.")
self.do_disconnect(None)
return ""
else:
return f"{Fore.RED}Error{Fore.RESET}: {e}"
except Exception as e:
return f"{Fore.RED}Error{Fore.RESET}: {e}"
return self.pretty_print(result)
def do_connect(self, url):
"""usage: connect [URL]
Connect to the given endpoint URL.
"""
if self.url:
self.do_disconnect(None)
try:
uuid = connect(url, SECRET_KEY)
except Exception as e:
print(f"{Fore.RED}Connection failed{Fore.RESET}: {e}")
return
available_commands = get_available_commands(url, SECRET_KEY)
for key, value in available_commands.items():
self.add_cmd(key, value)
print(f"{Fore.GREEN}Connected to {uuid}{Fore.RESET}\n")
self.prompt = f"{Fore.BLUE}sl{Fore.RESET} > "
self.url = url
def do_exit(self, arg):
"""usage: exit
Exit the shell.
"""
if self.url:
self.do_disconnect(None)
return True
def do_disconnect(self, arg):
"""usage: disconnect
Disconnect from the endpoint."""
if self.url:
success = False
try:
success = disconnect(self.url, SECRET_KEY)
print("Disconnected from endpoint.")
except Exception:
pass
if not success:
print("Disconnected from endpoint (without acknowledgement).")
self.url = None
self.prompt = self.default_prompt
for cmd in self.remote_commands:
self.remove_cmd(cmd)
else:
print(f"{Fore.RED}Error{Fore.RESET}: Not connected to endpoint")
def add_cmd(self, name, help_text):
"""Make a new command available within the shell."""
def do_cmd(arg):
print(self._send_cmd(f"{do_cmd.__name__} {arg}"))
do_cmd.__doc__ = help_text
do_cmd.__name__ = name
setattr(self, f"do_{name}", do_cmd)
self.remote_commands.append(name)
def remove_cmd(self, name):
"""Remove a command from the shell."""
if not hasattr(Shell, f"do_{name}") and hasattr(self, f"do_{name}"):
delattr(self, f"do_{name}")
filter(lambda a: a != name, self.remote_commands)
def do_help(self, arg):
"""List available commands with "help" or detailed help with "help cmd"."""
if arg:
try:
func = getattr(self, "help_" + arg)
except AttributeError:
try:
doc = getattr(self, "do_" + arg).__doc__
if doc:
stripped_lines = []
for line in doc.splitlines():
stripped_lines.append(line.strip())
if stripped_lines[-1] != "":
stripped_lines.append("")
stripped = "\n".join(stripped_lines)
self.stdout.write(f"{stripped}\n")
return
except AttributeError:
pass
self.stdout.write("%s\n" % str(self.nohelp % (arg,)))
return
func()
else:
names = self.get_names()
cmds_doc = []
cmds_undoc = []
cmds_doc_remote = []
cmds_undoc_remote = []
help = {}
for name in names:
if name[:5] == "help_":
help[name[5:]] = 1
names.sort()
# There can be duplicates if routines overridden
prevname = ""
for name in names:
if name[:3] == "do_":
if name == prevname:
continue
prevname = name
cmd = name[3:]
if cmd in self.remote_commands:
if cmd in help:
cmds_undoc_remote.append(cmd)
else:
cmds_doc_remote.append(cmd)
elif cmd in help:
cmds_doc.append(cmd)
del help[cmd]
elif getattr(self, name).__doc__:
cmds_doc.append(cmd)
else:
cmds_undoc.append(cmd)
self.stdout.write("%s\n" % str(self.doc_leader))
self.print_topics(self.doc_header, cmds_doc, 15, 80)
self.print_topics(self.doc_remote_header, cmds_doc_remote, 15, 80)
self.print_topics(self.misc_header, list(help.keys()), 15, 80)
self.print_topics(self.undoc_header, cmds_undoc, 15, 80)
self.print_topics(self.undoc_remote_header, cmds_undoc_remote, 15, 80)
def print_topics(self, header, cmds, cmdlen, maxcol):
if cmds:
self.stdout.write(Style.BRIGHT + "%s\n" % str(header))
if self.ruler:
self.stdout.write(
Fore.LIGHTBLACK_EX + "%s\n" % str(self.ruler * len(header))
)
self.columnize(cmds, maxcol - 1)
self.stdout.write("\n")
def run():
init(autoreset=True)
shell = Shell()
try:
shell.cmdloop(INTRO_TEXT)
except KeyboardInterrupt:
shell.do_exit(None)
deinit()
except Exception:
deinit()
# Attempt to disconnect so the session immediately becomes available again
try:
shell.do_disconnect()
except Exception:
pass
raise
run()