def on_connect(self, obj): try: local_port = self.ent_port.get_text() tunnel = None if self.ent_remote_host.get_text(): tunnel = SSHTunnelForwarder( self.ent_remote_host.get_text(), ssh_username=self.ent_remote_user.get_text(), ssh_pkey=self.file_remote_key.get_filename(), remote_bind_address=('127.0.0.1', int(self.ent_port.get_text()))) tunnel.start() local_port = tunnel.local_bind_port conn = psycopg2.connect(database=self.ent_database.get_text(), user=self.ent_user.get_text(), host=self.ent_host.get_text(), port=local_port, password=self.ent_password.get_text()) QueryWindow(conn, tunnel) WindowManager.remove(self.window) self.window.destroy() except SSHException as e: print e Alert('Unable to create SSH tunnel', self.window) except Exception as e: print e Alert('Unable to connect to server.', self.window)
def on_save(self, passphrase, repeat_passphrase): # if store.get("mnemonic"): # print ("Mnemonic exists") # print (store.get("mnemonic")) # return if passphrase.text != repeat_passphrase.text or not passphrase.text: Alert(title='Error message', text='Passphrases must match') return if len(passphrase.text) < 8: Alert(title='Error message', text='Passphrases must be at least 8 characters long') return if not self.mnemonic: Alert(title='Error message', text='PLease generate a New mnemonic') return scrypt_key, salt = generate_scrypt_key(passphrase.text) encrypted_mnemonic = aes_encrypt(scrypt_key, self.mnemonic) store.put("mnemonic", value=encrypted_mnemonic.hex(), salt=salt.hex()) print(store.get("mnemonic")) self.go_to_login() return
def test_alert(stats_good, stats_bad): a = Alert(stats_good, 1, 'test') a.do_work() assert (a.flag_alert is False) b = Alert(stats_bad, 1, 'test') b.do_work() assert (b.flag_alert is True)
def DelTargetRequest(self, request, context): try: target_file = File(self._target_file) target_file_content = target_file.open_file() fild_sd = FileSD(target_file_content) alert_file = File(self._alert_file) alert_file_content = alert_file.open_file() alerts = Alert(alert_file_content) fild_sd.del_target(vnf_id=request.vnf_id) target_file.write_to_file(str(fild_sd)) alerts.delete_rule(vnf_id=request.vnf_id) alert_file.write_to_file(str(alerts)) response = service_pb2.MonitorReply(message="", status=1) r = requests.post("http://127.0.0.1:9090/-/reload") print("Target deleted") return response except: traceback.print_exc(file=sys.stdout) response = service_pb2.MonitorReply(message="Unexpected error:", status=1) return response
def NewTargetRequest(self, request, context): try: target_file = File(self._target_file) target_file_content = target_file.open_file() fild_sd = FileSD(target_file_content) alert_file = File(self._alert_file) alert_file_content = alert_file.open_file() alerts = Alert(alert_file_content) for vdu in request.vdus: fild_sd.add_new_target(vdu, request.vnf_id) alerts.add_new_rule(alerts=vdu.alerts, vnf_id=request.vnf_id, vdu_name=vdu.vdu_name) target_file.write_to_file(str(fild_sd)) alert_file.write_to_file(str(alerts)) # Reload prometheus configuration r = requests.post("http://127.0.0.1:9090/-/reload") print("New target created") response = service_pb2.MonitorReply(message="", status=1) return response except: traceback.print_exc(file=sys.stdout) response = service_pb2.MonitorReply(message="Unexpected error:", status=1) return response
def _button_Create_clicked(self): saveDir = self.ui.lineEdit_BookPath.text() bookTitle = self.ui.lineEdit_BookTitle.text() author = self.ui.lineEdit_Author.text() publisher = self.ui.lineEdit_Publisher.text() readBy = self.ui.lineEdit_ReadBy.text() if saveDir and bookTitle: logging.debug(saveDir + ":" + bookTitle) self.switch_window.emit({"saveDir": saveDir, "bookTitle": bookTitle, "author": {"type": "Person", "name": author}, "publisher": publisher, "readBy": {"type": "Person", "name": readBy}}) else: self.mask = MaskWidget(self) self.mask.show() self.alert = Alert(self._translate("CreateNewWizard", "You must select one directory and" " keyin the booktitle!"), self._translate("CreateNewWizard", "Warning!")) self.alert.move( self.geometry().x() + self.geometry().width() / 2 - self.alert.geometry().width() / 2, self.geometry().y() + self.geometry().height() / 2 - self.alert.geometry().height() / 2) result = self.alert.exec_() self.mask.close()
def create_task(self, task_name): doc_name = input(Alert().messages['document_name']) path = self.path(doc_name) if path.exists(): _id = self.generate_task_id(doc_name) read_text = self.is_there_content( path.read_text() ) new_content = f'{read_text}{_id} - {task_name} - {datetime.datetime.now()}' path.write_text(new_content) print(Alert().messages['task_created']) else: create_document = input(Alert().messages['do_you_wanna_create_it']) if create_document.upper() == 'Y' or len(create_document) == 0: self.create_document(doc_name).write_text(f'{1} - {task_name} - {datetime.datetime.now()}') print(Alert().messages['task_created'])
def testICMP(config): db = Database(config) alert = Alert(db, config) ping = Ping() ping.thread_count = int(config.get('Config', 'config.numthreads')) while True: logger.info("Start test ICMP: %s" % time.ctime()) #Get hots hosts = list(db.getHostsActive()) if hosts: #test hosts tests = list(ping.start(list(hosts))) #Process old alerts with new alerts and send messages alert.procAlerts(tests) else: #Check if exist alerts when database is empty. If exist, clean all. flag, alerts = db.getAlert() if flag: for alert in alerts: flag, result = self.db.delAlert(alert[0]) if not flag: self.logger.info( 'I could not delete alerts %s, error %s' % (str(alert[0]), result)) else: self.logger.info('I could not get alerts: %s' % (alerts)) #Uncomment to sleep a while #time.sleep( 30 ) logger.info("End test ICMP: %s" % time.ctime())
def _parse_config(self, xml_config): logging.info('Hawkeye: Parsing config') clients = [] parsed = xmltodict.parse(xml_config) clients_config = parsed['root']['client'] for client in clients_config: ip_address = client['@ip'] port = int(client['@port']) username = client['@username'] password = client['@password'] email = client['@mail'] alerts = [] alerts_db_array = [] for alert_config in client['alert']: alerts.append(Alert(alert_config['@type'], alert_config['@limit'])) alerts_db_array.append([alert_config['@type'], alert_config['@limit']]) client_instance = self.db_driver.retrieve('hawkeye_db', 'clients', 'ip_address', ip_address) print('client_instance', client_instance) if client_instance is None: data = { 'ip_address': ip_address, 'port': port, 'username': username, 'password': password, 'email': email, 'alerts': alerts_db_array } clients.append(Client(ip_address, port, username, password, email, alerts)) return clients
def get_alerts(self): ''' Public method that parses ''' emptyfeed = "There are no active watches, warnings or advisories" alerts = [] if emptyfeed in str(self._raw_cap): pass else: main_dom = minidom.parseString(self._raw_cap) xml_entries = main_dom.getElementsByTagName('entry') # title is currently first so we can detect an empty cap feed for dom in xml_entries: #parse the entry to a temp 'entry' dict entry = self._parse_entry(dom) # perform some cleanup before creating an object #entry['locations'] = self.build_locations(entry) # FIXME: remove? entry['target_areas'] = self.build_target_areas(entry) alert = Alert(entry) alerts.append(alert) del entry del alert return alerts
def refresh_data(self): self.store.clear() query = 'SELECT * FROM %s' % self.table if self.where: query += ' WHERE %s' % self.where if self.order: query += ' ORDER BY %s %s' % (self.order, self.order_direction) query += ' LIMIT %s OFFSET %s' % (self.row_size, self.page * self.row_size) try: cursor = self.conn.cursor() cursor.execute(query) self.conn.commit() for row in cursor.fetchall(): data = [] for i, val in enumerate(row): if self.columns[i](val) == 'None': data.append(None) else: data.append(self.columns[i](val)) self.store.append(data) except DatabaseError as e: Alert(e.message, self.data_tree.get_toplevel()) self.conn.rollback() self.data_tree.show_all()
def __init__(self, access_token=None): self.digital_ocean = access_token self.report = "" config_file = open("config.json", "r") self.backup_data = json.load(config_file) self.alert = Alert(self.backup_data["femail"], self.backup_data["temail"])
def test_send_email_mock(self): self.mon.mailer = Mock() self.mon.mailer.send.return_value = {} self.assertTrue(self.mon.send_email(Alert("test", "msg"))) # assert ensure_wifi_mock.called assert self.mon.mailer.login.called assert self.mon.mailer.send.called assert self.mon.mailer.close.called
def test_send_email_mock_failed_send_false(self): self.mon.ensure_wifi = Mock() self.mon.mailer = Mock() self.mon.mailer.send.return_value = False self.assertFalse(self.mon.send_email(Alert("test1", "msg1"))) assert self.mon.mailer.login.called assert self.mon.mailer.send.called assert self.mon.mailer.close.called
def test_send_email_mock_failed_login(self): self.mon.ensure_wifi = Mock() self.mon.mailer = Mock() self.mon.mailer.login.side_effect = socket.gaierror self.assertFalse(self.mon.send_email(Alert("test1", "msg1"))) assert self.mon.mailer.login.called assert self.mon.mailer.login.not_called assert self.mon.mailer.close.called
def on_text_edit(self, widget, row, text, column_num): if self.data_tree.get_column(0).get_title() != 'id': Alert( 'Unable to update because we can\'t handle a missing ID column. TODO fix this' ) self.store[row][column_num] = text column = self.data_tree.get_column(column_num) column_name = column.get_title().replace('__', '_') try: cursor = self.conn.cursor() cursor.execute('UPDATE %s SET %s=\'%s\' WHERE id=%s' % (self.table, column_name, text, self.store[row][0])) self.conn.commit() except DatabaseError as e: Alert(e.message, self.data_tree.get_toplevel()) self.conn.rollback()
def read_document(self, doc_name): path = self.path(doc_name) if not path.exists(): print(Alert().messages['document_does_not_exist']) return False else: print(path.read_text()) return True
async def create_alert(user): ''' Creates a scheduled alert from user input ''' alert = Alert(user["name"], user["alert"][0], user["alert"][1], user["alert"][2], user["alert"][3]) db["Alerts"].append(alert)
def run_pressed(self, instance): try: screen_recorder.enable_log() fps_inspector.enable_fliprate_log() ready = True if self.pid.text: self.pid_value = int(self.pid.text) screen_recorder.init_resources(self.pid_value) self.game_inspector.config.pid = self.pid_value self.game_inspector.config.use_overlay = False elif self.process_path.text: game_overlay_sdk.injector.enable_monitor_logger() if self.steam_app_id.text: game_overlay_sdk.injector.run_process( self.process_path.text, '', int(self.steam_app_id.text)) else: game_overlay_sdk.injector.run_process( self.process_path.text, '', None) self.pid_value = game_overlay_sdk.injector.get_pid() screen_recorder.init_resources(self.pid_value) self.game_inspector.config.pid = self.pid_value self.game_inspector.config.use_overlay = True elif self.process_name.text: game_overlay_sdk.injector.enable_monitor_logger() game_overlay_sdk.injector.start_monitor(self.process_name.text) # wait for process creation Alert(title='Waiting for process with name %s' % self.process_name.text, text='now you need to start target process manually', condition=self.check_pid) else: Alert( title='Invalid input', text= 'nor PID nor Process Name nor Process Path were specified') ready = False if ready: self.register_callbacks() self.screen_manager.current = 'GameInspector' except Exception as e: Alert(title='Excpetion occured', text=str(e)) raise e
def delete_task(self, doc_name): if self.read_document(doc_name): path = self.path(doc_name) task_id = input(Alert().messages['task_id']) # It's neccesary to select a task id with path.open() as f: memory_tasks = { f"{fl.split('-')[0].strip()}": fl for fl in f.readlines() } if task_id in memory_tasks: memory_tasks.pop(task_id) new_content = '' for task in memory_tasks: new_content += memory_tasks[task] path.write_text(new_content) print(Alert().messages['task_deleted']) else: print(Alert().messages['task_no'])
def __init__(self): self.id = "1" self.name = "Indoor Temperature" self.unit = "C" self.type = "wt" self.virtual = 0 self.context = "Environment" self.system = "Test" self.enabled = True self.value = None self.alert = Alert(self.id)
def __init__(self, cfg): self.workbook = xlwt.Workbook(encoding='utf-8') self.tablespace_sheet = Tablespace(self.workbook) self.db_lock_sheet = DbLock(self.workbook) self.archive_sheet = Archive(self.workbook) self.cpu_sheet = CPU(self.workbook) self.memory_sheet = Memory(self.workbook) self.disk_use_sheet = DiskUse(self.workbook) self.disk_busy_sheet = DiskBusy(self.workbook) self.alert_sheet = Alert(self.workbook) self.ogg_sheet = OGG(self.workbook) self.cfg = cfg
def do_login(self, loginText, passwordText): app = App.get_running_app() print (app.get_application_config()) app.username = loginText print ("This is the password text %s"%passwordText) app.password = hashlib.sha256(passwordText.encode("utf-8")).hexdigest() print (app.password) if app.username == "" or app.password == "": Alert(title='Feynmen error message', text='username and password cannot be left blank') return if store.exists("credentials"): username = store["credentials"].get('username') password = store["credentials"].get('password') #stored passwill will be sha3_256 print ("Credentials found in the store", username, password) else: #TODO: Make an api request here username = "******" password = hashlib.sha256("1234".encode("utf-8")).hexdigest() print ("This is the password we are storing %s"%password) store.put("credentials", username=username, password=password) if app.username == username and app.password == password: self.manager.transition = SlideTransition(direction="left") self.manager.current = 'User' else: Alert(title='Feynmen error message', text='username and password entered are invalid') return app.config.read(app.get_application_config()) app.config.write()
def temp_alert(self, data): """ Method that instantiates Alert object and calls its method for sending alert email to a specified address. :param data: Data about the state of the instrument :type data: dict :return: :rtype: NoneType """ alert = Alert(self.settings["receiver"], self.settings["sender"], self.settings["username"], self.settings["password"]) sleep(5) alert.send_msg(*alert.format_temperature_alert_msg(data))
def dashboard(): """Primary dashboard the users will interact with.""" logger.info("User authenticated proceeding to dashboard.") AppFetcher().sync_config_and_images() user = User(session) alerts = Alert(user, app).get() all_apps = Application().apps apps = user.apps(all_apps)['apps'] return render_template('dashboard.html', user=user, apps=apps, alerts=alerts)
def do_login(self, passwordText): app = App.get_running_app() print (app.get_application_config()) if app.password == "": Alert(title='Error messege', text='Password cannot be left blank') return encrypted = store.get("mnemonic") encrypted_mnemonic = encrypted["value"] salt = encrypted["salt"] scrypt_key, salt = generate_scrypt_key(passwordText, bytes.fromhex(salt)) print (f"scrypt_key from password {scrypt_key.hex()} and salt is {salt.hex()}") print (f"Encrypted Mnemonic is {encrypted_mnemonic}") try: result = aes_decrypt(scrypt_key, bytes.fromhex(encrypted_mnemonic)) except Exception as e: print ("Error ") print (e) Alert(title='Error messege', text='Password entered is wrong') store.put("password", value=passwordText) print (result) ##This iwll check if the vm has runing ipfs connection or not, ##if its running global_variables.ipfs_node_id is not None """
def _openAlertWindow(self, str_Msg, str_Title): self.mask = MaskWidget(self) self.mask.show() self.alert = Alert(str_Msg, str_Title) self.alert.move( self.geometry().x() + self.geometry().width() / 2 - self.alert.geometry().width() / 2, self.geometry().y() + self.geometry().height() / 2 - self.alert.geometry().height() / 2) result = self.alert.exec_() self.mask.close() return result
def get_all_alerts(): con = sql.connect("data/scraper.db") cur = con.cursor() cur.execute("SELECT id, user_id, alert FROM alerts") result = [] for row in cur: result.append(Alert(alert_id=row[0], user_id=row[1], text=row[2])) con.close() return result
def __init__(self, vendor_name, logger): self.logger = logger self.vendor_name = vendor_name self.items_json_path = os.path.dirname(__file__) + '/../vendors/' + vendor_name.lower().replace(' ', '_') + '/items.json' self.alert = Alert(logger) self.session = FuturesSession() if os.path.isfile(self.items_json_path): with open(self.items_json_path, 'r') as file: json_data = json.load(file) self.items_to_check = json_data['items'] self.stores_to_check = json_data['stores'] else: raise IOError('File not found \'{}\''.format(self.items_json_path))
def get_users_alerts(user_id): con = sql.connect("data/scraper.db") cur = con.cursor() cur.execute("SELECT id, alert FROM alerts WHERE user_id = ?", (str(user_id))) result = [] for row in cur: result.append(Alert(alert_id=row[0], text=row[1])) con.close() return result