def run(): # print banner banner() options = parse_options() # config config = read_config(CONFIG_PATH) if options.mode == "s": target = config["share_mode"][options.target] target["mode"] = "share" mail = Sender(**target) mail.show_status() elif options.mode == 'd': target = config['direct_mode'][options.target] target["mode"] = "direct" mail = Sender(**target) mail.show_status() else: logger.error("Option.mode illegal!{}".format(options.mode)) sys.exit() fuzz_vector = json.loads(read_data(FUZZ_PATH).decode()) m = config["attack"][options.attack] for k in iterkeys(fuzz_vector): for f in fuzz_vector[k]: # TODO m[k] = f message = Message(**m) message = prepare_message(message, mail) message.show_status() mail.send(message) sleep() logger.info("All Task Done! :)")
def run(): options = parse_options() # config config = read_config(CONFIG_PATH) if options.mode == "s": target = config["share_mode"][options.target] target["mode"] = "share" mail = Sender(**target) mail.show_status() elif options.mode == 'd': target = config['direct_mode'][options.target] target["mode"] = "direct" mail = Sender(**target) mail.show_status() else: logger.error("Option.mode illegal!{}".format(options.mode)) sys.exit() m = config["attack"][options.attack] if options.mail_from: m['mail_from'] = options.mail_from if options.mail_to: m['mail_to'] = options.mail_to if options.mime_from: m['mime_from'] = options.mime_from if options.mime_to: m['to'] = options.mime_to message = Message(**m) message = prepare_message(message, mail) message.show_status() mail.send(message) logger.info("All Task Done! :)")
def find_device(self, port, free_ports=None): print('$', self.name, 'find device') success = False self._conn = Sender(port) if self._conn: model_info = self.get_model_info() if model_info and b'NP-F209' in model_info: success = True self.close_connection() if success: # got it! self._port = port return True return False
def main(): print("main") try: sender = Sender() sender.testConnection() except: print("Some error occurs sending message.") raise return employee = employeesManager.create("John", "Doe") employeesManager.save(employee) print("end")
def _get_connection(self): # if not Core.reserve_device(self.port): # log.info('%s: Device %s could not be reserved in Core.' %\ # (str(self.id), str(self.port))) # return False # else: #@@@ self.set_alarms('connection', False) #@@@ log.info('%s: Connection to %s established.' %\ #@@@ (str(self.id), str(self.port))) # print('$ _get_connection: %s' % self._port) # print('_conn:', self._conn, '_port:', self._port, '_protocol:', self._protocol) if self._conn is None: if self._protocol == 'serial': if self._port is not None: try: self._conn = Sender( self._port ) # TODO: engage self._connection_settings except Exception as e: log.error('Cannot get connection with %s: %s' %\ (str(self._port), str(e))) return False if not self._conn: return False return True else: pass # TODO: just wait for device_finder to define self._port elif self._protocol == 'socket': pass # TODO: socket connection return False else: log.critical('Module is run with unsupported protocol %s' % str(self._protocol)) return False
def run(): logger.info("Start evaluate email server....") logger.warning("-" * 70) options = parse_options() # config config = read_config(CONFIG_PATH) if options.mode == "s": target = config["share_mode"][options.target] target["mode"] = "share" mail = Sender(**target) mail.show_status() elif options.mode == 'd': target = config['direct_mode'][options.target] target["mode"] = "direct" mail = Sender(**target) mail.show_status() else: logger.error("Option.mode illegal!{}".format(options.mode)) sys.exit() for a in config["attack"]: try: data = config["attack"][a] name = a subject = template_subject.format(name=name) description = data['description'] defense = data['defense'] body = template_body.format(name=name, defense=defense, description=description) data['subject'] = subject data['body'] = body message = Message(**data) message = prepare_message(message, mail) message.show_status() mail.send(message) sleep() except Exception as e: logger.info(e) pass logger.info("All Task Done! :)")
def send_request(self, *args): self.save_configs() module = self.model.current_module conf = self.model.current_config mod_params = conf.utils[module] self.logger.debug(module) self.logger.debug(str(mod_params)) if self.sender is None: self.sender = Sender(self.logger, conf.host, self.model.login_pass, self.model.urls) self.sender.question_method = self.question_method if not self.sender.auth(): self.sender = None return request = self.mod_manager.create_request(module) response = self.sender.send_request(conf.instance, request) if response is None: self.sender = None
class F209(Module): CMDS = { 'Printer initialization': ESC + b'@', 'Full cut': ESC + b'i', 'Partial cut': ESC + b'm', 'Character code table selection': ESC + b't', 'Printer status transmission': ESC + b'v', 'Print and line feed': LF, 'Print and N lines feed': ESC + b'd', 'Carriage return': CR, 'Software reset': DC1, 'Line print permission': DC3 + b'+', 'Line print prohibition': DC3 + b'-', 'Line buffer A selection': DC3 + b'A', 'Line buffer B selection': DC3 + b'B', 'Line buffer clear': DC3 + b'C', 'Model info': ESC + b's\x02', 'Firmware version info': ESC + b's\x03', 'Boot version info': ESC + b's\x04', 'SW setting info': ESC + b's\x05', } def __init__(self, port_override=None): super().__init__() self._protocol = 'serial' self._port = port_override self._check_connection_period = 1.5 @staticmethod def spl(v, l=32): w = v.split() ret = list() ix = 0 ret.append('') for i in w: if len(i) > l: if len(ret[ix]) > 0: ix += 1 ret.append(i) else: ret[ix] = i ix += 1 ret.append('') elif len(ret[ix]) == 0 and len(i) <= l: ret[ix] += i elif len(ret[ix]) > 0 and len(ret[ix]) + 1 + len(i) <= l: ret[ix] += (' ' + i) else: ix += 1 ret.append(i) return ret def initialize(self): # s.write(b'\x1bi') # b'' # s.write(b'\x1bt\x04') # b'' # s.write(b'\x13+') # b'' # s.write(b'\x13A') # b'' # s.write(b'\x13C') # b'' # s.write(b'\x1bv') # b'\x00' # s.write(b'\x1bs\x02') # b'\xff\x02NP-F209 ' # s.write(b'\x1bs\x03') # b'\xff\x03Ver.1.10' # s.write('Локер-коробка, уходи!'.encode('cp1251')) # b'' self.update_status('initializing') self._execute(self.CMDS['Printer initialization']) while Global.run: state = self._execute(self.CMDS['Printer status transmission'], wait_for_response=True) if state and state == b'\x00': break sleep(0.25) self._execute(self.CMDS['Character code table selection'] + b'\x04') self._execute(self.CMDS['Line print permission']) self._execute(self.CMDS['Line buffer A selection']) self._execute(self.CMDS['Line buffer clear']) while Global.run: state = self._execute(self.CMDS['Printer status transmission'], wait_for_response=True) if state and state == b'\x00': break sleep(0.25) self.update_status('idle') def find_device(self, port, free_ports=None): print('$', self.name, 'find device') success = False self._conn = Sender(port) if self._conn: model_info = self.get_model_info() if model_info and b'NP-F209' in model_info: success = True self.close_connection() if success: # got it! self._port = port return True return False def check_connection(self, just_after_reconnection=False): if self._port: state = self.get_state() if state and len(state) == 1: self._chance = CHANCES if just_after_reconnection: self.initialize() return True else: if self._status not in (None, 'no_connection'): self._chance -= 1 if self._chance: return True return False def run(self): while Global.run: self.spin_once() sleep(SPIN_PERIOD) def spin_once(self): if self._conn: sts = self._status if sts not in (None, 'no_connection', 'initializing'): paper_is_present = self.is_paper_present() if paper_is_present == False: self.update_status('no_paper') elif paper_is_present == True: self.update_status('idle') ### FIXME elif paper_is_present is None: pass # nothing to do with it # check connection right now try: if not self._conn.conn: self.close_connection() except: self.close_connection() # serve requests rq = self._request sts = self._status if rq is not None and sts in ('idle', ): # print('got a request:', rq) if rq.startswith('print'): # print('starts with \'print\'') text = rq[len('print'):].strip() # print('get ready for printing:', text) #@@@ self.print_text(text) elif rq.startswith('cut'): self.cut_paper() #--- if rq is not None: log.debug('---- clearing request') self._request = None ##################################################################### def _execute(self, command, wait_for_response=False): response = b'' if self._conn and command: # print('f209 execute: locked????????????????????') with self._conn_lock: # print('f209 execute: locked!!!!!!!!!!!!!!') if type(command) is not list: if type(command) in (int, float): command = [int(command)] if type(command) is str: command = list(command.encode('cp1251')) else: command = list(command) log.debug( paint('-------- executing command %s' % brepr(command), YELLOW)) if self._conn: if wait_for_response: response = self._conn.send_packet(command, total_timeout=0.7) else: response = self._conn.send_packet( command, read_after_send=False) if response: log.debug('-------- response: %s' % brepr(response)) try: # disconnected? if not self._conn.conn: self.close_connection() except: self.close_connection() return response def print_text(self, text=None): if text: text_list = self.spl(text) for line in text_list: self._execute(line) self._execute(self.CMDS['Print and line feed']) def cut_paper(self): self._execute(self.CMDS['Print and N lines feed'] + b'\x04') self._execute(self.CMDS['Full cut']) def get_model_info(self): return self._execute(self.CMDS['Model info'], wait_for_response=True) def get_state(self): state = self._execute(self.CMDS['Printer status transmission'], wait_for_response=True) return state def is_paper_present(self): state = self.get_state() if not state: return None elif (state[0] & (1 << 2)) == 0: return True return False ##################################################################### # requests def request_print(self, text=''): rq = 'print ' + ' '.join(text.split()) if not self.is_paper_present(): log.warning('cannot print ticket: there is no paper in feeder') self.update_status('failed >> no paper') return False return self.check_request_and_status(rq, 'idle') def request_cut_paper(self): rq = 'cut paper' return self.check_request_and_status(rq, 'idle')
class MainController(QObject): def __init__(self, model): super().__init__() self.model = model self.logger = logging.getLogger(log_config.LOGGER_NAME) self.mod_manager = ModuleManager() self.sender = None self.question_method = None def load_login(self): if not os.path.isfile(self.model.LOGIN_FILE): self.model.login_pass = '' return with open(self.model.LOGIN_FILE, 'rb') as file: data = file.read() if data: self.model.login_pass = base64.b64decode(data).decode() else: self.model.login_pass = '' @try_except_wrapper def load_urls(self): if not os.path.isfile(self.model.URLS_FILE): return with open(self.model.URLS_FILE, 'r', encoding='utf-8') as file: data = yaml.load(file, yaml.FullLoader) if not data: self.logger.warning(f'{self.model.URLS_FILE} is empty') return self.model.urls = { n: data.get(n, '') for n, u in self.model.urls.items() } self.logger.debug('urls loaded') @try_except_wrapper def save_urls(self): with open(self.model.URLS_FILE, 'w', encoding='utf-8') as file: yaml.dump(self.model.urls, file, default_flow_style=False) self.logger.debug('urls saved') def update_url(self, key, value): self.model.urls[key] = value @try_except_wrapper def load_configs(self): if not os.path.isfile(self.model.CONFIGS_FILE): return with open(self.model.CONFIGS_FILE, 'r', encoding='utf-8') as file: data = yaml.load(file, yaml.FullLoader) if not data: self.logger.warning(f'{self.model.CONFIGS_FILE} is empty') return configs = [Config.from_dict(d) for d in data] for conf in configs: self.mod_manager.update_config_fields(conf) self.model.configs = configs self.logger.debug('configs loaded') @try_except_wrapper def save_configs(self, *args): data = [c.get_dict() for c in self.model.configs] with open(self.model.CONFIGS_FILE, 'w', encoding='utf-8') as file: yaml.dump(data, file, default_flow_style=False) self.logger.debug('configs saved') @try_except_wrapper def add_config(self, *args): conf = Config() self.mod_manager.update_config_fields(conf) self.model.add_config(conf) @try_except_wrapper def remove_config(self, *args): self.model.remove_config() self.save_configs() @try_except_wrapper def select_config(self, config): self.model.current_config = config self.sender = None def update_config_field(self, field, value): if self.model.current_config: set_field_value(self.model.current_config, field, value) # self.logger.debug(f'{field} = {value}') def select_module(self, module_name): self.model.current_module = module_name @try_except_wrapper def send_request(self, *args): self.save_configs() module = self.model.current_module conf = self.model.current_config mod_params = conf.utils[module] self.logger.debug(module) self.logger.debug(str(mod_params)) if self.sender is None: self.sender = Sender(self.logger, conf.host, self.model.login_pass, self.model.urls) self.sender.question_method = self.question_method if not self.sender.auth(): self.sender = None return request = self.mod_manager.create_request(module) response = self.sender.send_request(conf.instance, request) if response is None: self.sender = None