Commit b3a1fe26 by fwkz

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

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