Exemplo n.º 1
0
def main():
    config = Configuration()
    monitor = Monitor()

    monitor.Monitor()

    sleeptimer = float(config.sleeptimer)
    time.sleep(sleeptimer)
Exemplo n.º 2
0
    def sensorAppInit(self):

        # Initialize variables we need
        self.currentSensor = 1

        self.function_indicator = {
            1: self.ui.led_sensor,
            2: self.ui.led_temp,
            3: self.ui.led_hum,
            4: self.ui.led_t_alarm,
            5: self.ui.led_h_alarm
        }

        self.functionNumber = 1

        self.displayCelcius = False

        # Initialize the state of the UI
        self.ui.screen_output.setText("INITIALIZING")

        # Initialize UI timer for updates
        self.timer = QTimer()

        # Create instance of monitor class
        self.monitor = Monitor()

        # Register functions to corresponding event
        self.ui.pb_select.released.connect(self.select_button)
        self.ui.pb_up.released.connect(self.up_button)
        self.ui.pb_down.released.connect(self.down_button)
        self.ui.pb_convertTemp.released.connect(self.convertTemp_button)
        self.timer.timeout.connect(self.read_data)
        self.timer.start(10000)
    def addAgent(self, idAgent, hostname, version, port, comunity):
        if idAgent in self.pool:
            return False

        tiempo_actual = int(time.time())

        newAgent = {
            'idAgent': idAgent,
            'hostname': hostname,
            'version': version,
            'port': port,
            'comunity': comunity,
            'time': tiempo_actual
        }

        t = Monitor(newAgent)
        self.pool.update({idAgent: t})
        t.start()

        self.data['agents'].append(newAgent)
        with open('agents.json', 'w') as f:
            json.dump(self.data, f)

        crearBases(idAgent)

        return True
 def get_result(self):
     result = {}
     all_insts = {}
     cmd = "arm-linux-gnueabi-objdump -d " + self.bin_path + " > " + self.bin_path + ".raw"
     monitor = Monitor("arm-linux-gnueabi-objdump", self.bin_path,
                       self.monitor_time, ".objdump")
     monitor.start()
     print "Objdump get the result of  %s" % self.bin_path
     os.system(cmd)
     monitor.join()
     print "Objdump finish the result of %s" % self.bin_path
     result["instruction"] = {}
     f = open(self.bin_path + ".raw", "r")
     lines = f.readlines()
     f.close()
     for l in lines:
         l_split = l.split("\t")
         if l_split < 4:
             continue
         if l_split[0].endswith(":") and ".word" not in l:
             insn = int(l_split[0].strip()[:-1], 16)
             size = len(l_split[1].strip()) / 2
             disasm = " ".join(l_split[2:])
             all_insts[insn] = {}
             all_insts[insn]["size"] = size
             all_insts[insn]["disasm"] = disasm
     result["instruction"]["detail"] = all_insts
     return result
Exemplo n.º 5
0
def calChangedCB(gcal):
    '''Callback for calendar change from reciever'''
    print("Detected calendar changed.")
    mo_temp = []
    for component in gcal.walk():
        if component.name == "VEVENT":
            summary = component.get('summary')
            start_time = component.get('dtstart').dt
            end_time = component.get('dtend').dt
            time_delta = end_time - start_time

            # Create Cron Job base on schedule
            seconds = time_delta.total_seconds()
            comm0 = calendarParser.COMM + " " + summary + " " + str(seconds)

            # create new Monitor
            job = Monitor(0, comm0, start_time)
            mo_temp.append(job)

    print(utils.MONITORS)
    for mo in utils.MONITORS:
        mo.stop()

    utils.MONITORS = []
    timezone = pytz.timezone("US/Eastern")
    print mo_temp
    for mo in mo_temp:
        if mo.dt < timezone.localize(datetime.now()):
            continue
        utils.MONITORS.append(mo)
    for mo in utils.MONITORS:
        mo.start()
Exemplo n.º 6
0
def scheduleEvent(gcal, comm):
    ''' Get all details of all scheduled VEVENTs'''

    # initialize scheduler for events
    s = sched.scheduler(time.time, time.sleep)
    timezone = pytz.timezone("US/Eastern")

    for component in gcal.walk():
        if component.name == "VEVENT":
            summary = component.get('summary')
            start_time = component.get('dtstart').dt
            end_time = component.get('dtend').dt
            time_delta = end_time - start_time

            # Create Cron Job base on schedule
            seconds = time_delta.total_seconds()
            #seconds = seconds % 60
            comm0 = COMM + " " + summary + " " + str(seconds)

            # create new Monitor
            if start_time < timezone.localize(datetime.now()):
                continue
            job = Monitor(s, comm0, start_time)
            utils.MONITORS.append(job)
            # createCronJob(comm0, start_time)
            # scheduleJob(comm0, start_time, s)

    # t = threading.Thread(target=s.run)
    # t.start()
    for mo in utils.MONITORS:
        mo.start()
Exemplo n.º 7
0
    def test_real_init_workflow(self, buildSensor, buildReporter):
        config = '''
        {
            "reporters":[
                "reporter1",
                "reporter2"
            ],
            "sensors":[
                "sensor1",
                "sensor2",
                "sensor3"
            ]
        }
        '''
        monitor = Monitor(json.loads(config))

        self.assertIs(len(monitor.getReporters()), 2)
        buildReporter.assert_has_calls(
            [mock.call('reporter1'),
             mock.call('reporter2')])

        self.assertIs(len(monitor.getSensors()), 3)
        buildSensor.assert_has_calls([
            mock.call('sensor1', monitor.sensorTrigger),
            mock.call('sensor2', monitor.sensorTrigger),
            mock.call('sensor3', monitor.sensorTrigger)
        ])
    def __init__(self):
        """ 
            On initialisation the MonitorAndNotify class reads the current data and inserts into the datbase every minute 
            and only sends a notification once a day
        
        """

        # Scheduler = Schedule()
        # Instantiate all relevant classes
        data = DataLogger()
        dataManager = DatabaseManager(data)
        monitor = Monitor()
        weather = Weather(data, dataManager, monitor)
        sense = VirtualSenseHat.getSenseHat()

        # Scheduler.createSchedule()

        # verify if the temperature is within the range
        weather.verifyTemperature()
        # verify if the humidity is within the range
        weather.verifyHumidity()

        # close the connection to the database
        dataManager.closeDBConnection()

        # clear anything displayed on the sense hat
        sense.clear()
Exemplo n.º 9
0
def SetupMonitors():
    # Setup manager
    entityManager = EntityManager(config)

    # If I have not a list of monitors, I setup only a monitor
    if (consts.CONFIG_MONITORS_KEY not in config):
        monitor = Monitor(config, config, entityManager)
    else:  # More Monitors
        # Now setup monitors
        monitor_id = 0
        for monitor_config in config[consts.CONFIG_MONITORS_KEY]:
            monitor_id += 1
            monitor = Monitor(monitor_config, config, entityManager,
                              monitor_id)

    # Start sensors loop
    entityManager.Start()
Exemplo n.º 10
0
    def get(self, controller, redis_address):
        """
        Get a new reality capture scheduler

        :param controller: AgentController client instance.
        :param redis_address: Address of the redis instances that the jumpscripts will use to report stats and logs

        :return: Scheduler
        """
        return Monitor(controller, redis_address)
Exemplo n.º 11
0
def handle_args(port, baudrate, timeout, page_dir, debug):
    """Load config and arguments, (arguments have precidence)"""

    # Remove the default logger and add one with a log level we set
    logger.remove(0)
    logger.start(sys.stderr, level=("DEBUG" if debug else "INFO"))
    logger.info("Starting NASMon...")
    
    mon = Monitor(port, baudrate, timeout, page_dir)
    mon.start()
Exemplo n.º 12
0
def listen(ctx, verbose, home_id):
    """
    Passive monitoring of network
    :param ctx: shared context
    :param verbose: show received frames
    :param home_id: filter frames including specified home-id
    """
    # initialize
    signal.signal(signal.SIGINT, signal_handler)
    cfg = ctx.obj[CONFIGURATION]
    cfg.home_id = home_id
    cfg.verbose = verbose
    honeylog = ctx.obj[LOGGER]

    with multiprocessing.Manager() as manager:
        # initialize shared network and decoy information
        network = manager.dict(load_json(cfg.networks_path + '/' + cfg.network_file))
        decoys = manager.dict(load_json(cfg.networks_path + '/' + cfg.decoys_file))

        # init stats
        inner_stats = init_stats_dict()
        stats_real = manager.dict(inner_stats.copy())
        stats_malicious = manager.dict(inner_stats.copy())
        stats_invalid = manager.dict(inner_stats.copy())
        stats_in = manager.dict(inner_stats.copy())
        stats_out = manager.dict(inner_stats.copy())

        stats = {STAT_REAL: stats_real,
                 STAT_MALICIOUS: stats_malicious,
                 STAT_INVALID: stats_invalid,
                 STAT_IN: stats_in,
                 STAT_OUT: stats_out}

        frames_in = list()
        frames_out = list()

        # initialize components
        receiver = Receiver(cfg, network, decoys, honeylog, frames_in, frames_out)
        monitor = Monitor(cfg, network, decoys, honeylog, stats)

        receiver.monitor = monitor
        monitor.receiver = receiver

        # start configuration
        configuration_process = Process(target=set_configuration, args=(cfg, honeylog))
        configuration_process.start()

        # if not verbose
        if not verbose:
            # show only stats
            statsview_process = Process(target=stats_view, args=(stats, ctx.obj[DEBUG_LEVEL]))
            statsview_process.start()

        # start reception
        receiver.start(False, True)
Exemplo n.º 13
0
def manage():
    # 新建任务
    global process_list
    logger.debug("任务个数 " + str(len(config["monitor"]["tasks"])))
    for task in config["monitor"]["tasks"]:
        p = Monitor(task)
        process_list.append(p)
        p.start()
        logger.debug("开始任务 " + repr(p) + " " + repr(task))

    return
Exemplo n.º 14
0
    def check_new_executor(self, executor_id):
        """
            The function checks if that executor already has a monitor, if he doesn't creates him one.
        """

        # Check if it's a new executor so he doesn't have a monitor.
        if not executor_id in self.executors_monitors:

            # Create the monitor.
            self.executors_monitors[executor_id] = Monitor(
                self, self.executors_count)
Exemplo n.º 15
0
    def refresh_monitors(self):
        """
            The function is being called when a changes has been made an the monitors structure should get changed.
        """

        # If True that executor is the only one to get a window.
        if len(self.executors_monitors) == 1:
            pass
            # # Set the panel of the executor to the panel of the single monitor.
            # self.one_monitor_panel = self.executors_monitors.values()[0]

            # # Set the sizer of the monitors window to the single monitor panel.
            # self.SetSizer(self.one_monitor_panel_sizer)

        else:

            left_panel = Monitor(self.splitter, 0)
            right_panel = Monitor(self.splitter, 1)

            self.splitter.SplitVertically(left_panel, right_panel)
Exemplo n.º 16
0
    def test_sensor_trigger(self, reporter_send):
        reporter = Reporter(json.loads('{ "id": "testReporter" }'))
        monitor = Monitor(self.EMPTY_CONFIG)
        monitor.reporters.append(reporter)

        events = monitor.sensorTrigger('testSensor')

        for event in events:
            event.wait()

        reporter_send.assert_called_once_with(
            'Sensor testSensor was triggered!', events[0])
Exemplo n.º 17
0
def record(ctx):
    """Records frames until users interrupt"""
    configuration = ctx.obj[CONFIGURATION]
    logger = ctx.obj[LOGGER]
    network = load_json(configuration.networks_path + '/' +
                        configuration.real_networks_name)
    decoys = load_json(configuration.networks_path + '/' +
                       configuration.virtual_networks_name)
    receiver = Receiver(configuration, network, decoys, logger, None, None)
    monitor = Monitor(configuration, network, decoys, logger, None, receiver)
    receiver.monitor = monitor
    monitor.record()
Exemplo n.º 18
0
    def setUp(self):
        self.patches = []
        self.emails = []
        patch = mock.patch('smtplib.SMTP.sendmail',
                           side_effect=self.append_email)
        patch.start()
        self.patches.append(patch)

        rpi.set_pin_state(26, 0)
        config_file = 'etc/config/HomeMonitor.cfg'

        self.monitor = Monitor(util.config.importConfig(config_file))
    def __init__(self):
        self.data = {}
        self.data['agents'] = []
        self.pool = {}

        if os.path.exists('agents.json'):
            with open('agents.json', 'r') as f:
                self.data = json.load(f)
            for agent in self.data['agents']:
                t = Monitor(agent)
                self.pool.update({agent['idAgent']: t})
                t.start()
Exemplo n.º 20
0
def SetupMonitors():

    # Setup managers
    commandManager = Managers.CommandManager(config)
    sensorManager = Managers.SensorManager(config)
    # Link them
    commandManager.SetSensorManager(sensorManager)
    sensorManager.SetCommandManager(commandManager)

    # If I have not a list of monitors, I setup only a monitor
    if ('monitors' not in config):
        monitor = Monitor(config, config, commandManager, sensorManager)
    else:  # More Monitors
        # Now setup monitors
        monitor_id = 0
        for monitor_config in config['monitors']:
            monitor_id += 1
            monitor = Monitor(monitor_config, config, commandManager,
                              sensorManager, monitor_id)

    # Start sensors loop
    sensorManager.Start()
Exemplo n.º 21
0
    def __init__(self):
        self.__database = Database()
        self.__monitor = Monitor()

        self.__minTemperature = self.__monitor.getMinTemperature()
        self.__maxTemperature = self.__monitor.getMaxTemperature()
        self.__minHumidity = self.__monitor.getMinHumidity()
        self.__maxHumidity = self.__monitor.getMaxHumidity()

        self.__arrayOfDates = self.__database.getDates()
        self.__avgTemperature = None
        self.__avgHumidity = None
        self.__status = "some status"
        self.__message = "some message"
Exemplo n.º 22
0
def run():

    # the event for getting players actions
    player_action_received = threading.Event()
    player_action_received.set()

    # monitor is the GUI
    monitor = Monitor(player_action_received)

    # game is the manager
    game = Game(monitor, player_action_received)
    manager_thread = threading.Thread(target=game.start)
    manager_thread.start()

    # making the GUI appear
    monitor.start()
Exemplo n.º 23
0
def rebootServer():
    global monitor

    print("Loading data...")

    loadObjects()
    loadSettings()
    saveSettings()

    if (monitor != None):
        monitor.stop()
        del monitor

    monitor = Monitor(serverSettings['tempSensorGPIO'],
                      serverSettings['envUpdateMemory'],
                      serverSettings['envUpdatePeriod'])
    monitor.start()
Exemplo n.º 24
0
def web():
    M = Monitor()
    try:
        html = """
        <style>
            table {
                border-collapse: collapse;
            }
            th, td {
                vertical-align: top;
                border: 1px solid black;
            }
            .mode-watch {
                background: #ffa;
            }
            .mode-blacklist {
                background: #fcc;
            }
        </style>
        <table>
        <tr>
            <th>wiki</th>
            <th>id</th>
            <th>name</th>
            <th>mode</th>
        </tr>
        """
        M.cur.execute(
            """SELECT `af_id`, `af_name`, `mode`, `wiki` FROM `abusefilter` ORDER BY `wiki` ASC, `af_id` ASC"""
        )
        rows = M.cur.fetchall()
        for row in rows:
            html += """
                <tr class="mode-{2}">
                    <td>{3}</td>
                    <td>{0}</td>
                    <td>{1}</td>
                    <td>{2}</td>
                </tr>
                """.format(row[0], row[1], row[2], row[3])
        html += '</table>'
        return html
    except Exception:
        M.error(traceback.format_exc())
        return "OK1"
Exemplo n.º 25
0
    def __init__(self):
        """
            On initialisation the BluetoothManager class retrieves the temperature ranges from the Monitor Class
        """

        #declare variables that handle interactions with other classes
        self.__monitor = Monitor()
        self.__notifier = Notification()

        #declare variables that will store the head and message that will be sent via pushbullet
        self.__head = None
        self.__message = None

        #declare variables the store the ranges from the Monitor class using the classes methods
        self.__minTemperature = self.__monitor.getMinTemperature()
        self.__maxTemperature = self.__monitor.getMaxTemperature()
        self.__minHumidity = self.__monitor.getMinHumidity()
        self.__maxHumidity = self.__monitor.getMaxHumidity()
Exemplo n.º 26
0
def web():
    M = Monitor()
    try:
        html = """
        <style>
            table {
                border-collapse: collapse;
            }
            th, td {
                vertical-align: top;
                border: 1px solid black;
            }
        </style>
        status
        <a href="./log?type=log">log</a>
        <a href="./blacklist">blacklist</a>
        <table>
        <tr>
            <th>database</th>
            <th>last time</th>
        </tr>
        """
        for table in tables:
            M.cur.execute("""SELECT MAX(`timestamp`) FROM """ + table)
            rows = M.cur.fetchall()
            if rows[0][0] is None:
                html += """
                    <tr>
                        <td>{}</td>
                        <td>No record</td>
                    </tr>
                    """.format(table)
            else:
                html += """
                    <tr>
                        <td><a href="{0}log?type={1}" target="_blank">{1}</td>
                        <td>{2}</td>
                    </tr>
                    """.format(M.siteurl, table, M.formattimediff(rows[0][0]))
        html += '</table>'
        return html
    except Exception:
        M.error(traceback.format_exc())
        return "OK1"
	def addAgent(
		self, idAgent, hostname, version, port, comunity,
		ramReady, ramSet, ramGo,
		cpuReady, cpuSet, cpuGo,
		hddReady, hddSet, hddGo

	):
		if idAgent in self.pool:
			return False

		tiempo_actual = int(time.time())		

		newAgent = {  
		    'idAgent': idAgent,
		    'hostname': hostname,
		    'version': version,
		    'port': port,
		    'comunity': comunity,
		    'time': tiempo_actual,
		    'ramReady': ramReady,
		    'ramSet': ramSet,
		    'ramGo': ramGo,
		    'cpuReady': cpuReady,
		    'cpuSet': cpuSet,
		    'cpuGo': cpuGo,
		    'hddReady': hddReady,
		    'hddSet': hddSet,
		    'hddGo': hddGo
		}

		t = Monitor(newAgent)
		self.pool.update({idAgent: t})
		t.start()

		self.data['agents'].append(newAgent)
		with open('agents.json', 'w') as f:
		    json.dump(self.data, f)

		crearBases( idAgent )	
		crearBasesLb( comunity, hostname, port, idAgent )		

		return True
Exemplo n.º 28
0
def start():
    if len(sys.argv[1:]) == 0:
        config = utils.load_config()
    else:
        config = utils.load_config(sys.argv[1])
    logger = utils.get_logger()
    logger.info('BiliLive Link Start!!!')
    room_count = len(config['ROOM_URLS'])
    if room_count == 0:
        logger.info('No Live Room Found,Exit Now!')
        exit(0)
    pool = ThreadPool(room_count)
    for room_url in config['ROOM_URLS']:
        m = Monitor(room_url)
        pool.apply_async(m.run)
    pool.close()
    try:
        pool.join()
    except KeyboardInterrupt:
        logger.warning('Rua!')
        exit(1)
    def addAgent(self, idAgent, hostname, version, port, comunity):
        if idAgent in self.pool:
            return False

        newAgent = {
            'idAgent': idAgent,
            'hostname': hostname,
            'version': version,
            'port': port,
            'comunity': comunity
        }

        t = Monitor(newAgent)
        self.pool.update({idAgent: t})
        t.start()

        self.data['agents'].append(newAgent)
        with open('agents.json', 'w') as f:
            json.dump(self.data, f)

        return True
Exemplo n.º 30
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        # 设置背景透明
        # self.setAttribute(Qt.WA_TranslucentBackground)
        # 设置无边框样式
        self.setWindowFlags(Qt.FramelessWindowHint)
        # 设置背景颜色
        # self.setStyleSheet('QWidget{background-color:blue}')
        # 信号槽
        self.actionMaximize.triggered.connect(self.showMaximized)
        self.actionMinimize.triggered.connect(self.showMinimized)
        self.actionDefault.triggered.connect(self.showNormal)

        self.playButton.clicked.connect(self.play_pause)
        self.positionslider.sliderMoved.connect(self.set_position)
        self.positionslider.sliderPressed.connect(self.set_position)
        self.volumeslider.valueChanged.connect(self.set_volume)
        self.soundButton.clicked.connect(self.set_mute)
        self.getStatusButton.clicked.connect(self.setStatus)
        # vlc
        self.instance = vlc.Instance()
        self.media = None
        self.mediaplayer = self.instance.media_player_new()
        self.is_paused = False
        self.is_urlplay = False
        self.original_valume = 0
        # self.mediaplayer.set_fullscreen(True)
        # self.fullscreenButton.clicked.connect(self.set_fscreen)
        # timer
        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(100)  # 设置更新时间为100ms
        self.timer.timeout.connect(self.update_ui)
        self.cnt = 0
        # 鼠标
        self.m_flag = False
        # 声音
        self.volumeslider.setValue(self.mediaplayer.audio_get_volume())
        # 监控
        self.monitor = Monitor()