Skip to content

Commit

Permalink
Refactoring and adds shell as a standalone action
Browse files Browse the repository at this point in the history
  • Loading branch information
dimeko committed Jun 26, 2024
1 parent ef869fd commit a8102e1
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 40 deletions.
19 changes: 9 additions & 10 deletions deltascan/cli/cli_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from deltascan.core.utils import (format_string)
from deltascan.core.output import Output
from deltascan.core.schemas import ReportScanFromDB, ReportDiffs
from deltascan.core.exceptions import AppExceptions
from deltascan.core.config import APP_DATE_FORMAT
from marshmallow import ValidationError
from rich.console import Console
Expand All @@ -33,7 +32,7 @@ class CliOutput(Output):
console: Console
_display_title: str

def __init__(self, data=None, suppress=False):
def __init__(self, data=None, verbose=False):
"""
Initializes a new instance of the DataPresentation class.
Expand All @@ -46,7 +45,7 @@ def __init__(self, data=None, suppress=False):
self.data = []
if data is not None:
self._validate_data(data)
self.suppress = suppress
self.verbose = verbose
self._index_to_uuid_mapping = {}
self.console = Console()

Expand Down Expand Up @@ -118,7 +117,7 @@ def _display_scan_results(self):
}
tables = []
_counter = 1
if self.suppress is True:
if self.verbose is False:
_sup_table = Table(show_header=True)
_sup_table.add_column("Index", style=colors["col_1"], no_wrap=False, width=10)
_sup_table.add_column("Uid", style=colors["col_2"], no_wrap=False)
Expand All @@ -132,7 +131,7 @@ def _display_scan_results(self):

for scan in self.data:
self._index_to_uuid_mapping[str(_counter)] = scan["uuid"]
if self.suppress is False:
if self.verbose is True:
table = Table(show_header=True)
_status = self._print_color_depended_on_value(
scan['results']['status'])
Expand Down Expand Up @@ -186,7 +185,7 @@ def _display_scan_results(self):
)
_counter += 1

if self.suppress is True:
if self.verbose is False:
tables.append(_sup_table)

return tables
Expand All @@ -213,7 +212,7 @@ def _display_scan_diffs(self):
"for the given arguments[/]")
return [table]

if self.suppress is True:
if self.verbose is False:
_sup_table = Table(show_header=True)
_sup_table.add_column("Host", style=colors[0], no_wrap=True)
_sup_table.add_column("Dates", style=colors[1], no_wrap=True)
Expand All @@ -222,7 +221,7 @@ def _display_scan_diffs(self):
_sup_table.add_column("Arguments", style=colors[0], no_wrap=True)

for row in self.data:
if self.suppress is False:
if self.verbose is True:
table = Table()
table.title = f"[dim]Host: [/][rosy_brown]" \
f"{self._print_generic_information_if_different(row['generic'][1]['host'], row['generic'][0]['host'])}[/]\n" \
Expand Down Expand Up @@ -263,7 +262,7 @@ def _display_scan_diffs(self):
row['generic']['arguments']
)

if self.suppress is True:
if self.verbose is False:
tables.append(_sup_table)

return tables
Expand Down Expand Up @@ -291,7 +290,7 @@ def _dict_diff_fields_to_list(self, diff_dict):
return new_list

def _display(self):
raise AppExceptions.DScanMethodNotImplemented("Something wrong happened. Please check your input")
print("No output to display ...")

def display(self):
"""
Expand Down
31 changes: 19 additions & 12 deletions deltascan/cli/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def clear_screen():
os.system("clear -x")


def interactive_shell(_app, _ui, _interactive):
def interactive_shell(_app, _ui, _interactive, open_shell=False):
"""
Starts an interactive shell for the application.
Expand All @@ -50,8 +50,9 @@ def interactive_shell(_app, _ui, _interactive):
__only_first_time = True

while _app.cleaning_up is False:
if _app.is_running is True and _interactive is True and __only_first_time is True:
if (_app.is_running is True and _interactive is True and __only_first_time is True) or open_shell is True:
__only_first_time = False
open_shell = False
pass
else:
# Setting input with timeout in order not to block in case of cancel
Expand Down Expand Up @@ -176,7 +177,7 @@ def do_view(self, _):
Execute the view action using the current configuration"""
try:
_r = self._app.view()
output = CliOutput(_r, self._app.suppress)
output = CliOutput(_r, self._app.verbose)
_res = output.display()
self.last_index_to_uuid_mapping = _res
except Exception as e:
Expand Down Expand Up @@ -301,7 +302,7 @@ def run():
parser = argparse.ArgumentParser(
prog='deltascan', description='A package for scanning deltas')
parser.add_argument(
"action", help='the command to run', choices=['scan', 'diff', 'view', 'import', 'version'])
"action", help='the command to run', choices=['scan', 'diff', 'view', 'import', 'shell', 'version'])
parser.add_argument("-o", "--output", help='output file', required=False)
parser.add_argument("-d", "--diff-files",
help='comma separated files to find their differences (xml)',
Expand All @@ -326,8 +327,8 @@ def run():
# "-v", "--verbose", default=False, action='store_true',
# help="verbose output", required=False)
parser.add_argument(
"-s", "--suppress", default=False, action='store_true',
help="suppress output", required=False)
"-v", "--verbose", default=False, action='store_true',
help="verbose output", required=False)
parser.add_argument(
"--n-scans", help="limit of scans databse queries. It is applied in scans view as well as scans diff",
required=False)
Expand Down Expand Up @@ -388,8 +389,7 @@ def run():
"action": clargs.action,
"profile": clargs.profile,
"conf_file": clargs.conf_file,
"verbose": None,
"suppress": clargs.suppress,
"verbose": clargs.verbose,
"n_scans": clargs.n_scans,
"n_diffs": clargs.n_diffs,
"fdate": clargs.from_date,
Expand Down Expand Up @@ -445,7 +445,7 @@ def run():
item for sublist in [
_s["scans"] for _s in _dscan.result if "scans" in _s
] for item in sublist
], _dscan.suppress)
], _dscan.verbose)

output.display()
os._exit(0)
Expand All @@ -455,16 +455,23 @@ def run():
_r = _dscan.files_diff()
else:
_r = _dscan.diffs()
output = CliOutput(_r)
output = CliOutput(_r, _dscan.verbose)
output.display()
elif clargs.action == 'view':
_r = _dscan.view()
output = CliOutput(_r)
output = CliOutput(_r, _dscan.verbose)
output.display()
elif clargs.action == 'import':
_r = _dscan.import_data()
output = CliOutput(_r)
output = CliOutput(_r, _dscan.verbose)
output.display()
elif clargs.action == 'shell':
_dscan_thread = ThreadWithException(target=_dscan.scan)
_shell_thread = ThreadWithException(
target=interactive_shell, args=(_dscan, ui_context, clargs.interactive, True))
_dscan_thread.start()
_shell_thread.start()
_dscan_thread.join()
else:
if clargs.interactive is True:
print("No action provided. Starting interactive shell.")
Expand Down
1 change: 0 additions & 1 deletion deltascan/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ class Config:
profile: str
conf_file: str
verbose: bool
suppress: bool
n_scans: str
n_diffs: str
fdate: str
Expand Down
26 changes: 11 additions & 15 deletions deltascan/core/deltascan.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ def __init__(self, config, ui_context=None, result=[]):
_config['profile'],
_config['conf_file'],
_config['verbose'],
_config['suppress'],
_config['n_scans'],
_config['n_diffs'],
_config['fdate'],
Expand Down Expand Up @@ -113,7 +112,6 @@ def __init__(self, config, ui_context=None, result=[]):
self._scans_history = []
self.renderables = []
self._cleaning_up = False
self._has_been_interactive = False
self._is_running = False

self._T = None
Expand Down Expand Up @@ -272,7 +270,7 @@ def _scan_orchestrator(self):
if self.scans_to_wait == 0:
time.sleep(0.2)

if (self.scans_to_wait == 0 and (self._config.is_interactive is False and self._has_been_interactive is False)) or self._cleaning_up:
if (self.scans_to_wait == 0 and self._config.is_interactive is False) or self._cleaning_up:
self._is_running = False
break

Expand Down Expand Up @@ -344,7 +342,7 @@ def _port_scan(self, __host=None, __profile=None, __name=None, __evt=None):
raise AppExceptions.DScanInputValidationException("Invalid host format")

if self.ui_context is not None:
self.ui_context["show_nmap_logs"] = self._config.is_interactive is False and self._has_been_interactive is False
self.ui_context["show_nmap_logs"] = self._config.is_interactive is False

results = Scanner.scan(_host, _profile_arguments, self.ui_context, logger=self.logger, name=_name, _cancel_evt=__evt)

Expand All @@ -364,8 +362,8 @@ def _port_scan(self, __host=None, __profile=None, __name=None, __evt=None):

# getting the current date and time in order not to override existing files
_now = datetime.now().strftime(FILE_DATE_FORMAT)
# Create the report only if output_file is configured and has never got ininteractive mode
if self._config.output_file is not None and (self._config.is_interactive is False and self._has_been_interactive is False):
# Create the report only if output_file is configured and has never got interactive mode
if self._config.output_file is not None and (self._config.is_interactive is False):
self._report_scans(last_n_scans, f"scans_{_host}_{_profile}_{_now}_{self._config.output_file}")

self._result.append({
Expand Down Expand Up @@ -416,7 +414,7 @@ def diffs(self, uuids=None):
_split_scans_in_hosts = self.__split_scans_in_hosts([_s for _s in scans])

diffs = self._list_scans_with_diffs([_s for _scans in _split_scans_in_hosts.values() for _s in _scans])
if self._config.output_file is not None and (self._config.is_interactive is False and self._has_been_interactive is False):
if self._config.output_file is not None and self._config.is_interactive is False:
self._report_diffs(diffs, output_file=f"diffs_{self._config.output_file}")

# getting the current date and time in order not to override existing files
Expand Down Expand Up @@ -544,7 +542,7 @@ def files_diff(self, _diff_files=None):
"diffs": __diffs,
"result_hashes": ["", ""]
})
if self._config.output_file is not None and (self._config.is_interactive is False and self._has_been_interactive is False):
if self._config.output_file is not None and self._config.is_interactive is False:
self._report_diffs(_final_diffs, output_file=f"diffs_{self._config.output_file}")
return _final_diffs

Expand Down Expand Up @@ -993,16 +991,14 @@ def is_interactive(self):
@is_interactive.setter
def is_interactive(self, value):
self._config.is_interactive = value
if self._config.is_interactive is True:
self._has_been_interactive = True

@property
def suppress(self):
return self._config.suppress
def verbose(self):
return self._config.verbose

@suppress.setter
def suppress(self, value):
self._config.suppress = value
@verbose.setter
def verbose(self, value):
self._config.verbose = value

@property
def host(self):
Expand Down
1 change: 0 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ class Config:
profile: str
conf_file: str
verbose: str
suppress: bool
n_scans: str
n_diffs: str
fdate: str
Expand Down
1 change: 0 additions & 1 deletion tests/unit/test_deltascan.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ def setUp(self):
"profile": "TEST_V1",
"conf_file": CONFIG_FILE,
"verbose": False,
"suppress": False,
"n_scans": 1,
"n_diffs": 1,
"fdate": "2024-03-09 10:00:00",
Expand Down

0 comments on commit a8102e1

Please sign in to comment.