class IPCServer(threading.Thread): def __init__(self, manager, port=None): super(IPCServer, self).__init__(name='ipc_server') self.daemon = True self.manager = manager self.host = '127.0.0.1' self.port = port or 0 self.password = ''.join(random.choice(string.letters + string.digits) for x in range(15)) self.server = None def authenticator(self, sock): channel = rpyc.Channel(rpyc.SocketStream(sock)) password = channel.recv() if password != self.password: channel.send(AUTH_ERROR) raise rpyc.utils.authenticators.AuthenticationError('Invalid password from client.') channel.send(AUTH_SUCCESS) return sock, self.password def run(self): DaemonService.manager = self.manager self.server = ThreadedServer( DaemonService, hostname=self.host, port=self.port, authenticator=self.authenticator, logger=log ) # If we just chose an open port, write save the chosen one self.port = self.server.listener.getsockname()[1] self.manager.write_lock(ipc_info={'port': self.port, 'password': self.password}) self.server.start() def shutdown(self): self.server.close()
def server(): class SsdpSenderService(rpyc.Service): from ssdp_sender import SsdpSender as exposed_SsdpSender from rpyc.utils.server import ThreadedServer t = ThreadedServer(SsdpSenderService, port = 18861, protocol_config = {"allow_public_attrs" : True}) t.start()
def main(): logging.basicConfig() parser = argparse.ArgumentParser() parser.add_argument('--pid', action='store', dest='pid', default='/var/tmp/harvester_rpc.pid', help='pid filename') parser.add_argument('--port', dest='port', type=int, default=18861, help='the TCP port to bind to') parser.add_argument('--backlog', dest='backlog', type=int, default=10, help='backlog for the port') parser.add_argument('--stdout', action='store', dest='stdout', default='/var/tmp/harvester_rpc.out', help='stdout filename') parser.add_argument('--stderr', action='store', dest='stderr', default='/var/tmp/harvester_rpc.err', help='stderr filename') options = parser.parse_args() # make daemon context outfile = open(options.stdout, 'w+') errfile = open(options.stderr, 'w+') dc = daemon.DaemonContext( pidfile=daemon.pidfile.PIDLockFile(options.pid), stdout=outfile, stderr=errfile) # run thread server with dc: from rpyc.utils.server import ThreadedServer t = ThreadedServer(RpcBot, port=options.port, backlog=options.backlog, protocol_config={"allow_all_attrs": True}) t.start() # finalize outfile.close() errfile.close()
def main(): from solarsan import logging logger = logging.getLogger(__name__) from solarsan.cluster.models import Peer from solarsan.conf import rpyc_conn_config from rpyc.utils.server import ThreadedServer #from rpyc.utils.server import ThreadedZmqServer, OneShotZmqServer from setproctitle import setproctitle from .service import CLIService import rpyc title = 'SolarSan CLI' setproctitle('[%s]' % title) local = Peer.get_local() cluster_iface_bcast = local.cluster_nic.broadcast # Allow all public attrs, because exposed_ is stupid and should be a # f*****g decorator. #t = ThreadedZmqServer(CLIService, port=18863, #t = OneShotZmqServer(CLIService, port=18863, t = ThreadedServer(CLIService, port=18863, registrar=rpyc.utils.registry.UDPRegistryClient(ip=cluster_iface_bcast, #logger=None, logger=logger, ), auto_register=True, logger=logger, #logger=None, protocol_config=rpyc_conn_config) t.start()
class RPCserver(Collected,Jobber): """A channel server""" storage = RPCservers def __init__(self,name,host,port): self.name = name self.host=host self.port=port self.server = ThreadedServer(gen_rpcconn(name), hostname=host,port=port,ipv6=True, protocol_config = {"safe_attrs":set(("list","__unicode__","year","month","day","days","date","time","hour","minute","second","seconds","microseconds","ctx","items","iteritems")).union(DEFAULT_CONFIG["safe_attrs"])}) self.server.listener.settimeout(None) self.start_job("job",self._start) super(RPCserver,self).__init__() def _start(self): self.server.start() def delete(self,ctx=None): self.server.close() self.server = None super(RPCserver,self).delete() def list(self): for r in super(RPCserver,self).list(): yield r yield ("host",self.host) yield ("port",self.port) yield ("server",repr(self.server))
def start_service(): t = ThreadedServer(SimService, port=18861, auto_register=True) try: t.start() except KeyboardInterrupt: t.stop() logging.warning("SINGINT caught from user keyboard interrupt") sys.exit(1)
def server(): 'Launch a server' try: server = ThreadedServer(MyService, port = 12345, protocol_config = {"allow_all_attrs": True}, auto_register = False) server.start() except Exception: raise return True
def serve_threaded(options): t = ThreadedServer(SlaveService, hostname = options.host, port = options.port, reuse_addr = True, authenticator = options.authenticator, registrar = options.registrar, auto_register = options.auto_register) t.logger.quiet = options.quiet if options.logfile: t.logger.console = open(options.logfile, "w") t.start()
class Server(Thread): def __init__(self): Thread.__init__(self) self.setDaemon(True) self.server = ThreadedServer(MyService, port = DEFAULT_SERVER_PORT) def run(self): self.server.start()
def main(): global handler open('./nohup.out','w').close() handler=word_handler() handler.add_embedding_file('all') for date in xrange(2005,2014): handler.add_embedding_file(date) sr=ThreadedServer(Listener,port=22222,auto_register=False) sr.start()
def main(): setup_logging() logger.info("Starting server ...") locale.setlocale(locale.LC_ALL, "") args = parse_args() start_background_worker(args) wrapService = WrapService(net_io_counters, logs) s = ThreadedServer(wrapService, port=5050, protocol_config={"allow_public_attrs":True}) s.start()
def remote_service_operator(DATA): """ starts the (threaded) service which exposes the RPYC_service factory class to remote RPYC clients. This is the function which should be called in the main function, there is no need for hiding it in a class. """ CS = CustomizedService(DATA) t = ThreadedServer(CS, port = DATA.localhost.port)#, protocol_config = {"allow_public_attrs" : True}) t.start()
def rpcThread(): class TrafficMonitor(rpyc.Service): def on_connect(self): pass def on_disconnect(self): pass def exposed_get_traffic(self): return g_rate from rpyc.utils.server import ThreadedServer t = ThreadedServer(TrafficMonitor, port = PORT) t.start()
def _run(self): message = 'Starting m_server daemon...' logger.info("%s" % message) # 开启监听服务 while True: try: s = ThreadedServer(ManagerService, port=PORT, auto_register=False) # 启动rpyc服务监听、接受、响应请求 s.start() except Exception, e: message = 'Starting service error!' logger.error(message) sys.exit()
def start_server(config_file): defaults = { 'hostname':'localhost', 'lport':'31337', 'ipv6':'off', 'backlog':'10', } config = ConfigParser.SafeConfigParser(defaults) config.readfp(open(config_file, 'r')) lport = config.getint("Network", 'lport') host = config.get("Network", 'hostname').strip() agent = ThreadedServer(WeaponSystem, hostname=host, port=lport) agent.start()
def main(self): logger.info("Worker just staring.") print "THIS IS IMPORTANT COPY THOSE TO WEB CONTROL PANEL" print "PUBLIC HOSTNAME: ",get_public_hostname() print "PUBLIC IP ADDR: ",get_public_ip_addr() print "IP ADDR: ",get_ip_addr() print "WILL START IN 2 SECONDS !" import time time.sleep(2) from rpyc.utils.server import ThreadedServer t = ThreadedServer(PreciousWorkerService, port=get_worker_port()) t.start()
def inner_run(self, *args, **options): """ Starts a threaded server on given hostname:port (defaults to 127.0.0.1:4444) """ # defaults hostname = '0.0.0.0' port = '4444' if len(args) == 1: hostname, port = args[0].split(':') print "Starting serviced on {}:{}".format(hostname, port) server = ThreadedServer(CallService, port=int(port)) server.start()
def target(host, port, threads=True): ''' Start a process that will generate a new thread for every connection. Each Component, in the graph, will be represented by a new dedicated connection for the proxy object representing that component. ''' from rpyc import SlaveService if threads: from rpyc.utils.server import ThreadedServer t = ThreadedServer(SlaveService, hostname=host, port=port) else: from rpyc.utils.server import ForkingServer t = ForkingServer(SlaveService, hostname=host, port=port) t.start()
class mavLinkServiceClientThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.t = None def run(self): from rpyc.utils.server import ThreadedServer self.t = ThreadedServer(MavLinkRpycClientService, port = 18862) #self.t._closed = False self.t.start() def stop(self): if not(self.t==None): #self.t.stop() # https://docs.python.org/2/library/thread.html self.t.exit()
class MasterRPC: def __init__(self, redis_host, redis_port=6379, slaves_db=3, port=8780, auto_register=False): global slaves, ws slaves = SlaveStorage(slaves_db, redis_host, redis_port) ws = websocket.create_connection("ws://localhost:8000/soc") self.server = ThreadedServer(MasterRPCService, port=port, auto_register=auto_register) logging.info("Start master on port %d..." % port) ws.send("Start master on port %d..." % port) # http.post("Start master on port %d..." % port) self.server.start() def close(self): self.server.close()
class mavLinkServiceThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.t = None def run(self): from rpyc.utils.server import ThreadedServer self.t = ThreadedServer(MavLinkRpycService.MavLinkRpycService, port = 18861) #t = ThreadedServer(MyService, port = 18861) self.t.start() def stop(self): if not(self.t==None): self.t.exit() # https://docs.python.org/2/library/thread.html #def reconnect(self): # c = rpyc.connect("localhost", 18861) #LIM # c.root.reconnect()
class IPCServer(threading.Thread): def __init__(self, manager, port=None): super(IPCServer, self).__init__(name='ipc_server') self.daemon = True self.manager = manager self.host = '127.0.0.1' self.port = port or 0 self.password = ''.join( random.choice(string.ascii_letters + string.digits) for x in range(15) ) self.server = None def authenticator(self, sock): channel = rpyc.Channel(rpyc.SocketStream(sock)) password = channel.recv().decode('utf-8') if password != self.password: channel.send(AUTH_ERROR) raise rpyc.utils.authenticators.AuthenticationError('Invalid password from client.') channel.send(AUTH_SUCCESS) return sock, self.password def run(self): # Make the rpyc logger a bit quieter when we aren't in debugging. rpyc_logger = logging.getLogger('ipc.rpyc') if logging.getLogger().getEffectiveLevel() > logging.DEBUG: rpyc_logger.setLevel(logging.WARNING) DaemonService.manager = self.manager self.server = ThreadedServer( DaemonService, hostname=self.host, port=self.port, authenticator=self.authenticator, logger=rpyc_logger, ) # If we just chose an open port, write save the chosen one self.port = self.server.listener.getsockname()[1] self.manager.write_lock(ipc_info={'port': self.port, 'password': self.password}) self.server.start() def shutdown(self): if self.server: self.server.close()
class RPyCViewerLevelThread(ViewerLevelThread): """ implementation of viewer level thread using Remote Python Calls (RPyC) """ def __init__(self, *args, **kwargs): ViewerLevelThread.__init__(self, *args, **kwargs) def run(self): """ instantiate the server """ if self.verbose: print "thread started..." global RPYCTHREAD RPYCTHREAD = self self.server = ThreadedServer( RPyCViewerService, port=DEFAULT_SERVER_PORT, auto_register=False, registrar=UDPRegistryClient() ) self.server.start() def join(self): self.server.close() ViewerLevelThread.join(self)
def rpcThread(): logging.info('RPC thread started') class LoadMonitor(rpyc.Service): def on_connect(self): pass def on_disconnect(self): pass def exposed_get_load(self): return g_netutil def exposed_get_cost_data(self): latency = configparser.ConfigParser() latency.read(args['latency']) logging.debug('Latency data: ' + [x for x in latency.items()]) return dict(x for x in latency['LATENCY'].items()) def exposed_get_bandwidthcap(self): return BANDWIDTHCAP from rpyc.utils.server import ThreadedServer t = ThreadedServer(LoadMonitor, port = PORT) t.start()
def main(): from rpyc.utils.server import ThreadedServer from setproctitle import setproctitle title = 'SolarSan Storage' setproctitle('[%s]' % title) local = Peer.get_local() cluster_iface_bcast = local.cluster_nic.broadcast # Allow all public attrs, because exposed_ is stupid and should be a # f*****g decorator. t = ThreadedServer(StorageService, port=18862, registrar=rpyc.utils.registry.UDPRegistryClient(ip=cluster_iface_bcast, #logger=None, logger=logger, ), auto_register=True, #logger=logger.getChild('rpc.server_storage'), logger=logger, #logger=None, protocol_config=conf.rpyc_conn_config) t.start()
def start_server(options): """ Start RPyC server """ if options['daemonize'] and options['server_user'] and \ options['server_group']: #ensure the that the daemon runs as specified user change_uid_gid(options['server_user'], options['server_group']) if options['threaded']: serv = ThreadedServer(server.OpenProximityService, options['host'], port = options['port'], auto_register = options['autoregister']) else: print "Forking server is not a tested server!" serv = ForkingServer(server.OpenProximityService, options['host'], port = options['port'], auto_register = options['autoregister']) try: serv.start() except KeyboardInterrupt, err: serv.stop()
class RPyCServer(QObject): """ Contains a RPyC server that serves modules to remote computers. Runs in a QThread. """ def __init__(self, serviceClass, host, port, certfile=None, keyfile=None): """ @param class serviceClass: class that represents an RPyC service @param int port: port that hte RPyC server should listen on """ super().__init__() self.serviceClass = serviceClass self.host = host self.port = port self.certfile = certfile self.keyfile = keyfile def run(self): """ Start the RPyC server """ if self.certfile is not None and self.keyfile is not None: authenticator = SSLAuthenticator(self.certfile, self.keyfile) self.server = ThreadedServer( self.serviceClass, hostname=self.host, port=self.port, protocol_config={'allow_all_attrs': True}, authenticator=authenticator, cert_reqs=ssl.CERT_REQUIRED, ciphers='EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH', ssl_version=ssl.PROTOCOL_TLSv1_2) else: self.server = ThreadedServer( self.serviceClass, hostname=self.host, port=self.port, protocol_config={'allow_all_attrs': True}) self.server.start()
class ComThread(threading.Thread): """ Class to run the rpyc server thread ComServer will handle execution of commands from the web UI or other controllers. It allows the client (mycodo_client.py, excuted as non-root user) to communicate with the daemon (mycodo_daemon.py, executed as root). """ def __init__(self, mycodo): threading.Thread.__init__(self) self.logger = logging.getLogger("mycodo.rpyc") self.logger.setLevel(logging.WARNING) self.mycodo = mycodo self.server = None self.rpyc_monitor = None def run(self): try: # Start RPYC server service = mycodo_service(self.mycodo) self.server = ThreadedServer(service, port=18813, logger=self.logger) self.server.start() # self.rpyc_monitor = threading.Thread( # target=monitor_rpyc, # args=(self.logger,)) # self.rpyc_monitor.daemon = True # self.rpyc_monitor.start() except Exception as err: self.logger.exception( "ERROR: ComThread: {msg}".format(msg=err)) def close(self): self.server.close()
def run_server(port, fake=False, remote_rp=False): print("start server at port", port) if fake: print("starting fake server") control = FakeRedPitayaControl() else: if remote_rp is not None: assert ( "@" in remote_rp and ":" in remote_rp ), "invalid format, should be root:[email protected]" username, tmp = remote_rp.split(":", 1) r_host, r_password = "".join(reversed(tmp)).split("@", 1) host = "".join(reversed(r_host)) password = "".join(reversed(r_password)) control = RedPitayaControlService(host=host, user=username, password=password) else: control = RedPitayaControlService() control.run_acquiry_loop() control.exposed_write_data() failed_auth_counter = {"c": 0} def username_and_password_authenticator(sock): # when a client starts the server, it supplies this hash via an environment # variable secret = os.environ.get("LINIEN_AUTH_HASH") # client always sends auth hash, even if we run in non-auth mode # --> always read 64 bytes, otherwise rpyc connection can't be established received = sock.recv(64) # as a protection against brute force, we don't accept requests after # too many failed auth requests if failed_auth_counter["c"] > 1000: print("received too many failed auth requests!") sys.exit(1) if secret is None: print("warning: no authentication set up") else: if received != secret.encode(): print("received invalid credentials: ", received) failed_auth_counter["c"] += 1 raise AuthenticationError("invalid username / password") print("authentication successful") return sock, None t = ThreadedServer(control, port=port, authenticator=username_and_password_authenticator, protocol_config={"allow_pickle": True}) t.start()
def server(): t = ThreadedServer(MyService, port=18861) t.start()
def process(self): obj = SvnService(self.svn_root, token=self.token, normal=self.normal, refuse=self.refuse, target=self.target) s = ThreadedServer(obj, port=self.port, auto_register=False) s.start()
def start_subserver(addr, port): print(f"Starting subserver {port} on {addr}...\n") subss = ThreadedServer(SubServerService(port, sub_server_root_dir), port=port) subss.start()
def run(self): thread = ThreadedServer(RPC_Service(self.sonosManagerInstance), port=RPC_PORT, protocol_config={"allow_public_attrs": True}) thread.start()
from rpyc import Service from rpyc.utils.server import ThreadedServer from rpyc.core.service import SlaveService # hostname有所变化,可以通过ipconfig在cmd进行查看 sr = ThreadedServer(SlaveService, hostname='192.168.11.36', port=9999, auto_register=False) sr.start()
del server_registry[name] print("\tSuccess!") return True else: print("\tEntry not found.") return False # Retorna um servidor, se existir, da lista. def fetch_server(self, name): if self.query_registry(name): print("\tSuccess!") return (server_registry[name][1], server_registry[name][2]) else: print("\tEntry not found.") return None def query_registry(self, name) print("Looking for server with name \"{}\"...".format(name)) if name in server_registry: print("Name \"{}\" found in registry.".format(name)) return True else: print("Name \"{}\" not found in registry.".format(name)) return False if __name__ == "__main__": directory_server = ThreadedServer(DirectoryServer, port=const.DIR_PORT) directory_server.start()
def main(): t = ThreadedServer(forController, port=8090) t.start()
from rpyc.lib import setup_logger import signal def _handle_sighup(myrpcserver, signum, unused): """Closes (terminates) all of its clients. Though keeps server running.""" print("SIGHUP: stopping all clients", sys.stderr) if myrpcserver._closed: return for c in set(myrpcserver.clients): try: c.shutdown(socket.SHUT_RDWR) except Exception: pass c.close() myrpcserver.clients.clear() ThreadedServer._handle_sighup = _handle_sighup setup_logger(False, None) myrpcserver = ThreadedServer(SlaveService, hostname="", port=DEFAULT_SERVER_PORT, reuse_addr=True, ipv6=False) signal.signal(signal.SIGHUP, myrpcserver._handle_sighup) myrpcserver.start()
) # need to specify full path+filename to get the filesize as only filename is not recognized mtime = dt.fromtimestamp( os.path.getmtime(os.path.join(dirpath, file)) ) # This returns a datetime object datetime.datetime(YYYY, MM, DD, hh, mm, ss, ms) tempdict['ModTime'] = mtime.strftime( timeformat ) # Formats the mtime to "YYYY-MM-DD hh:mm:ss" which is human readable filelist.append( tempdict) # Appends each file to the filelist print(filelist) return (filelist) if __name__ == "__main__": t2 = ThreadedServer(DNServer, hostname=IP, port=PORT, protocol_config={'allow_public_attrs': True}) # 'allow_public_attrs' is needed to make the rpyc items visible. If this is not specified, it will result in errors # .. since rpyc dicts & lists are not visible as normal dict and list # e.g. while converting an rpyc list of dict (filelist) to dataframe, it returns 'keys' error setup_logger(quiet=False, logfile=None) subprocess.call( "start cmd /K python ftpserver2.py", shell=True ) # this opens the ftpserver2.py file in a new console window (shell=True) so that we can view the FTP logs t2.start() # Start the DNode server """ NOTE: Here we call the ftpserver script separately as including teh FTP script in this file creates collision between the rpyc logging and ftp logging & it was difficult to run both simultaneously USing a new window for FTPserver fixes this issue """
try: USER_NAME = os.getenv('USER') or os.getenv('USERNAME') if USER_NAME == 'root': USER_NAME = os.getenv('SUDO_USER') or USER_NAME logDebug('Hello username `{}`!'.format(USER_NAME)) except Exception: USER_NAME = '' if not USER_NAME: logError('Cannot guess user name for the User Service! Exiting!') exit(1) try: open(LOG_FILE, 'w').close() except Exception: print 'Cannot reset log!!' logInfo('User Service: Starting...') USER_HOME = subprocess.check_output('echo ~' + USER_NAME, shell=True).strip().rstrip('/') th_s = ThreadedServer(UserService, port=int(PORT[0]), protocol_config=CONFIG, listener_timeout=1) th_s.start() logInfo('User Service: Bye bye.') # Eof()
import uuid import os from rpyc.utils.server import ThreadedServer from serverService import serverService #FILE_DIR = ["/home/roger/Desktop/ECS251/tbmounted/"] FILE_DIR = [ "/home/pearlhsu/Documents/subserver1/", "/home/pearlhsu/Documents/subserver2/", "/home/pearlhsu/Documents/subserver3/" ] if __name__ == "__main__": subserver_port = input("Input the port for the Subserver: ") sub = ThreadedServer(serverService(FILE_DIR), port=int(subserver_port), protocol_config={ 'allow_public_attrs': True, }) print("IP: localhost") print("Port: ", subserver_port) print("Starting sub server service...") sub.start()
subprocess.Popen('shutdown -f -r -t 5', shell=True) class StockService(Service): def __init__(self, conn): super(StockService, self).__init__(conn) def exposed_get_time(self): return time.ctime() def exposed_shutdown(self): try: t = Shutdown() t.start() # res = subprocess.Popen('shutdown -f -r -t 3', shell=True) # result = pexpect.spawn('shutdown -f -r -t 3') return {'status': True} except Exception as e: return {'status': False, 'result': 'error'} # result = pexpect.spawn('shutdown -f -r -t 3') # if not result.read(): # return {'status': True} # else: # return {'status':False, 'result':result.read()} if __name__ == '__main__': s = ThreadedServer(StockService, port=60000, auto_register=False) s.start()
def main(): from rpyc.utils.server import ThreadedServer t = ThreadedServer(MyService, port=18861) t.start()
def get_file_table_entry(self,fname): if fname in self.__class__.file_table: return self.__class__.file_table[fname] else: return None def get_block_size(self): return self.__class__.block_size def get_nodes(self): return self.__class__.nodes def get_num_blocks(self,size): return int(math.ceil(float(size)/self.__class__.block_size)) def allocate(self,dest,num_blocks): blocks = [] for i in range(0,num): block_uuid = uuid.uuid1() nodes_ids = random.sample(self.__class__.nodes.keys(),self.__class__.dup) blocks.append((block_uuid,nodes_ids)) self.__class__.file_table[dest].append((block_uuid,nodes_ids)) return blocks if __name__ == "__main__": get_config() signal.signal(signal.SIGINT,int_handler) thread = ThreadedServer(MasterServer, port = 2131) thread.start()
def serve(): t = ThreadedServer(Averager, port=50051) t.start() while True: time.sleep(600)
res = ''.join(random.choices(string.ascii_uppercase + string.digits, k = self.N))#kb,kdc M = Fernet(File_server_key) self.File_server_key = M.encrypt(bytes(res,'utf-8')) return self.File_server_key,File_server_key def exposed_share_key_2(self): #key for Client Side #Client_key = Fernet.generate_key() import random import string self.N = 25 self.seed2 = 30 random.seed(self.seed2) res = ''.join(random.choices(string.ascii_uppercase + string.digits, k = self.N)) M = Fernet(res) self.Client_key_en = M.encrypt(res) return self.Client_key_en if __name__ == '__main__': from rpyc.utils.server import ThreadedServer T = ThreadedServer(My_Service,port = 8000) print('Server Running') T.start() T.close() print('Server stopped')
import rpyc import constants from rpyc.utils.server import ThreadedServer class DBList(rpyc.Service): def exposed_registry(self, peer_id, file_name): pass def exposed_search(self, file_name): pass if __name__ == "__main__": server = ThreadedServer(DBList, hostname=constants.SERVER, port=constants.PORT) print("Server starts") server.start()
str_diff = '' sql = '' temp_text = new_id_text + str(r['id']) + '\n' message += temp_text temp_text = sim + str(m) + '\n' message += temp_text for line in diff: str_diff += line message += line + '\n' sql = "INSERT INTO programs_diffs (program1_id, program2_id, similarity, diff) VALUES (" + str( n) + "," + str(r_id) + "," + str(m) + ",\'" + str_diff + "\')" self.db.executesql(sql) self.db.commit_changes() self.message_for_client = message def exposed_get_message(self): return self.message_for_client def exposed_get_program_id(self): if self.db_thread.is_alive: self.db_thread.join() return self.client_program_id if __name__ == '__main__': s = ThreadedServer(Module4Server, hostname='localhost', port=18871, protocol_config={"allow_public_attrs": True}) s.start()
exam_uuid = uuid.uuid4() try: cur.execute( "UPDATE public.exam SET directory=%s WHERE exam_id=%s;", [str(exam_uuid), data["exam_id"]]) self.db_conn.commit() cur.close() return exam_uuid except Exception as err: self.db_conn.rollback() print(err) return None def exposed_split_file(self, exam_id): exam_uuid = get_exam_uuid(exam_id) if is_zip_done(exam_uuid): return exam_uuid pdf_qrcode_reader(exam_uuid) zip_results(exam_uuid) return exam_uuid port = services["file_service"] rypc_server = ThreadedServer(File_service, port=port, protocol_config={ 'allow_public_attrs': True, "allow_pickle": True }) rypc_server.start()
self.sv_list[channel].mailqueue.append((datatype, data)) def dump_object_attr_info(thing): print '%s.%s' % (thing.__class__.__module__, thing.__class__.__name__) for item in dir(thing): print ' .%s' % item print ' Type:', type(getattr(thing, item)) print ' Content:\n ', getattr(thing, item) print if __name__ == '__main__': print 'creating server' srvr = ThreadedServer(BorkedbotSupervisorService, port=29389, protocol_config={ 'allow_all_attrs': True, 'allow_setattr': True, 'allow_delattr': True }) print 'starting server' try: srvr.start() except KeyboardInterrupt: print 'Keyboard break' finally: print 'Server shut down'
self.cpu_cores = sysconf("SC_NPROCESSORS_CONF") logging.info("Detected %d CPU core(s)" % self.cpu_cores) except ValueError: logging.error( "Could not detect number of processors; assuming 1") self.cpu_cores = 1 def __tables__(self): ''' Load rainbow table configurations ''' for algo in self.algorithms: try: table_path = config.get("RainbowTables", algo) if table_path.lower() != 'none': self.rainbow_tables[algo] = table_path if not path.exists(self.rainbow_tables[algo]): logging.warn( "%s rainbow table directory not found (%s)" % (algo, self.rainbow_tables[algo])) except: logging.exception("Failed to read %s configuration from file" % algo) if __name__ == "__main__": from rpyc.utils.server import ThreadedServer agent = ThreadedServer(WeaponSystem, hostname="localhost", port=config.getint("Network", 'lport')) logging.info("Weapon system ready, waiting for orbital control uplink ...") agent.start()
def run(self): server = ThreadedServer(ComServer, port=18813) server.start()
print(f"Registrando Server Novamente") if serverName in self.ListaDiretorio: print(f"Achou item que vai ser registrado novamente") self.ListaDiretorio[serverName] = (ipAdress, portNum) return self.ListaDiretorio[serverName] else: print(f"Item nao registrado") return self.sNaoRegistrado def exposed_removaServer(self, serverName): print(f"Removendo Server") if serverName in self.ListaDiretorio: print(f"Achamos o server a ser removido") ElementoRemovido = self.ListaDiretorio[serverName] print( f"Guardando o elemento: {ElementoRemovido} para ser usado no return" ) self.ListaDiretorio.pop(key=serverName) print(f"Removendo elemento do servidor") return ElementoRemovido else: print(f"Nao achamos o server a ser removido") return self.sNaoRegistrado if __name__ == "__main__": ListaDiretorio = {} print(f"Iniciando servidor de diretórios na porta: {PORTDIR}") SDiretorio = ThreadedServer(SDiretorio(ListaDiretorio), port=12307) SDiretorio.start()
# This function helps keep a global reference to an open RFmx session on the server def GetGlobalInstrMX(self, resourceName, optionString): global instr if instr is not None and not instr.IsDisposed: return instr else: instr = self.exposed_InstrMX.RFmxInstrMX(resourceName, optionString) return instr def ComplexWaveform(self, nettype, param): return self.exposed_NationalInstruments.ComplexWaveform[nettype](param) def exec(self, expression): exec(expression) def eval(self, expression): return eval(expression) # start the server if __name__ == "__main__": port = 18861 print("Starting RFmxService on port " + str(port) + '.') from rpyc.utils.server import ThreadedServer t = ThreadedServer(RFmxService, port = port, protocol_config = {"allow_all_attrs" : True, "allow_setattr": True}) try: t.start() except: pass t.close() print("RFmxService stopped.")
def run(self): service = mycodo_service(self.mycodo) server = ThreadedServer(service, port=18813) server.start()
def start_service(app): service = ClientService(app) server = ThreadedServer(service, port=3000, protocol_config={'allow_public_attrs': True}) server.start()
def run(self): global server server = ThreadedServer(ComServer, port = 18812) server.start()
def server_side(): t = ThreadedServer(TestService, port=18861) t.start()
def runserver(Sv, prt): masterforworker = ThreadedServer( Sv, port = prt,protocol_config={"allow_all_attrs":True, "allow_pickle":True}, listener_timeout=20000) masterforworker.start()
baser = [(int(r1c),R1mask),(int(r2c),R2mask)] cropbg = filter(lambda a: a[0] != 0, basebg) cropr = filter(lambda a: a[0] != 0, baser) negbg = map(lambda a: (-a[0]%256,a[1]), cropbg) negr = map(lambda a: (-a[0]%256,a[1]), cropr) last = 0 i = 0 for a in sorted(negbg): if (a[0] == last): pwmlistbg[i*2-1] = pwmlistbg[i*2-1] | a[1] else: pwmlistbg[i*2] = a[0] pwmlistbg[i*2+1] = a[1] last = a[0] i = i + 1 last = 0 i = 0 for a in sorted(negr): if (a[0] == last): pwmlistr[i*2-1] = pwmlistr[i*2-1] | a[1] else: pwmlistr[i*2] = a[0] pwmlistr[i*2+1] = a[1] last = a[0] i = i + 1 return pwmlistbg+pwmlistr if __name__ == "__main__": server = ThreadedServer(LRKService, hostname="localhost", port = 12345) server.start()
def child_process(host, door): identifier = host + ':' + str(door) chord = rpyc.connect(HOST, ch.CHORD_PORT) process = ThreadedServer(Process(identifier, chord), port=door) process.start()