Skip to content

Commit 0192fd4

Browse files
committed
Adapted lazy imports
1 parent f0c64c7 commit 0192fd4

File tree

8 files changed

+73
-68
lines changed

8 files changed

+73
-68
lines changed

src/sploitkit/core/components/config.py

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,4 @@
11
# -*- coding: UTF-8 -*-
2-
import re
3-
from itertools import chain
4-
from termcolor import colored
5-
from tinyscript.helpers import is_function, BorderlessTable, Path
6-
72
from .logger import *
83

94

@@ -40,7 +35,7 @@ def __delitem__(self, key):
4035
self.console.reset()
4136
except AttributeError as err:
4237
pass
43-
l.debug("{} => null".format(key.name))
38+
l.debug(f"{key.name} => null")
4439

4540
def __getitem__(self, key):
4641
""" Custom method for getting an item, returning the original value from the current Config instance or, if the
@@ -72,7 +67,7 @@ def __setitem__(self, key, value):
7267
key = self._setkey(key, value)
7368
if not force and key.old_value == key.value:
7469
try:
75-
l.debug("{} unchanged".format(key.name))
70+
l.debug(f"{key.name} unchanged")
7671
except AttributeError:
7772
pass
7873
return # stop here if the final value is unchanged
@@ -83,7 +78,7 @@ def __setitem__(self, key, value):
8378
self.console.reset()
8479
except AttributeError as err:
8580
pass
86-
l.success("{} => {}".format(key.name, value if force else key.value))
81+
l.success(f"{key.name} => {value if force else key.value}")
8782

8883
def __str__(self):
8984
""" Custom string method. """
@@ -94,33 +89,35 @@ def __str__(self):
9489
continue
9590
r = ["N", "Y"][r]
9691
if v == "":
92+
from tinyscript.helpers import colored
9793
n, v, r = map(lambda s: colored(s, "red", attrs=['bold']), [n, v, r])
9894
data.append([n, v, r, d])
9995
if len(data) > 1:
96+
from tinyscript.helpers import BorderlessTable
10097
try:
10198
prefix = self.console.opt_prefix
10299
except AttributeError:
103100
prefix = None
104101
return BorderlessTable(data).table if prefix is None else \
105-
BorderlessTable(data, "%s options" % prefix).table
102+
BorderlessTable(data, f"{prefix} options").table
106103
return ""
107104

108105
def __run_callback(self, key, name):
109106
""" Method for executing a callback and updating the current value with its return value if any. """
110-
logger.detail("{} {} callback triggered".format(key, name))
107+
logger.detail(f"{key} {name} callback triggered")
111108
retval = None
112109
if hasattr(self, "_last_error"):
113110
del self._last_error
114111
try:
115-
retval = getattr(key, "{}_callback".format(name))()
112+
retval = getattr(key, f"{name}_callback")()
116113
except Exception as e:
117114
self._last_error = e
118115
if True:#not isinstance(e, AttributeError):
119116
raise
120117
if retval is not None:
121118
key.old_value = key.value
122119
if not key.validate(retval):
123-
raise ValueError("Invalid value '{}'".format(retval))
120+
raise ValueError(f"Invalid value '{retval}'")
124121
self._d[key.name] = (key, retval)
125122

126123
def _getitem(self, key):
@@ -159,7 +156,7 @@ def _setkey(self, key, value):
159156
# then assign the new one if it is valid
160157
self._d[key.name] = (key, value)
161158
if value is not None and not key.validate(value):
162-
raise ValueError("Invalid value '{}' for key '{}'".format(value, key.name))
159+
raise ValueError(f"Invalid value '{value}' for key '{key.name}'")
163160
super(Config, self).__setitem__(key, value)
164161
return key
165162

@@ -181,6 +178,7 @@ def items(self, fail=True):
181178

182179
def keys(self, glob=False):
183180
""" Return string keys (like original dict). """
181+
from itertools import chain
184182
l = [k for k in self._d.keys()]
185183
if glob:
186184
for k in chain(self._d.keys(), Config._g.keys()):
@@ -300,7 +298,7 @@ def __repr__(self):
300298

301299
def __str__(self):
302300
""" Custom string method. """
303-
return "<{}[{}]>".format(self.name, ["N", "Y"][self.required])
301+
return f"<{self.name}[{'NY'[self.required]}]>"
304302

305303
def __set_func(self, func, name, default_func=None):
306304
""" Set a function, e.g. for manipulating option's value. """
@@ -309,7 +307,7 @@ def __set_func(self, func, name, default_func=None):
309307
if isinstance(func, type(lambda:0)):
310308
setattr(self, name, func.__get__(self, self.__class__))
311309
else:
312-
raise Exception("Bad {} lambda".format(name))
310+
raise Exception(f"Bad {name} lambda")
313311

314312
def bind(self, parent):
315313
""" Register this instance as a key of the given Config or retrieve the already existing one. """
@@ -325,6 +323,7 @@ def bind(self, parent):
325323
@property
326324
def choices(self):
327325
""" Pre- or lazy-computed list of choices. """
326+
from tinyscript.helpers import is_function
328327
c = self._choices
329328
if not is_function(c):
330329
return c
@@ -344,7 +343,7 @@ def input(self):
344343
if hasattr(self, "config"):
345344
return self.config[self]
346345
else:
347-
raise Exception("Unbound option {}".format(self.name))
346+
raise Exception(f"Unbound option {self.name}")
348347

349348
@property
350349
def module(self):
@@ -368,10 +367,12 @@ def value(self):
368367
if value == getattr(self, "default", None):
369368
value = Config._g.get(self.name, value)
370369
if self.required and value is None:
371-
raise ValueError("{} must be defined".format(self.name))
372-
try: # try to expand format variables using console's attributes
370+
raise ValueError(f"{self.name} must be defined")
371+
# try to expand format variables using console's attributes
372+
from re import findall
373+
try:
373374
kw = {}
374-
for n in re.findall(r'\{([a-z]+)\}', str(value)):
375+
for n in findall(r'\{([a-z]+)\}', str(value)):
375376
kw[n] = self.config.console.__dict__.get(n, "")
376377
try:
377378
value = value.format(**kw)
@@ -381,6 +382,7 @@ def value(self):
381382
pass
382383
# expand and resolve paths
383384
if self.name.endswith("FOLDER") or self.name.endswith("WORKSPACE"):
385+
from tinyscript.helpers import Path
384386
# this will ensure that every path is expanded
385387
value = str(Path(value, expand=True))
386388
# convert common formats to their basic types
@@ -447,7 +449,7 @@ def __getattribute__(self, name):
447449
return c.__getattribute__(name)
448450
except AttributeError:
449451
continue
450-
raise AttributeError("'ProxyConfig' object has no attribute '{}'".format(name))
452+
raise AttributeError(f"'ProxyConfig' object has no attribute '{name}'")
451453

452454
def __getitem__(self, key):
453455
""" Get method for returning the first occurrence of a key among the list of Config instances. """

src/sploitkit/core/components/files.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from ftplib import FTP, FTP_TLS
55
from shutil import which
66
from subprocess import call, PIPE
7-
from tinyscript.helpers import b, ensure_str, txt_terminal_render, Path, TempPath
7+
from tinyscript.helpers import Path
88

99

1010
__all__ = ["FilesManager"]
@@ -42,7 +42,7 @@ def edit(self, filename):
4242
#FIXME: edit by calling the locator and manage its local file (e.g. for a URL, point to a temp folder)
4343
ted = self.console.config['TEXT_EDITOR']
4444
if which(ted) is None:
45-
raise ValueError("'%s' does not exist or is not installed" % ted)
45+
raise ValueError(f"'{ted}' does not exist or is not installed")
4646
p = Path(self.console.config['WORKSPACE']).joinpath(filename)
4747
if not p.exists():
4848
p.touch()
@@ -78,7 +78,7 @@ def page(self, *filenames):
7878
""" Page a list of files using Less. """
7979
tvw = self.console.config['TEXT_VIEWER']
8080
if which(tvw) is None:
81-
raise ValueError("'%s' does not exist or is not installed" % tvw)
81+
raise ValueError(f"'{tvw}' does not exist or is not installed")
8282
filenames = list(map(str, filenames))
8383
for f in filenames:
8484
if not Path(str(f)).is_file():
@@ -98,6 +98,7 @@ def save(self, key, dst):
9898

9999
def view(self, key):
100100
""" View a file using the configured text viewer. """
101+
from tinyscript.helpers import txt_terminal_render
101102
try:
102103
self.page_text(self[key])
103104
except KeyError:
@@ -120,7 +121,8 @@ def list(self):
120121
@property
121122
def tempdir(self):
122123
""" Get the temporary directory. """
124+
from tinyscript.helpers import TempPath
123125
if not hasattr(self, "_tempdir"):
124-
self._tempdir = TempPath(prefix="%s-" % self.console.appname, length=16)
126+
self._tempdir = TempPath(prefix=f"{self.console.appname}-", length=16)
125127
return self._tempdir
126128

src/sploitkit/core/components/jobs.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
# -*- coding: UTF-8 -*-
22
import shlex
33
import subprocess
4-
from six import string_types
5-
from time import time
64
from tinyscript.helpers.text import ansi_seq_strip
75

8-
from sploitkit.core.components.logger import null_logger
96

107
__all__ = ["JobsPool"]
118

@@ -20,7 +17,7 @@ def __init__(self, cmd, **kwargs):
2017
debug = not kwargs.pop('no_debug', False)
2118
if debug:
2219
self.parent.logger.debug(" ".join(cmd) if isinstance(cmd, (tuple, list)) else cmd)
23-
cmd = shlex.split(cmd) if isinstance(cmd, string_types) and not kwargs.get('shell', False) else cmd
20+
cmd = shlex.split(cmd) if isinstance(cmd, str) and not kwargs.get('shell', False) else cmd
2421
super(Job, self).__init__(cmd, stdout=subprocess.PIPE, **kwargs)
2522
self._debug = debug
2623

@@ -86,6 +83,7 @@ def run(self, cmd, stdin=None, show=False, timeout=None, ansi_strip=True, **kwar
8683
return out, err
8784

8885
def run_iter(self, cmd, timeout=None, ansi_strip=True, **kwargs):
86+
from time import time
8987
kwargs['stderr'] = subprocess.STDOUT
9088
kwargs['universal_newlines'] = True
9189
p = Job(cmd, parent=self, **kwargs)
@@ -124,5 +122,6 @@ def terminate(self, subpool=None):
124122
def logger(self):
125123
if hasattr(self, "console"):
126124
return self.console.logger
125+
from sploitkit.core.components.logger import null_logger
127126
return null_logger
128127

src/sploitkit/core/components/logger.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
# -*- coding: utf8 -*-
2-
from logging.handlers import RotatingFileHandler
3-
from termcolor import colored
4-
from tinyscript import logging
2+
from tinyscript import colored, logging
53

64

75
__all__ = ["get_logger", "null_logger", "set_logging_level"]
@@ -54,6 +52,7 @@ def emit(self, record):
5452
def get_logger(name, logfile=None, level="INFO", dev=False, enabled=True):
5553
""" Logger initialization function. """
5654
def _setup_logfile(l):
55+
from logging.handlers import RotatingFileHandler
5756
if logfile is not None and not any(isinstance(h, RotatingFileHandler) for h in l.handlers):
5857
l.__logfile__ = logfile
5958
# setup a FileHandler for logging to a file (at level DEBUG)

src/sploitkit/core/components/recorder.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
# -*- coding: UTF-8 -*-
2-
from tinyscript.helpers import Path
3-
4-
52
__all__ = ["Recorder"]
63

74

@@ -24,6 +21,7 @@ def save(self, text):
2421

2522
def start(self, filename, overwrite=False):
2623
""" Start the recorder, creating the record file. """
24+
from tinyscript.helpers import Path
2725
self.__file = f = Path(filename)
2826
if f.suffix != ".rc":
2927
self.__file = f = Path(self.root_dir).joinpath(filename + ".rc")

src/sploitkit/core/components/sessions.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
# -*- coding: UTF-8 -*-
22
import os
3-
import shlex
4-
import shutil
5-
from subprocess import Popen
6-
from tinyscript.helpers import Path
3+
74

85
__all__ = ["SessionsManager"]
96

107

118
class Session(object):
129
""" Class representing a session object based on a shell command """
1310
def __init__(self, n, cmd, **kwargs):
11+
from shlex import split
12+
from tinyscript.helpers import Path
1413
self.id = n
1514
self.parent = kwargs.pop('parent')
1615
if isinstance(cmd, str):
17-
cmd = shlex.split(cmd)
16+
cmd = split(cmd)
1817
self._path = Path(self.parent.console._files.tempdir, "session", str(n), create=True)
1918
for i, s in enumerate(["stdin", "stdout", "stderr"]):
2019
fifo = str(self._path.joinpath(str(i)))
@@ -23,13 +22,15 @@ def __init__(self, n, cmd, **kwargs):
2322
setattr(self, "_" + s, os.open(fifo ,os.O_WRONLY))
2423

2524
def close(self):
25+
from shutil import rmtree
2626
for s in ["stdin", "stdout", "stderr"]:
2727
getattr(self, "_" + s).close()
28-
shutil.rmtree(str(self._path))
28+
rmtree(str(self._path))
2929
self._process.wait()
3030
del self.parent[self.id]
3131

3232
def start(self, **kwargs):
33+
from subprocess import Popen
3334
kwargs['close_fds'] = True
3435
kwargs['preexec_fn'] = os.setsid # NB: see subprocess' doc ; preexec_fn is not thread-safe
3536
self._process = Popen(cmd, stdout=self._stdout, stderr=self._stderr, stdin=self._stdin, **kwargs)

src/sploitkit/core/components/store.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
# -*- coding: UTF-8 -*-
2-
import re
3-
from os import remove
4-
from shutil import copy
52
from peewee import SqliteDatabase
63

74

@@ -88,6 +85,7 @@ def __init__(self, path, *args, **kwargs):
8885

8986
def __getattr__(self, name):
9087
""" Override getattr to handle add_* store methods. """
88+
from re import match
9189
if name == "basemodels":
9290
BaseModel = self._pool._entity_class._subclasses["basemodel"]
9391
return self._pool._entity_class._subclasses[BaseModel]
@@ -96,7 +94,7 @@ def __getattr__(self, name):
9694
return self._pool._entity_class._subclasses[Model]
9795
elif name == "volatile":
9896
return self.path == ":memory:"
99-
elif re.match(r"^[gs]et_[a-z]+", name) and name != "model":
97+
elif match(r"^[gs]et_[a-z]+", name) and name != "model":
10098
model = "".join(w.capitalize() for w in name.split("_")[1:])
10199
cls = self.get_model(model)
102100
if cls is not None:
@@ -121,8 +119,10 @@ def snapshot(self, save=True):
121119
if save:
122120
self._last_snapshot += 1
123121
s = "{}.snapshot{}".format(self.path, self._last_snapshot)
122+
from shutil import copy
124123
copy(self.path, s) if save else copy(s, self.path)
125124
if not save:
125+
from os import remove
126126
remove("{}.snapshot{}".format(self.path, self._last_snapshot))
127127
self._last_snapshot -= 1
128128
self.connect()

0 commit comments

Comments
 (0)