Skip to content

Commit 7485353

Browse files
authored
Merge branch 'main' into main
2 parents 0ed7ff2 + 97df993 commit 7485353

File tree

11 files changed

+69
-61
lines changed

11 files changed

+69
-61
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,4 @@ tmp
7272
TODO
7373
script.py
7474
tool.py
75+
testsploit/workspace/*

pyproject.toml

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,14 @@ classifiers = [
3434
"Programming Language :: Python :: 3.9",
3535
"Programming Language :: Python :: 3.10",
3636
"Programming Language :: Python :: 3.11",
37+
"Programming Language :: Python :: 3.12",
3738
"Topic :: Software Development :: Libraries :: Python Modules",
3839
]
3940
dependencies = [
40-
"peewee",
41-
"prompt_toolkit>=3.0.32",
41+
"peewee>=3.17.6",
42+
"prompt_toolkit>=3.0.47",
4243
"requests",
43-
"tinyscript>=1.28.6",
44+
"tinyscript>=1.30.15",
4445
]
4546
dynamic = ["version"]
4647

src/sploitkit/core/components/config.py

Lines changed: 10 additions & 8 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

@@ -94,15 +89,17 @@ 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):
@@ -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()):
@@ -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
@@ -369,9 +368,11 @@ def value(self):
369368
value = Config._g.get(self.name, value)
370369
if self.required and value is None:
371370
raise ValueError(f"{self.name} must be defined")
372-
try: # try to expand format variables using console's attributes
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

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: 5 additions & 5 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,9 +119,11 @@ def snapshot(self, save=True):
121119
if save:
122120
self._last_snapshot += 1
123121
s = f"{self.path}.snapshot{self._last_snapshot}"
122+
from shutil import copy
124123
copy(self.path, s) if save else copy(s, self.path)
125124
if not save:
126-
remove(f"{self.path}.snapshot{self._last_snapshot}")
125+
from os import remove
126+
remove("{}.snapshot{}".format(self.path, self._last_snapshot))
127127
self._last_snapshot -= 1
128128
self.connect()
129129

0 commit comments

Comments
 (0)