Commit b3a1fe26 by fwkz

Using PrinterThread as a main entry for all sys.out operations

parent 8c7ece59
......@@ -5,6 +5,7 @@ import itertools
import traceback
import atexit
from routersploit.threads import PrinterThread, printer_queue
from routersploit.exceptions import RoutersploitException
from routersploit.exploits import GLOBAL_OPTS
from routersploit import utils
......@@ -75,7 +76,7 @@ class BaseInterpreter(object):
def start(self):
""" Routersploit main entry point. Starting interpreter loop. """
print(self.banner)
utils.print_info(self.banner)
while True:
try:
command, args = self.parse_line(raw_input(self.prompt))
......@@ -86,11 +87,13 @@ class BaseInterpreter(object):
except RoutersploitException as err:
utils.print_error(err)
except EOFError:
print()
utils.print_info()
utils.print_status("routersploit stopped")
break
except KeyboardInterrupt:
print()
utils.print_info()
finally:
printer_queue.join()
def complete(self, text, state):
"""Return the next possible completion for 'text'.
......@@ -168,6 +171,7 @@ class RoutersploitInterpreter(BaseInterpreter):
def __init__(self):
super(RoutersploitInterpreter, self).__init__()
PrinterThread().start()
self.current_module = None
self.raw_prompt_template = None
......@@ -287,7 +291,7 @@ class RoutersploitInterpreter(BaseInterpreter):
try:
self.current_module.run()
except KeyboardInterrupt:
print()
utils.print_info()
utils.print_error("Operation cancelled by user")
except:
utils.print_error(traceback.format_exc(sys.exc_info()))
......@@ -385,21 +389,21 @@ class RoutersploitInterpreter(BaseInterpreter):
try:
devices = self.current_module._Exploit__info__['devices']
print("\nTarget devices:")
utils.print_info("\nTarget devices:")
i = 0
for device in devices:
if isinstance(device, dict):
print(" {} - {}".format(i, device['name']))
utils.print_info(" {} - {}".format(i, device['name']))
else:
print(" {} - {}".format(i, device))
utils.print_info(" {} - {}".format(i, device))
i += 1
print()
utils.print_info()
except KeyError:
print("\nTarget devices are not defined")
utils.print_info("\nTarget devices are not defined")
def __show_modules(self, root=''):
for module in [module for module in self.modules if module.startswith(root)]:
print(module.replace('.', os.sep))
utils.print_info(module.replace('.', os.sep))
def _show_all(self, *args, **kwargs):
self.__show_modules()
......@@ -444,9 +448,9 @@ class RoutersploitInterpreter(BaseInterpreter):
utils.print_status("Target could not be verified")
def command_help(self, *args, **kwargs):
print(self.global_help)
utils.print_info(self.global_help)
if self.current_module:
print("\n", self.module_help)
utils.print_info("\n", self.module_help)
def command_exec(self, *args, **kwargs):
os.system(args[0])
......
......@@ -359,7 +359,7 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.assertEqual(self.interpreter.current_module, None)
@mock.patch('__builtin__.print')
@mock.patch('routersploit.utils.print_info')
def test_show_info(self, mock_print):
metadata = {
'devices': 'target_desc',
......@@ -390,7 +390,7 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
]
)
@mock.patch('__builtin__.print')
@mock.patch('routersploit.utils.print_info')
def test_command_show_info_module_with_no_metadata(self, mock_print):
metadata = {}
description = "Elaborate description fo the module"
......@@ -403,7 +403,7 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
[mock.call()]
)
@mock.patch('__builtin__.print')
@mock.patch('routersploit.utils.print_info')
def test_show_options(self, mock_print):
exploit_attributes = {
'target': 'target_desc',
......@@ -444,7 +444,7 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
]
)
@mock.patch('__builtin__.print')
@mock.patch('routersploit.utils.print_info')
def test_command_show_options_when_there_is_no_module_opts(self, mock_print):
exploit_attributes = {
'target': 'target_desc',
......@@ -483,7 +483,7 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
"What do you want to show?\n"
"Possible choices are: {}".format(self.interpreter.show_sub_commands))
@mock.patch('__builtin__.print')
@mock.patch('routersploit.utils.print_info')
def test_show_all(self, mock_print):
self.interpreter.modules = [
'exploits.foo',
......@@ -507,7 +507,7 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
]
)
@mock.patch('__builtin__.print')
@mock.patch('routersploit.utils.print_info')
def test_show_scanners(self, mock_print):
self.interpreter.modules = [
'exploits.foo',
......@@ -524,7 +524,7 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
[mock.call("scanners/foo"), mock.call("scanners/bar")]
)
@mock.patch('__builtin__.print')
@mock.patch('routersploit.utils.print_info')
def test_show_exploits(self, mock_print):
self.interpreter.modules = [
'exploits.foo',
......@@ -541,7 +541,7 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
[mock.call("exploits/foo"), mock.call("exploits/bar")]
)
@mock.patch('__builtin__.print')
@mock.patch('routersploit.utils.print_info')
def test_show_creds(self, mock_print):
self.interpreter.modules = [
'exploits.foo',
......@@ -603,13 +603,13 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.interpreter.command_exec("foo -bar")
mock_system.assert_called_once_with("foo -bar")
@mock.patch('__builtin__.print')
@mock.patch('routersploit.utils.print_info')
def test_command_help(self, mock_print):
self.interpreter.current_module = None
self.interpreter.command_help()
mock_print.assert_called_once_with(self.interpreter.global_help)
@mock.patch('__builtin__.print')
@mock.patch('routersploit.utils.print_info')
def test_command_help_with_module_loaded(self, mock_print):
self.interpreter.command_help()
......
......@@ -18,6 +18,7 @@ from abc import ABCMeta, abstractmethod
import requests
from .threads import printer_queue
from .exceptions import RoutersploitException
from . import modules as rsf_modules
......@@ -39,6 +40,7 @@ colors = {
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
Resource = collections.namedtuple("Resource", ["name", "template_path", "context"])
PrintResource = collections.namedtuple("PrintResource", ['content', 'sep', 'end', 'file',])
def index_modules(modules_directory=MODULES_DIR):
......@@ -146,7 +148,7 @@ def stop_after(space_number):
if len(args[1].split(' ', space_number)) == space_number + 1:
return []
except Exception as err:
print(err)
print_info(err)
return wrapped_function(self, *args, **kwargs)
return _wrapper
return _outer_wrapper
......@@ -225,17 +227,16 @@ def __cprint(*args, **kwargs):
if not kwargs.pop("verbose", True):
return
with print_lock:
color = kwargs.get('color', None)
if color:
file_ = kwargs.get('file', sys.stdout)
sep = kwargs.get('sep', ' ')
end = kwargs.get('end', '\n')
print('\033[{}m'.format(colors[color]), end='', file=file_, sep=sep)
print(*args, end='', file=file_, sep=sep) # TODO printing text that starts from newline
print('\033[0m', sep=sep, end=end, file=file_)
if color:
printer_queue.put(PrintResource(content='\033[{}m'.format(colors[color]), end='', file=file_, sep=sep))
printer_queue.put(PrintResource(content=args, end='', file=file_, sep=sep)) # TODO printing text that starts from newline
printer_queue.put(PrintResource(content='\033[0m', sep=sep, end=end, file=file_))
else:
print(*args, **kwargs)
printer_queue.put(PrintResource(content=args, sep=sep, end=end, file=file_))
def print_error(*args, **kwargs):
......@@ -328,9 +329,9 @@ def print_table(headers, *args, **kwargs):
'{:<{}}'.format(header_separator * len(header), current_line_fill)
))
print()
print(headers_line)
print(headers_separator_line)
print_info()
print_info(headers_line)
print_info(headers_separator_line)
for arg in args:
content_line = ' '
for idx, element in enumerate(arg):
......@@ -338,9 +339,9 @@ def print_table(headers, *args, **kwargs):
content_line,
'{:<{}}'.format(element, fill[idx])
))
print(content_line)
print_info(content_line)
print()
print_info()
def sanitize_url(address):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment