Example #1
0
def main():
    try:
        base_path = sys._MEIPASS
    except AttributeError:
        base_path = Path(__file__).parent

    # https://github.com/kivy/kivy/issues/4182#issuecomment-471488773
    if 'twisted.internet.reactor' in sys.modules:
        del sys.modules['twisted.internet.reactor']

    qapp = QApplication(sys.argv)
    qapp.setApplicationName("HPOS Seed")
    qapp.setOrganizationDomain("holo.host")
    qapp.setOrganizationName("Holo")

    # qt5reactor needs to be imported and installed after QApplication(),
    # but before importing twisted.internet.reactor. See qt5reactor docs.
    import qt5reactor
    qt5reactor.install()

    from twisted.internet import reactor
    app = App(qapp, reactor)

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("app", app)
    engine.load(Path(base_path, 'send_qt.qml').as_uri())

    reactor.run()
Example #2
0
def test_self_toggling(qtbot):
    # TODO: CAMPid 03127876954165421679215396954697
    # https://github.com/kivy/kivy/issues/4182#issuecomment-253159955
    # fix for pyinstaller packages app to avoid ReactorAlreadyInstalledError
    if "twisted.internet.reactor" in sys.modules:
        del sys.modules["twisted.internet.reactor"]

    import qt5reactor

    qt5reactor.install()

    from twisted.internet import reactor

    try:
        real_bus = can.interface.Bus(bustype="socketcan", channel="can0")
    except Exception:
        # Yep, it really raises just an Exception...
        real_bus = can.interface.Bus(bustype="pcan", channel="PCAN_USBBUS1")
    bus = epyqlib.busproxy.BusProxy(bus=real_bus)

    device = epyqlib.device.Device(
        file=epyqlib.tests.common.devices["customer"],
        node_id=247,
        bus=bus,
    )

    tx_signal_path = ("ParameterQuery", "ManageDIO", "InvertHwEnable")
    tx_signal = device.nvs.neo.signal_by_path(*tx_signal_path)
    rx_signal = tx_signal.status_signal

    value_changed_count = 0

    def value_changed():
        nonlocal value_changed_count
        value_changed_count += 1

    (widget, ) = [
        w for w in device.ui.findChildren(epyqlib.widgets.toggle.Toggle)
        if w.signal_path == ";".join(tx_signal_path)
    ]

    widget.ui.value.valueChanged.connect(value_changed)

    def toggle(n):
        value = False
        for _ in range(n):
            value = not value
            rx_signal.set_value(value)
            rx_signal.frame.update_from_signals()
            bus.notifier.message_received(rx_signal.frame.to_message())
            print(" + - + - receiving message now")

    toggle_count = 4
    QTimer.singleShot(1 * 1000, functools.partial(toggle, n=toggle_count))

    QTimer.singleShot(10 * 1000, reactor.stop)
    reactor.run()

    print("value_changed_count", value_changed_count)
    assert value_changed_count < 2 * toggle_count
Example #3
0
def run():
    app = PyQt5.QtWidgets.QApplication(sys.argv)

    # TODO: CAMPid 03127876954165421679215396954697
    # https://github.com/kivy/kivy/issues/4182#issuecomment-253159955
    # fix for pyinstaller packages app to avoid ReactorAlreadyInstalledError
    if 'twisted.internet.reactor' in sys.modules:
        del sys.modules['twisted.internet.reactor']

    import qt5reactor
    qt5reactor.install()

    from twisted.internet import reactor

    device = epyqlib.device.Device(
        file=epyqlib.tests.common.devices['customer'],
        node_id=247,
        # bus=bus,
    )
    device.ui.show()

    PyQt5.QtCore.QTimer.singleShot(1 * 1000, reactor.stop)
    reactor.run()

    return 0
Example #4
0
def main(width, height, path, timeout, hosts):
    """
    @summary: main algorithm
    @param height: {integer} height of screenshot
    @param width: {integer} width of screenshot
    @param timeout: {float} in sec
    @param hosts: {list(str(ip[:port]))}
    @return: {list(tuple(ip, port, Failure instance)} list of connection state
    """
    #create application
    app = QtWidgets.QApplication(sys.argv)

    #add qt5 reactor
    import qt5reactor
    qt5reactor.install()

    from twisted.internet import reactor

    for host in hosts:      
        if ':' in host:
            ip, port = host.split(':')
        else:
            ip, port = host, "3389"

        reactor.connectTCP(ip, int(port), RDPScreenShotFactory(reactor, app, width, height, path + "%s.jpg" % ip, timeout))

    reactor.runReturn()
    app.exec_()
    return RDPScreenShotFactory.__STATE__
Example #5
0
def main():
    app = QApplication(sys.argv)

    parser = argparse.ArgumentParser()

    parser.add_argument('--name', default=pwd.getpwuid(os.getuid()).pw_name, type=str, nargs='?', help='cmdr name')
    parser.add_argument('--stretch', default=0.6, type=float, nargs='?', help='window stretching factor')

    args = parser.parse_args()

    geometry = app.desktop().screenGeometry()
    import qt5reactor

    qt5reactor.install()
    from twisted.internet import reactor

    import miniActor

    actor = miniActor.connectActor(['hub', 'spsait'])

    try:
        ex = SequencePanel(reactor,
                             actor,
                             geometry.width() * args.stretch,
                             geometry.height() * args.stretch,
                             args.name)
    except:
        actor.disconnectActor()
        raise

    reactor.run()
    actor.disconnectActor()
Example #6
0
def main():
    app = QApplication(sys.argv)

    parser = argparse.ArgumentParser()

    parser.add_argument('--name', default=pwd.getpwuid(os.getuid()).pw_name, type=str, nargs='?', help='cmdr name')
    parser.add_argument('--stretch', default=0.6, type=float, nargs='?', help='window stretching factor')

    args = parser.parse_args()

    systemPath = '%s/%s' % (os.getcwd(), sys.argv[0].split('main.py')[0])
    geometry = app.desktop().screenGeometry()
    import qt5reactor

    qt5reactor.install()
    from twisted.internet import reactor

    import miniActor
    models = ['hub', 'xcu_r0']
    actor = miniActor.connectActor(models)

    try:
        ex = TemplateGUI(reactor,
                         actor,
                         geometry.width() * args.stretch,
                         geometry.height() * args.stretch,
                         args.name,
                         systemPath)
    except:
        actor.disconnectActor()
        raise

    reactor.run()
    actor.disconnectActor()
Example #7
0
def main():
    parser = ArgumentParser(
        description='PyQt version of Crossbar Gauges demo.')
    parser.add_argument(
        '--url',
        type=unicode,
        default=u'ws://127.0.0.1:8080/ws',
        metavar='<url>',
        help='WAMP router URL (default: ws://127.0.0.1:8080/ws).')
    args = parser.parse_args()

    app = QApplication(argv)
    qt5reactor.install()

    from twisted.internet import reactor

    def quit():
        if reactor.threadpool is not None:
            reactor.threadpool.stop()
        app.quit()

    window = VotesWindow(args.url, u'crossbardemo')
    window.closed.connect(quit)
    window.show()

    reactor.run()
Example #8
0
def main():
    args = parse_args()

    app = QApplication(argv)
    qt5reactor.install()

    runner = ApplicationRunner(args.url, u'crossbardemo', extra=vars(args))
    runner.run(make)
Example #9
0
def main():
    args = parse_args()

    app = QApplication(argv)
    qt5reactor.install()

    runner = ApplicationRunner(args.url, u'crossbardemo', extra=vars(args))
    runner.run(make)
Example #10
0
def main(**kwargs):
    app = QtApplication()
    qt5reactor.install()
    view = ViewerWindow(filename=kwargs.get('file', '-'),
                        frameless=kwargs.get('frameless', False))
    view.protocol = ViewerProtocol(view)
    view.show()
    app.deferred_call(lambda: StandardIO(view.protocol))
    app.start()
Example #11
0
def _setup_pre_reactor():
    global _qapp

    import sys

    import qt5reactor
    from PyQt5.QtWidgets import QApplication

    _qapp = QApplication.instance()
    if not _qapp:
        _qapp = QApplication(sys.argv)
    qt5reactor.install()
Example #12
0
def main():
    app = QtWidgets.QApplication(sys.argv)

    window = MainApp()
    window.show()

    import qt5reactor #Install reactor for all users
    qt5reactor.install()

    from twisted.internet import reactor
    reactor.connectTCP("localhost", 7410, ChatFactory(window))
    window.reactor = reactor
    reactor.run()
Example #13
0
def test_main():
    # TODO: CAMPid 03127876954165421679215396954697
    # https://github.com/kivy/kivy/issues/4182#issuecomment-253159955
    # fix for pyinstaller packages app to avoid ReactorAlreadyInstalledError
    if "twisted.internet.reactor" in sys.modules:
        del sys.modules["twisted.internet.reactor"]

    import qt5reactor

    qt5reactor.install()

    from twisted.internet import reactor

    real_bus = can.interface.Bus(bustype="socketcan", channel="can0")
    bus = epyqlib.busproxy.BusProxy(bus=real_bus)

    device = epyqlib.device.Device(
        file=epyqlib.tests.common.devices["customer"],
        node_id=247,
    )

    tx_signal = device.neo_frames.signal_by_path("CCP", "Connect",
                                                 "CommandCounter")
    rx_signal = device.neo_frames.signal_by_path("CCPResponse", "Connect",
                                                 "CommandCounter")
    protocol = ccp.Handler(
        endianness="little" if tx_signal.little_endian else "big",
        tx_id=tx_signal.frame.id,
        rx_id=rx_signal.frame.id,
    )
    transport = epyqlib.twisted.busproxy.BusProxy(
        protocol=protocol,
        reactor=reactor,
        bus=bus,
    )

    d = protocol.connect()
    d.addCallback(lambda _: protocol.set_mta(
        address_extension=ccp.AddressExtension.flash_memory,
        address=0x310000,
    ))
    d.addCallback(lambda _: protocol.disconnect())
    d.addBoth(logit)

    logging.debug("---------- started")
    QTimer.singleShot(3000, reactor.stop)
    reactor.run()
Example #14
0
def capture_host(cli_parsed, rdp_object):
    log._LOG_LEVEL = log.Level.ERROR
    width = 1200
    height = 800
    timeout = cli_parsed.timeout

    app = QtWidgets.QApplication(sys.argv)

    import qt5reactor
    qt5reactor.install()
    from twisted.internet import reactor

    reactor.connectTCP(
        rdp_object.remote_system, int(rdp_object.port), RDPScreenShotFactory(
            reactor, app, width, height,
            rdp_object.screenshot_path, timeout, rdp_object))

    reactor.runReturn()
    app.exec_()
Example #15
0
def main():
    app = QApplication(sys.argv)

    parser = argparse.ArgumentParser()

    parser.add_argument('--name',
                        default=pwd.getpwuid(os.getuid()).pw_name,
                        type=str,
                        nargs='?',
                        help='cmdr name')

    args = parser.parse_args()

    import qt5reactor

    qt5reactor.install()
    from twisted.internet import reactor

    import miniActor

    specIds = [i + 1 for i in range(12)]
    viscamNames = ['b%i' % i for i in specIds] + ['r%i' % i for i in specIds]
    nircamNames = ['n%i' % i for i in specIds]

    xcus = ['xcu_%s' % cam for cam in viscamNames + nircamNames]
    ccds = ['ccd_%s' % cam for cam in viscamNames]
    hxs = ['hx_%s' % cam for cam in nircamNames]
    enus = ['enu_sm%i' % i for i in specIds]
    lam = ['aten', 'sac', 'breva']
    sps = ['sps', 'dcb', 'dcb2', 'rough1', 'rough2']

    actor = miniActor.connectActor(['hub'] + lam + sps + enus + xcus + ccds +
                                   hxs)

    try:
        ex = Spsgui(reactor, actor, args.name)
    except:
        actor.disconnectActor()
        raise

    reactor.run()
    actor.disconnectActor()
Example #16
0
def main():
    # создаем приложение
    app = QtWidgets.QApplication(sys.argv)
    # испортируем реактор для Qt
    import qt5reactor

    # создаем графическое окно
    window = ExampleApp()
    window.show()

    # настройка реактора Qt
    qt5reactor.install()
    # импортируем стандартный реактор
    from twisted.internet import reactor

    # стнадартный запуск реактора
    reactor.connectTCP("localhost", 7410, ChatFactory(window))
    # передаем его также в окно для обращения
    window.reactor = reactor
    reactor.run()
Example #17
0
def main_gui():
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)

    # Check environment first
    from PyQt5.QtWidgets import QMessageBox, QSystemTrayIcon

    def dialog(message: str) -> None:
        QMessageBox.critical(None, "VirtScreen", message)

    if not QSystemTrayIcon.isSystemTrayAvailable():
        dialog("Cannot detect system tray on this system.")
        sys.exit(1)
    check_env(dialog)

    # Replace Twisted reactor with qt5reactor
    import qt5reactor  # pylint: disable=E0401
    qt5reactor.install()
    from twisted.internet import reactor  # pylint: disable=E0401

    app.setWindowIcon(QIcon(ICON_PATH))
    os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"
    # os.environ["QT_QUICK_CONTROLS_STYLE"] = "Fusion"

    # Register the Python type.  Its URI is 'People', it's v1.0 and the type
    # will be called 'Person' in QML.
    qmlRegisterType(DisplayProperty, 'VirtScreen.DisplayProperty', 1, 0,
                    'DisplayProperty')
    qmlRegisterType(Backend, 'VirtScreen.Backend', 1, 0, 'Backend')
    qmlRegisterType(Cursor, 'VirtScreen.Cursor', 1, 0, 'Cursor')
    qmlRegisterType(Network, 'VirtScreen.Network', 1, 0, 'Network')

    # Create a component factory and load the QML script.
    engine = QQmlApplicationEngine()
    engine.load(QUrl(MAIN_QML_PATH))
    if not engine.rootObjects():
        dialog("Failed to load QML")
        sys.exit(1)
    sys.exit(app.exec_())
    reactor.run()
Example #18
0
def main(args=None):
    app = QApplication(sys.argv)

    if args is None:
        args = sys.argv[1:]

    args = parse_args(args=args)

    if args.verbose >= 1:
        logger.setLevel(logging.DEBUG)

    if args.verbose >= 2:
        twisted.internet.defer.setDebugging(True)

    if args.verbose >= 3:
        logging.getLogger().setLevel(logging.DEBUG)

    qt5reactor.install()
    from twisted.internet import reactor

    reactor.runReturn()

    QApplication.instance().aboutToQuit.connect(about_to_quit)

    real_bus = can.interface.Bus(bustype=args.interface,
                                 channel=args.channel,
                                 bitrate=args.bitrate)
    bus = epyqlib.busproxy.BusProxy(bus=real_bus, auto_disconnect=False)

    flasher = Flasher(file=args.file, bus=bus)

    flasher.completed.connect(lambda f=flasher: completed(flasher=f))
    flasher.failed.connect(failed)
    flasher.done.connect(bus.set_bus)

    flasher.flash()

    return app.exec()
Example #19
0
def main():
    parser = ArgumentParser(description='PyQt version of Crossbar Gauges demo.')
    parser.add_argument('--url',
                        type=unicode,
                        default=u'ws://127.0.0.1:8080/ws',
                        metavar='<url>',
                        help='WAMP router URL (default: ws://127.0.0.1:8080/ws).')
    args = parser.parse_args()

    app = QApplication(argv)
    qt5reactor.install()

    from twisted.internet import reactor

    def quit():
        if reactor.threadpool is not None:
            reactor.threadpool.stop()
        app.quit()

    window = VotesWindow(args.url, u'crossbardemo')
    window.closed.connect(quit)
    window.show()

    reactor.run()
Example #20
0
def main():
    config = configparser.ConfigParser()
    config.read(os.path.expanduser("~/.la4.config.ini"))

    args = parse_args()
    app = QApplication(argv)
    qt5reactor.install()

    if not args.url or not config.has_option("gui", "url"):
        print("missing config file/parmas")
        configurator = QDialog()
        configurator.ui = LambentConfigWindow()
        configurator.ui.setupUi(configurator)
        configurator.exec_()

    elif "url" in "url" in config.options("gui"):
        print("found config")
        runner = ApplicationRunner(config.get("gui", "url"),
                                   u'realm1',
                                   extra=vars(args))
        runner.run(make)
    else:
        runner = ApplicationRunner(args.url, u'realm1', extra=vars(args))
        runner.run(make)
Example #21
0
def install_qtreactor(verbose):
    init_qt_app(verbose)
    import qt5reactor
    qt5reactor.install()
Example #22
0
# Aether modules
from GUI.guiElements import *
from globals import enableWebkitInspector, basedir

from ORM import Hermes

app = Aether()

#Python imports
import os

if globals.FROZEN:
    del sys.modules['twisted.internet.reactor']

import qt5reactor
qt5reactor.install()
from twisted.internet import reactor


# Aether modules that need to load after the reactor
from InputOutput.Charon import Charon

baseurl = os.getcwd()+'/'

if len(sys.argv) > 1 and sys.argv[1] == '-openatlogin':
    globals.appStartedAtBoot = True

# if globals.PLATFORM == 'OSX':
#     import  objc
#     import AppKit
#
Example #23
0
def install_qtreactor(verbose):
    init_qt_app(verbose)
    import qt5reactor
    qt5reactor.install()
Example #24
0
def main(args=None):
    """
    Entrypoint for EPyQ. Initializes the general Qt settings, accepts some command line args,
    and sets up the main GUI window. Final thing to be spun up is the reactor from twisted
    allowing for async functionality with the otherwise single threaded UI.

    Args:
        args (Union[int, float, str], optional): [description]. Defaults to None.
        - verbose: sets the logger level
        - quit-after: sets the time for the duration of the application GUI
        - load-offline: loads only the windows in the device tree denoted as offline from the
        given UI file
    """
    print("starting epyq")

    signal.signal(signal.SIGINT, sigint_handler)

    # TODO: CAMPid 9757656124812312388543272342377
    app = QApplication(sys.argv)
    epyqlib.utils.qt.exception_message_box_register_versions(
        version_tag=epyq.__version_tag__,
        build_tag=epyq.__build_tag__,
    )
    sys.excepthook = functools.partial(
        epyqlib.utils.qt.exception_message_box, )
    QtCore.qInstallMessageHandler(epyqlib.utils.qt.message_handler)
    app.setStyleSheet(
        "QMessageBox {{ messagebox-text-interaction-flags: {}; }}".format(
            Qt.TextBrowserInteraction))
    app.setOrganizationName("EPC Power Corp.")
    app.setApplicationName("EPyQ")

    os_signal_timer = QtCore.QTimer()
    os_signal_timer.start(200)
    os_signal_timer.timeout.connect(lambda: None)

    # TODO: CAMPid 03127876954165421679215396954697
    # https://github.com/kivy/kivy/issues/4182#issuecomment-253159955
    # fix for pyinstaller packages app to avoid ReactorAlreadyInstalledError
    if "twisted.internet.reactor" in sys.modules:
        del sys.modules["twisted.internet.reactor"]

    import qt5reactor

    qt5reactor.install()

    import argparse

    ui_default = "main.ui"

    parser = argparse.ArgumentParser()
    parser.add_argument("--verbose", "-v", action="count", default=0)
    parser.add_argument("--quit-after", type=float, default=None)
    parser.add_argument("--load-offline", default=None)
    if args is None:
        args = parser.parse_args()
    else:
        args = parser.parse_args(args)

    can_logger_modules = ("can", "can.socketcan.native")

    for module in can_logger_modules:
        logging.getLogger(module).setLevel(logging.WARNING)

    if args.verbose >= 1:
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)

    if args.verbose >= 2:
        import twisted.internet.defer

        twisted.internet.defer.setDebugging(True)

    if args.verbose >= 3:
        logging.getLogger().setLevel(logging.DEBUG)

    if args.verbose >= 4:
        logging.getLogger().setLevel(logging.INFO)
        for module in can_logger_modules:
            logging.getLogger(module).setLevel(logging.DEBUG)

    window = Window()
    epyqlib.utils.qt.exception_message_box_register_parent(parent=window)

    window.show()

    if args.quit_after:
        QtCore.QTimer.singleShot(args.quit_after * 1000, app.quit)

    if args.load_offline:

        def load_offline():
            (bus_node, ) = [
                node for node in window.ui.device_tree.model.root.children
                if node.fields.name == "Offline"
            ]

            split = args.load_offline.split("_", maxsplit=1)
            if split[0] == "test":
                path = epyqlib.tests.common.devices[split[1]]
            else:
                path = args.load_offline

            window.ui.device_tree.add_device(
                bus=bus_node,
                device=epyqlib.device.Device(
                    file=path,
                    bus=bus_node.bus,
                    node_id=247,
                ),
            )

        QtCore.QTimer.singleShot(0.5 * 1000, load_offline)

    from twisted.internet import reactor

    reactor.runReturn()
    result = app.exec()
    if reactor.threadpool is not None:
        reactor._stopThreadPool()
        logging.debug("Thread pool stopped")
    logging.debug("Application ended")
    reactor.stop()
    logging.debug("Reactor stopped")

    # TODO: this should be sys.exit() but something keeps the process
    #       from terminating.  Ref T679  Ref T711
    os._exit(result)
Example #25
0
    def __install_twisted(self):

        import qt5reactor
        qt5reactor.install()
Example #26
0
def main(args=None):
    print('starting epyq')

    signal.signal(signal.SIGINT, sigint_handler)

    # TODO: CAMPid 9757656124812312388543272342377
    app = QApplication(sys.argv)
    epyqlib.utils.qt.exception_message_box_register_versions(
        version_tag=epyq.__version_tag__,
        build_tag=epyq.__build_tag__,
    )
    sys.excepthook = functools.partial(
        epyqlib.utils.qt.exception_message_box, )
    QtCore.qInstallMessageHandler(epyqlib.utils.qt.message_handler)
    app.setStyleSheet(
        'QMessageBox {{ messagebox-text-interaction-flags: {}; }}'.format(
            Qt.TextBrowserInteraction))
    app.setOrganizationName('EPC Power Corp.')
    app.setApplicationName('EPyQ')

    os_signal_timer = QtCore.QTimer()
    os_signal_timer.start(200)
    os_signal_timer.timeout.connect(lambda: None)

    # TODO: CAMPid 03127876954165421679215396954697
    # https://github.com/kivy/kivy/issues/4182#issuecomment-253159955
    # fix for pyinstaller packages app to avoid ReactorAlreadyInstalledError
    if 'twisted.internet.reactor' in sys.modules:
        del sys.modules['twisted.internet.reactor']

    import qt5reactor
    qt5reactor.install()

    import argparse

    ui_default = 'main.ui'

    parser = argparse.ArgumentParser()
    parser.add_argument('--verbose', '-v', action='count', default=0)
    parser.add_argument('--quit-after', type=float, default=None)
    parser.add_argument('--load-offline', default=None)
    if args is None:
        args = parser.parse_args()
    else:
        args = parser.parse_args(args)

    can_logger_modules = ('can', 'can.socketcan.native')

    for module in can_logger_modules:
        logging.getLogger(module).setLevel(logging.WARNING)

    if args.verbose >= 1:
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)

    if args.verbose >= 2:
        import twisted.internet.defer
        twisted.internet.defer.setDebugging(True)

    if args.verbose >= 3:
        logging.getLogger().setLevel(logging.DEBUG)

    if args.verbose >= 4:
        logging.getLogger().setLevel(logging.INFO)
        for module in can_logger_modules:
            logging.getLogger(module).setLevel(logging.DEBUG)

    window = Window()
    epyqlib.utils.qt.exception_message_box_register_parent(parent=window)

    window.show()

    if args.quit_after is not None:
        QtCore.QTimer.singleShot(args.quit_after * 1000, app.quit)

    if args.load_offline is not None:

        def load_offline():
            bus_node, = [
                node for node in window.ui.device_tree.model.root.children
                if node.fields.name == 'Offline'
            ]

            split = args.load_offline.split('_', maxsplit=1)
            if split[0] == 'test':
                path = epyqlib.tests.common.devices[split[1]]
            else:
                path = args.load_offline

            window.ui.device_tree.add_device(
                bus=bus_node,
                device=epyqlib.device.Device(
                    file=path,
                    bus=bus_node.bus,
                    node_id=247,
                ),
            )

        QtCore.QTimer.singleShot(0.5 * 1000, load_offline)

    from twisted.internet import reactor
    reactor.runReturn()
    result = app.exec()
    if reactor.threadpool is not None:
        reactor._stopThreadPool()
        logging.debug('Thread pool stopped')
    logging.debug('Application ended')
    reactor.stop()
    logging.debug('Reactor stopped')

    # TODO: this should be sys.exit() but something keeps the process
    #       from terminating.  Ref T679  Ref T711
    os._exit(result)
Example #27
0
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of  MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.
import logging

import qt5reactor
qt5reactor.install()  # noqa

from twisted.internet import reactor

from ..module import Module
from client import ClientFactory

logger = logging.getLogger('IDAConnect.Network')


class Network(Module):
    """
    The network module, responsible for all interactions with the server.
    """
    def __init__(self, plugin):
        super(Network, self).__init__(plugin)
Example #28
0
def install_qt5_reactor():
    import qt5reactor
    qt5reactor.install()
    from twisted.internet import reactor
    return reactor
Example #29
0
            self.plainTextEdit.appendPlainText('You: ' + message)   # Вывод в PlainText, того что ввели.
            self.protocol.sendLine(message.encode())
            self.lineEdit.clear()
            self.lineEdit.setFocus()
        if len(message2) > 0 and len(message3) > 0:
            message2 = "login:"******" password:"******"192.168.0.102",
    1234,
    Connector(window)
)

window.reactor = reactor
reactor.run()
Example #30
0
def install_reactor():
    global app
    app = QApplication(sys.argv)
    import qt5reactor
    qt5reactor.install()
class MultipleClientContainer(QtWidgets.QWidget):
    name = None

    def __init__(self, clientList, reactor):
        QtWidgets.QDialog.__init__(self)
        self.clientList = clientList
        self.reactor = reactor
        self.populateGUI()

    def populateGUI(self):
        self.layout = QtWidgets.QHBoxLayout()
        for client in self.clientList:
            self.layout.addWidget(client)
        self.setFixedSize(230 * len(self.clientList), 120)
        self.setWindowTitle(self.name)
        self.setLayout(self.layout)

    def closeEvent(self, x):
        self.reactor.stop()


if __name__ == '__main__':
    a = QtWidgets.QApplication([])
    import qt5reactor
    qt5reactor.install()
    from twisted.internet import reactor
    widget = IntSpinBox([-100, 100])
    widget.show()
    reactor.run()
Example #32
0
def multi_mode(cli_parsed):
    dbm = db_manager.DB_Manager(cli_parsed.d + '/ew.db')
    dbm.open_connection()
    if not cli_parsed.resume:
        dbm.initialize_db()
    dbm.save_options(cli_parsed)
    m = Manager()
    targets = m.Queue()
    lock = m.Lock()
    multi_counter = m.Value('i', 0)
    display = None

    def exitsig(*args):
        dbm.close()
        if current_process().name == 'MainProcess':
            print ''
            print 'Resume using ./EyeWitness.py --resume {0}'.format(
                cli_parsed.d + '/ew.db')
        os._exit(1)

    signal.signal(signal.SIGINT, exitsig)
    if cli_parsed.resume:
        pass
    else:
        url_list, rdp_list, vnc_list = target_creator(cli_parsed)
        if any((cli_parsed.web, cli_parsed.headless)):
            for url in url_list:
                dbm.create_http_object(url, cli_parsed)
        for rdp in rdp_list:
            dbm.create_vnc_rdp_object('rdp', rdp, cli_parsed)
        for vnc in vnc_list:
            dbm.create_vnc_rdp_object('vnc', vnc, cli_parsed)

    if any((cli_parsed.web, cli_parsed.headless)):
        if cli_parsed.web and not cli_parsed.show_selenium:
            display = Display(visible=0, size=(1920, 1080))
            display.start()

        multi_total = dbm.get_incomplete_http(targets)
        if multi_total > 0:
            if cli_parsed.resume:
                print 'Resuming Web Scan ({0} Hosts Remaining)'.format(
                    str(multi_total))
            else:
                print 'Starting Web Requests ({0} Hosts)'.format(
                    str(multi_total))

        if multi_total < cli_parsed.threads:
            num_threads = multi_total
        else:
            num_threads = cli_parsed.threads
        for i in xrange(num_threads):
            targets.put(None)
        try:
            workers = [
                Process(target=worker_thread,
                        args=(cli_parsed, targets, lock, (multi_counter,
                                                          multi_total)))
                for i in xrange(num_threads)
            ]
            for w in workers:
                w.start()
            for w in workers:
                w.join()
        except Exception as e:
            print str(e)

        # Set up UA table here
        if cli_parsed.cycle is not None:
            ua_dict = get_ua_values(cli_parsed.cycle)
            if not cli_parsed.ua_init:
                dbm.clear_table("ua")
                completed = dbm.get_complete_http()
                completed[:] = [x for x in completed if x.error_state is None]
                for item in completed:
                    for browser, ua in ua_dict.iteritems():
                        dbm.create_ua_object(item, browser, ua)

                cli_parsed.ua_init = True
                dbm.clear_table("opts")
                dbm.save_options(cli_parsed)

            for browser, ua in ua_dict.iteritems():
                targets = m.Queue()
                multi_counter.value = 0
                multi_total = dbm.get_incomplete_ua(targets, browser)
                if multi_total > 0:
                    print(
                        "[*] Starting requests for User Agent {0}"
                        " ({1} Hosts)").format(browser, str(multi_total))
                if multi_total < cli_parsed.threads:
                    num_threads = multi_total
                else:
                    num_threads = cli_parsed.threads
                for i in xrange(num_threads):
                    targets.put(None)
                workers = [
                    Process(target=worker_thread,
                            args=(cli_parsed, targets, lock,
                                  (multi_counter, multi_total), (browser, ua)))
                    for i in xrange(num_threads)
                ]
                for w in workers:
                    w.start()
                for w in workers:
                    w.join()

    if any((cli_parsed.vnc, cli_parsed.rdp)):
        log._LOG_LEVEL = log.Level.ERROR
        multi_total, targets = dbm.get_incomplete_vnc_rdp()
        if multi_total > 0:
            print ''
            print 'Starting VNC/RDP Requests ({0} Hosts)'.format(
                str(multi_total))

            app = QtWidgets.QApplication(sys.argv)
            timer = QTimer()
            timer.start(10)
            timer.timeout.connect(lambda: None)

            # add qt5 reactor
            import qt5reactor
            qt5reactor.install()
            from twisted.internet import reactor

            for target in targets:
                if os.path.dirname(cli_parsed.d) != os.path.dirname(
                        target.screenshot_path):
                    target.set_paths(cli_parsed.d)
                tdbm = db_manager.DB_Manager(cli_parsed.d + '/ew.db')
                if target.proto == 'vnc':
                    reactor.connectTCP(
                        target.remote_system, target.port,
                        vnc_module.RFBScreenShotFactory(
                            target.screenshot_path, reactor, app, target,
                            tdbm))
                else:
                    reactor.connectTCP(
                        target.remote_system, int(target.port),
                        rdp_module.RDPScreenShotFactory(
                            reactor, app, 1200, 800, target.screenshot_path,
                            cli_parsed.timeout, target, tdbm))
            reactor.runReturn()
            app.exec_()

    if display is not None:
        display.stop()
    results = dbm.get_complete_http()
    vnc_rdp = dbm.get_complete_vnc_rdp()
    dbm.close()
    m.shutdown()
    write_vnc_rdp_data(cli_parsed, vnc_rdp)
    sort_data_and_write(cli_parsed, results)
    if cli_parsed.ocr:
        for target in targets:
            try:
                rdp_module.parse_screenshot(cli_parsed.d, target)
            except IOError:
                pass