Exemplo n.º 1
0
    def __init__(self, serverhandler, servercmdhandler):
        """Constructor"""
        self.srvhandler = ServerHandler()
        self.srvhandler = serverhandler

        self.cmdhandler = ServerCommandHandler(serverhandler)
        self.cmdhandler = servercmdhandler
Exemplo n.º 2
0
class Server(QtWidgets.QWidget):
    handler: ServerHandler

    def __init__(self, flags=None, *args, **kwargs):
        super().__init__(flags, *args, **kwargs)
        # Задание имени окна
        self.setWindowTitle('Сервер обмена файлами')
        # Статическая надпись
        self.port_label = QtWidgets.QLabel('Порт')
        # Числовое поле порта
        self.port = QtWidgets.QSpinBox()
        self.port.setMaximum(2 ** 16)
        self.port.setMinimum(1)
        self.port.setValue(8888)
        # Контейнер компонент порта
        self.port_box = QtWidgets.QHBoxLayout()
        self.port_box.addWidget(self.port_label)
        self.port_box.addWidget(self.port)
        # Кнопки запуска и остановки сервера
        self.start_button = QtWidgets.QPushButton('Запуск сервера')
        self.stop_button = QtWidgets.QPushButton('Остановка сервера')
        # Контейнер управляющих кнопок
        self.buttons_box = QtWidgets.QHBoxLayout()
        self.buttons_box.addWidget(self.start_button)
        self.buttons_box.addWidget(self.stop_button)
        # Фоновый контейнер
        self.central_layout = QtWidgets.QVBoxLayout()
        self.central_layout.addLayout(self.port_box)
        self.central_layout.addLayout(self.buttons_box)

        self.setLayout(self.central_layout)
        self.setFixedSize(400, 90)
        self.block_controls(False)
        # Задание обработок нажатия клавиш
        self.start_button.clicked.connect(self.start)
        self.stop_button.clicked.connect(self.stop)

    # Запуск сервера
    def start(self):
        # Инициализация потока, работающего с сокетами
        self.handler = ServerHandler(
            host=socket.gethostname(),
            port=self.port.value()
        )
        self.handler.start()  # Запуск потока

        self.block_controls(True)

    # Остановка сервера
    def stop(self):
        self.handler.terminate()

        self.block_controls(False)

    # Блокировка/разблокировка компонент, в зависимости от состояния подключения
    def block_controls(self, connected):
        self.start_button.setDisabled(connected)
        self.port.setDisabled(connected)
        self.stop_button.setEnabled(connected)
Exemplo n.º 3
0
    def start(self):
        # Инициализация потока, работающего с сокетами
        self.handler = ServerHandler(
            host=socket.gethostname(),
            port=self.port.value()
        )
        self.handler.start()  # Запуск потока

        self.block_controls(True)
Exemplo n.º 4
0
    def __init__(self, serverhandler):
        """Constructor"""
        self.srvhandler = ServerHandler()
        self.srvhandler = serverhandler

        self.commands = {
            'luarun': self.command_luarun,
            'rcon': self.command_rcon,
            'sendfile': self.command_sendfile,
        }
Exemplo n.º 5
0
    def __init__(self, sock, rsakey):
        self._socket = sock
        # self._client_address
        try:
            self._transport = paramiko.Transport(self._socket)

            rsakey = paramiko.RSAKey(filename=rsakey)
            
            self._transport.add_server_key(rsakey)
            self._server = ServerHandler()
            self._transport.start_server(server=self._server)
        except paramiko.SSHException:
            raise RuntimeError("ssh negotiation failed.")
        except Exception:
            raise RuntimeError("failed to init client")
Exemplo n.º 6
0
class ClientServer:

    def __init__(self, socket, address):

        self._socket = socket
        self._hostname = address[0]
        self._port = address[1]
        try:
            self._transport = paramiko.Transport(self._socket)
            
            self._transport.add_server_key(load_host_key())
            self._server = ServerHandler()

            self._transport.start_server(server=self._server)
        except paramiko.SSHException:
            raise Exception("ssh negotiation failed.")
        except:
            raise Exception("failed to init client")
        
    def get_client_channel(self, timeout=3):
        channel = self._transport.accept(timeout)

        if channel is None:
            raise Exception("no channel opened. timeout...")
        if self._server.wait_for_event() is False:
            raise Exception("client did not ask for shell.")
        return channel
Exemplo n.º 7
0
class SSHClientConnection(object):

    def __init__(self, sock, rsakey):
        self._socket = sock
        # self._client_address
        try:
            self._transport = paramiko.Transport(self._socket)

            rsakey = paramiko.RSAKey(filename=rsakey)
            
            self._transport.add_server_key(rsakey)
            self._server = ServerHandler()
            self._transport.start_server(server=self._server)
        except paramiko.SSHException:
            raise RuntimeError("ssh negotiation failed.")
        except Exception:
            raise RuntimeError("failed to init client")

    def get_channel(self, timeout=3):
        channel = self._transport.accept(timeout)

        if channel is None:
            raise Exception("no channel opened. timeout...")
        if self._server.wait_for_event() is False:
            raise Exception("client did not ask for shell.")
        return channel

    def get_remote_address(self):
        return self._server.remote_address
Exemplo n.º 8
0
    def __init__(self, socket, address):

        self._socket = socket
        self._hostname = address[0]
        self._port = address[1]
        try:
            self._transport = paramiko.Transport(self._socket)

            self._transport.add_server_key(load_host_key())
            self._server = ServerHandler()

            self._transport.start_server(server=self._server)
        except paramiko.SSHException:
            raise Exception("ssh negotiation failed.")
        except:
            raise Exception("failed to init client")
Exemplo n.º 9
0
class ClientServer:
    def __init__(self, socket, address):

        self._socket = socket
        self._hostname = address[0]
        self._port = address[1]
        try:
            self._transport = paramiko.Transport(self._socket)

            self._transport.add_server_key(load_host_key())
            self._server = ServerHandler()

            self._transport.start_server(server=self._server)
        except paramiko.SSHException:
            raise Exception("ssh negotiation failed.")
        except:
            raise Exception("failed to init client")

    def get_client_channel(self, timeout=3):
        channel = self._transport.accept(timeout)

        if channel is None:
            raise Exception("no channel opened. timeout...")
        if self._server.wait_for_event() is False:
            raise Exception("client did not ask for shell.")
        return channel
Exemplo n.º 10
0
    def __init__(self, socket, address):

        self._socket = socket
        self._hostname = address[0]
        self._port = address[1]
        try:
            self._transport = paramiko.Transport(self._socket)
            
            self._transport.add_server_key(load_host_key())
            self._server = ServerHandler()

            self._transport.start_server(server=self._server)
        except paramiko.SSHException:
            raise Exception("ssh negotiation failed.")
        except:
            raise Exception("failed to init client")
Exemplo n.º 11
0
    def __init__(self, *args, **kwargs):
        QtWidgets.QMainWindow.__init__(self, *args, **kwargs)

        # Cargar GUI
        self.setupUi(self)

        # Determinar OS
        self.determine_os()
        
        # QMessageBox
        self.msg_box = QtWidgets.QMessageBox

        # Virus Total Handler
        try:
            self.server_handler = ServerHandler()
        except ValueError:
            self.msg_box.critical(self, 'Error', 'No se detectó una API Key válida de Virus Total.')
            os._exit(1)

        # Thread
        self.thread = QtCore.QThread()
        self.worker = self.server_handler
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(partial(self.server_handler.get_analysis, ""))
        self.worker.progress.connect(self.update_progress)
        self.worker.finished.connect(self.thread.quit)

        # Ocultar items
        self.uploadPb.setVisible(False)
        self.checkHarmlessLbl.setVisible(False)
        self.crossHarmlessLbl.setVisible(False)
        self.checkMaliciousLbl.setVisible(False)
        self.crossMaliciousLbl.setVisible(False)
        self.checkSuspiciousLbl.setVisible(False)
        self.crossSuspiciousLbl.setVisible(False)
        self.uploadBtn.clicked.connect(self.open_file_dialog)
Exemplo n.º 12
0
class ServerCommandHandler():
    """ServerCommandHandler"""
    def __init__(self, serverhandler):
        """Constructor"""
        self.srvhandler = ServerHandler()
        self.srvhandler = serverhandler

        self.commands = {
            'luarun': self.command_luarun,
            'rcon': self.command_rcon,
            'sendfile': self.command_sendfile,
        }

    def queue_command(self, serverip, arg_type, arg_command):
        """Queue Server Command"""
        self.srvhandler.servers[serverip].append([arg_type, arg_command])

    def command_luarun(self, arg_command, arg_input):
        """Luarun"""
        tosend = arg_input[len(arg_command) + 1:]
        self.queue_command(self.srvhandler.get_current_server(), arg_command,
                           tosend)
        print("luarun " + tosend + ">>" + self.srvhandler.get_current_server())

    def command_rcon(self, arg_command, arg_input):
        """Rcon"""
        tosend = arg_input[len(arg_command) + 1:]
        self.queue_command(self.srvhandler.get_current_server(), arg_command,
                           tosend)
        print("rcon " + tosend + ">>" + self.srvhandler.get_current_server())

    def command_sendfile(self, arg_command, arg_input):
        """SendFile"""
        tosend = arg_input[len(arg_command) + 1:]
        try:
            file_container = open('./includes/' + tosend + '.lua', 'r').read()
        except Exception:
            print("Error opening file: " + tosend + '.lua')
            return
        self.queue_command(self.srvhandler.get_current_server(), 'luarun',
                           file_container)
        print("luarun " + tosend + ">>" + self.srvhandler.get_current_server())
Exemplo n.º 13
0
class InputHandler():
    """Class InputHandler"""

    def __init__(self, serverhandler, servercmdhandler):
        """Constructor"""
        self.srvhandler = ServerHandler()
        self.srvhandler = serverhandler

        self.cmdhandler = ServerCommandHandler(serverhandler)
        self.cmdhandler = servercmdhandler

    def handle_console_input(self, originalInput):
        """Main Input func. Todo: split"""
        cmd = originalInput.split(" ")

        if originalInput == "list":
            for k in self.srvhandler.servers.keys():
                online = self.srvhandler.server_time[k]['curtime'] + \
                    10 >= time.time()
                print(k + " | Online: " + str(online))
            return

        try:
            command = cmd[0]
            arg = cmd[1]

        except Exception:
            print("[1] No such command: " + originalInput)
            return

        if command == "addserver":
            with open('server.list', 'a') as file:
                if os.stat("server.list").st_size == 0:
                    file.write(arg)
                else:
                    file.write('\n' + arg)
            self.srvhandler.servers[arg] = []
            self.srvhandler.set_server_time(arg, 0)
            print('Successful added ' + arg + ' to the list')
            return
        if command == "selectserver":
            if arg not in self.srvhandler.servers:
                print("No such server found.")
                return
            self.srvhandler.set_current_server(arg)
            print("Successfully selected server: " +
                  self.srvhandler.get_current_server())
            return

        try:

            if self.cmdhandler.commands[command]:
                if self.srvhandler.get_current_server() == "nil":
                    print(
                        "No server selected. ",
                        "Select a server by using selectserver [ip]")
                    return
                self.cmdhandler.commands[command](command, originalInput)
                return
        except Exception:
            print("[2] Wrong syntax: " + command)

    def read_input(self):
        while True:
            original_input = input()
            self.handle_console_input(original_input)
Exemplo n.º 14
0
 def __init__(self, server_address, handler, handler_class=Serv):
     super().__init__(server_address, handler_class)
     self.srvhandler = ServerHandler()
     self.srvhandler = handler