def call_register(uuid): print("Registering peer with uuid: {}".format(uuid)) client = RPCClient(b'localhost', 18080) res = client.call(b'register', uuid) client.close() return res
def call_get_schedule(uuid, num, method="smart"): print("Getting schedule for uuid: {}".format(uuid)) data = {'uuid': uuid, 'num': num, 'method': method} client = RPCClient(b'localhost', 18080) result = client.call(b'get_schedule', data) client.close() return result
def call_get_schedule(uuid, num, method="smart"): print("Getting schedule for uuid: {}".format(uuid)) data = { 'uuid':uuid, 'num':num, 'method':method } client = RPCClient(b'localhost', 18080) result = client.call(b'get_schedule', data) client.close() return result
def __exec_mprpc__(self, args): from mprpc import RPCClient, RPCPoolClient method = args[0] args = args[1] assert method in ["get", "set"] try: client = RPCClient(self.server, self.mprpc_port) result = client.call(method, args) client.close() return result except Exception as e: print(e) try: client.close() except: pass
class Proxy(object): def __init__(self, uri, show=False): self.showerr = show try: self.host, self.port = uri.split(":") except: self.host = "0.0.0.0" self.port = 0 self.OK = False self.__linked = False try: self._link_ = RPCClient(self.host, int(self.port), timeout=10) self.__linked = True except: self.__linked = False if show: P_Log("[FR]ERROR [FW] No Link to {}".format(uri)) def _close(self): if self._link_.is_connected(): self._link_.close() def connect(self): try: if not self.OK: self._link_ = RPCClient(self.host, int(self.port), timeout=20) if self._link_.is_connected(): self.OK = self.__create_hooks() else: self.OK = False except: self.OK = False if self.showerr: P_Log("[FR]ERROR [FW] No Connect to {}".format(uri)) finally: return self.OK def __call__(self): return self.connect() def __str__(self): if self.OK: return "{}:{}::Connected".format(*self._link_.getpeername()) elif self.__linked: return "{}:{}::Linked".format(*self._link_.getpeername()) else: return "Disconected 1.1.1.1:1" def __create_hooks(self): try: _config = self._link_.call('G_E_T_Configuration') except: _config = {} #print("error creating hooks {}:{}".format(self.host,self.port)) hooks = [] for defs, params in _config.items(): params_def = params[0] params_call = "" for x in params[1]: params_call = params_call + "," + str(x) d = def_skel.format(defs, params_def, params_call, self.host + ":" + str(self.port)) #print(d) hooks.append((defs, d)) for defs, fun in hooks: exec(fun) self.__dict__[defs] = types.MethodType(eval(defs), self) self.functions = hooks return len(self.functions) > 0 def get_uri(self): return "{}:{}".format(self.host, self.port) def get_functions(self): return [a for a, b in self.functions] def call(self, fn, *args): try: return self._link_.call(fn, *args) except Exception as ex: #raise P_Log("[[FR]ERROR[FW]] Running call on Proxy {}".format( self.get_uri())) P_Log(str(ex)) return None
class MPMShell(cmd.Cmd): """ RPC Shell class. See cmd module. """ def __init__(self): cmd.Cmd.__init__(self) self.prompt = "> " self.client = None self.remote_methods = [] self._claimer = None self._host = None self._port = None self._device_info = None args = parse_args() if args.host is not None: self.connect(args.host, args.port) if args.claim: self.claim() elif args.hijack: self.hijack(args.hijack) self.update_prompt() def _add_command(self, command, docs, requires_token=False): """ Add a command to the current session """ cmd_name = 'do_' + command if not hasattr(self, cmd_name): new_command = lambda args: self.rpc_template( str(command), requires_token, args ) new_command.__doc__ = docs setattr(self, cmd_name, new_command) self.remote_methods.append(command) def rpc_template(self, command, requires_token, args=None): """ Template function to create new RPC shell commands """ if requires_token and \ (self._claimer is None or self._claimer.token is None): print("Cannot execute `{}' -- no claim available!") return try: if args or requires_token: expanded_args = self.expand_args(args) if requires_token: expanded_args.insert(0, self._claimer.token) response = self.client.call(command, *expanded_args) else: response = self.client.call(command) except RPCError as ex: print("RPC Command failed!") print("Error: {}".format(ex)) return except Exception as ex: print("Unexpected exception!") print("Error: {}".format(ex)) return if isinstance(response, bool): if response: print("Command executed successfully!") return print("Command failed!") return print("==> " + str(response)) def get_names(self): " We need this for tab completion. " return dir(self) ########################################################################### # Cmd module specific ########################################################################### def run(self): " Go, go, go! " try: self.cmdloop() except KeyboardInterrupt: self.do_disconnect(None) exit(0) def postcmd(self, stop, line): """ Is run after every command executes. Does: - Update prompt """ self.update_prompt() ########################################################################### # Internal methods ########################################################################### def connect(self, host, port): """ Launch a connection. """ print("Attempting to connect to {host}:{port}...".format( host=host, port=port )) try: self.client = RPCClient(host, port, pack_params={'use_bin_type': True}) print("Connection successful.") except Exception as ex: print("Connection refused") print("Error: {}".format(ex)) return False self._host = host self._port = port print("Getting methods...") methods = self.client.call('list_methods') for method in methods: self._add_command(*method) print("Added {} methods.".format(len(methods))) print("Quering device info...") self._device_info = self.client.call('get_device_info') return True def disconnect(self): """ Clean up after a connection was closed. """ self._device_info = None if self._claimer is not None: self._claimer.unclaim() if self.client: try: self.client.close() except RPCError as ex: print("Error while closing the connection") print("Error: {}".format(ex)) for method in self.remote_methods: delattr(self, "do_" + method) self.remote_methods = [] self.client = None self._host = None self._port = None def claim(self): " Initialize claim " assert self.client is not None if self._claimer is not None: print("Claimer already active.") return True print("Claiming device...") self._claimer = MPMClaimer(self._host, self._port, self.unclaim_hook) return True def hijack(self, token): " Hijack running session " assert self.client is not None if self._claimer is not None: print("Claimer already active. Can't hijack.") return False print("Hijacking device...") self._claimer = MPMHijacker(token) return True def unclaim(self): """ unclaim """ if self._claimer is not None: self._claimer.unclaim() self._claimer = None def unclaim_hook(self): """ Hook """ pass def update_prompt(self): """ Update prompt """ if self._device_info is None: self.prompt = '> ' else: if self._claimer is None: claim_status = '' elif isinstance(self._claimer, MPMClaimer): claim_status = ' [C]' elif isinstance(self._claimer, MPMHijacker): claim_status = ' [H]' self.prompt = '{dev_id}{claim_status}> '.format( dev_id=self._device_info.get( 'name', self._device_info.get('serial', '?') ), claim_status=claim_status, ) def expand_args(self, args): """ Takes a string and returns a list """ if self._claimer is not None and self._claimer.token is not None: args = args.replace('$T', str(self._claimer.token)) eval_preamble = '=' args = args.strip() if args.startswith(eval_preamble): parsed_args = eval(args.lstrip(eval_preamble)) if not isinstance(parsed_args, list): parsed_args = [parsed_args] else: parsed_args = [] for arg in args.split(): try: parsed_args.append(int(arg, 0)) continue except ValueError: pass try: parsed_args.append(float(arg)) continue except ValueError: pass parsed_args.append(arg) return parsed_args ########################################################################### # Predefined commands ########################################################################### def do_connect(self, args): """ Connect to a remote MPM server. See connect() """ host, port = split_args(args, 'localhost', MPM_RPC_PORT) port = int(port) self.connect(host, port) def do_claim(self, _): """ Spawn a claim loop """ self.claim() def do_hijack(self, token): """ Hijack a running session """ self.hijack(token) def do_unclaim(self, _): """ unclaim """ self.unclaim() def do_disconnect(self, _): """ disconnect from the RPC server """ self.disconnect() def do_import(self, args): """import a python module into the global namespace""" globals()[args] = import_module(args) def do_EOF(self, _): " When catching EOF, exit the program. " print("Exiting...") self.disconnect() exit(0)
class MPMShell(cmd.Cmd): """ RPC Shell class. See cmd module. """ def __init__(self, host, port, claim, hijack): cmd.Cmd.__init__(self) self.prompt = "> " self.client = None self.remote_methods = [] self._claimer = None self._host = host self._port = port self._device_info = None if host is not None: self.connect(host, port) if claim: self.claim() elif hijack: self.hijack(hijack) self.update_prompt() def _add_command(self, command, docs, requires_token=False): """ Add a command to the current session """ cmd_name = 'do_' + command if not hasattr(self, cmd_name): new_command = lambda args: self.rpc_template( str(command), requires_token, args ) new_command.__doc__ = docs setattr(self, cmd_name, new_command) self.remote_methods.append(command) def rpc_template(self, command, requires_token, args=None): """ Template function to create new RPC shell commands """ if requires_token and \ (self._claimer is None or self._claimer.token is None): print("Cannot execute `{}' -- no claim available!") return try: if args or requires_token: expanded_args = self.expand_args(args) if requires_token: expanded_args.insert(0, self._claimer.token) response = self.client.call(command, *expanded_args) else: response = self.client.call(command) except RPCError as ex: print("RPC Command failed!") print("Error: {}".format(ex)) return except Exception as ex: print("Unexpected exception!") print("Error: {}".format(ex)) return if isinstance(response, bool): if response: print("Command executed successfully!") else: print("Command failed!") else: print("==> " + str(response)) return response def get_names(self): " We need this for tab completion. " return dir(self) ########################################################################### # Cmd module specific ########################################################################### def run(self): " Go, go, go! " try: self.cmdloop() except KeyboardInterrupt: self.do_disconnect(None) exit(0) def postcmd(self, stop, line): """ Is run after every command executes. Does: - Update prompt """ self.update_prompt() ########################################################################### # Internal methods ########################################################################### def connect(self, host, port): """ Launch a connection. """ print("Attempting to connect to {host}:{port}...".format( host=host, port=port )) try: self.client = RPCClient(host, port, pack_params={'use_bin_type': True}) print("Connection successful.") except Exception as ex: print("Connection refused") print("Error: {}".format(ex)) return False self._host = host self._port = port print("Getting methods...") methods = self.client.call('list_methods') for method in methods: self._add_command(*method) print("Added {} methods.".format(len(methods))) print("Quering device info...") self._device_info = self.client.call('get_device_info') return True def disconnect(self): """ Clean up after a connection was closed. """ self._device_info = None if self._claimer is not None: self._claimer.unclaim() if self.client: try: self.client.close() except RPCError as ex: print("Error while closing the connection") print("Error: {}".format(ex)) for method in self.remote_methods: delattr(self, "do_" + method) self.remote_methods = [] self.client = None self._host = None self._port = None def claim(self): " Initialize claim " assert self.client is not None if self._claimer is not None: print("Claimer already active.") return True print("Claiming device...") self._claimer = MPMClaimer(self._host, self._port, self.unclaim_hook) return True def hijack(self, token): " Hijack running session " assert self.client is not None if self._claimer is not None: print("Claimer already active. Can't hijack.") return False print("Hijacking device...") self._claimer = MPMHijacker(token) return True def unclaim(self): """ unclaim """ if self._claimer is not None: self._claimer.unclaim() self._claimer = None def unclaim_hook(self): """ Hook """ pass def update_prompt(self): """ Update prompt """ if self._device_info is None: self.prompt = '> ' else: if self._claimer is None: claim_status = '' elif isinstance(self._claimer, MPMClaimer): claim_status = ' [C]' elif isinstance(self._claimer, MPMHijacker): claim_status = ' [H]' self.prompt = '{dev_id}{claim_status}> '.format( dev_id=self._device_info.get( 'name', self._device_info.get('serial', '?') ), claim_status=claim_status, ) def expand_args(self, args): """ Takes a string and returns a list """ if self._claimer is not None and self._claimer.token is not None: args = args.replace('$T', str(self._claimer.token)) eval_preamble = '=' args = args.strip() if args.startswith(eval_preamble): parsed_args = eval(args.lstrip(eval_preamble)) if not isinstance(parsed_args, list): parsed_args = [parsed_args] else: parsed_args = [] for arg in args.split(): try: parsed_args.append(int(arg, 0)) continue except ValueError: pass try: parsed_args.append(float(arg)) continue except ValueError: pass parsed_args.append(arg) return parsed_args ########################################################################### # Predefined commands ########################################################################### def do_connect(self, args): """ Connect to a remote MPM server. See connect() """ host, port = split_args(args, 'localhost', MPM_RPC_PORT) port = int(port) self.connect(host, port) def do_claim(self, _): """ Spawn a claim loop """ self.claim() def do_hijack(self, token): """ Hijack a running session """ self.hijack(token) def do_unclaim(self, _): """ unclaim """ self.unclaim() def do_disconnect(self, _): """ disconnect from the RPC server """ self.disconnect() def do_import(self, args): """import a python module into the global namespace""" globals()[args] = import_module(args) def do_EOF(self, _): " When catching EOF, exit the program. " print("Exiting...") self.disconnect() exit(0)
class MPMShell(cmd.Cmd): """ RPC Shell class. See cmd module. """ def __init__(self, host, port, claim, hijack, script): cmd.Cmd.__init__(self) self.prompt = "> " self.client = None self.remote_methods = [] self._host = host self._port = port self._device_info = None self._claimer = MPMClaimer(self._host, self._port) if host is not None: self.connect(host, port) if claim: self.claim() elif hijack: self.hijack(hijack) self.update_prompt() self._script = script if self._script: self.parse_script() def _add_command(self, command, docs, requires_token=False): """ Add a command to the current session """ cmd_name = 'do_' + command if not hasattr(self, cmd_name): new_command = lambda args: self.rpc_template( str(command), requires_token, args) new_command.__doc__ = docs setattr(self, cmd_name, new_command) self.remote_methods.append(command) def _print_response(self, response): print(re.sub("^", "< ", response, flags=re.MULTILINE)) def rpc_template(self, command, requires_token, args=None): """ Template function to create new RPC shell commands """ from mprpc.exceptions import RPCError if requires_token and \ (self._claimer is None or self._claimer.get_token() is None): self._print_response("Cannot execute `{}' -- " "no claim available!".format(command)) return False try: if args or requires_token: expanded_args = self.expand_args(args) if requires_token: expanded_args.insert(0, self._claimer.get_token()) response = self.client.call(command, *expanded_args) else: response = self.client.call(command) except RPCError as ex: self._print_response("RPC Command failed!\nError: {}".format(ex)) return False except Exception as ex: self._print_response("Unexpected exception!\nError: {}".format(ex)) return True if isinstance(response, bool): if response: self._print_response("Command succeeded.") else: self._print_response("Command failed!") else: self._print_response(str(response)) return False def get_names(self): " We need this for tab completion. " return dir(self) ########################################################################### # Cmd module specific ########################################################################### def default(self, line): self._print_response("*** Unknown syntax: %s" % line) def preloop(self): """ In script mode add Execution start marker to ease parsing script output :return: None """ if self._script: print("Execute %s" % self._script) def precmd(self, line): """ Add command prepended by "> " in scripting mode to ease parsing script output. """ if self.cmdqueue: print("> %s" % line) return line def postcmd(self, stop, line): """ Is run after every command executes. Does: - Update prompt """ self.update_prompt() return stop ########################################################################### # Internal methods ########################################################################### def connect(self, host, port): """ Launch a connection. """ from mprpc import RPCClient print("Attempting to connect to {host}:{port}...".format(host=host, port=port)) try: self.client = RPCClient(host, port, pack_params={'use_bin_type': True}) print("Connection successful.") except Exception as ex: print("Connection refused") print("Error: {}".format(ex)) return False self._host = host self._port = port print("Getting methods...") methods = self.client.call('list_methods') for method in methods: self._add_command(*method) print("Added {} methods.".format(len(methods))) print("Quering device info...") self._device_info = self.client.call('get_device_info') return True def disconnect(self): """ Clean up after a connection was closed. """ from mprpc.exceptions import RPCError self._device_info = None if self._claimer is not None: self._claimer.exit() if self.client: try: self.client.close() except RPCError as ex: print("Error while closing the connection") print("Error: {}".format(ex)) for method in self.remote_methods: delattr(self, "do_" + method) self.remote_methods = [] self.client = None self._host = None self._port = None def claim(self): " Initialize claim " print("Claiming device...") self._claimer.claim() return True def hijack(self, token): " Hijack running session " if self._claimer.hijacked: print("Claimer already active. Can't hijack.") return False print("Hijacking device...") self._claimer.hijack(token) return True def unclaim(self): """ unclaim """ self._claimer.unclaim() def update_prompt(self): """ Update prompt """ if self._device_info is None: self.prompt = '> ' else: token = self._claimer.get_token() if token is None: claim_status = '' elif self._claimer.hijacked: claim_status = ' [H]' else: claim_status = ' [C]' self.prompt = '{dev_id}{claim_status}> '.format( dev_id=self._device_info.get( 'name', self._device_info.get('serial', '?')), claim_status=claim_status, ) def parse_script(self): """ Adding script command from file pointed to by self._script. The commands are read from file one per line and added to cmdqueue of parent class. This way they will be executed instead of input from stdin. An EOF command is appended to the list to ensure the shell exits after script execution. :return: None """ try: with open(self._script, "r") as script: for command in script: self.cmdqueue.append(command.strip()) except OSError as ex: print("Failed to read script. (%s)" % ex) self.cmdqueue.append("EOF") # terminate shell after script execution def expand_args(self, args): """ Takes a string and returns a list """ if self._claimer is not None and self._claimer.get_token() is not None: args = args.replace('$T', str(self._claimer.get_token())) eval_preamble = '=' args = args.strip() if args.startswith(eval_preamble): parsed_args = eval(args.lstrip(eval_preamble)) if not isinstance(parsed_args, list): parsed_args = [parsed_args] else: parsed_args = [] for arg in args.split(): try: parsed_args.append(int(arg, 0)) continue except ValueError: pass try: parsed_args.append(float(arg)) continue except ValueError: pass parsed_args.append(arg) return parsed_args ########################################################################### # Predefined commands ########################################################################### def do_connect(self, args): """ Connect to a remote MPM server. See connect() """ host, port = split_args(args, 'localhost', MPM_RPC_PORT) port = int(port) self.connect(host, port) def do_claim(self, _): """ Spawn a claim loop """ self.claim() def do_hijack(self, token): """ Hijack a running session """ self.hijack(token) def do_unclaim(self, _): """ unclaim """ self.unclaim() def do_disconnect(self, _): """ disconnect from the RPC server """ self.disconnect() def do_import(self, args): """import a python module into the global namespace""" globals()[args] = import_module(args) # pylint: disable=invalid-name def do_EOF(self, _): """ When catching EOF, exit the program. """ print("Exiting...") self.disconnect() return True # orderly shutdown