def _get_server_instance(self, instance): i_key = self._instance_key(instance) service_check_tags = [ 'vcenter_server:{0}'.format(instance.get('name')), 'vcenter_host:{0}'.format(instance.get('host')), ] # Check for ssl configs and generate an appropriate ssl context object ssl_verify = instance.get('ssl_verify', True) ssl_capath = instance.get('ssl_capath', None) if not ssl_verify: context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_NONE elif ssl_capath: context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(capath=ssl_capath) # If both configs are used, log a message explaining the default if not ssl_verify and ssl_capath: self.log.debug("Your configuration is incorrectly attempting to " "specify both a CA path, and to disable SSL " "verification. You cannot do both. Proceeding with " "disabling ssl verification.") if i_key not in self.server_instances: try: server_instance = connect.SmartConnect( host=instance.get('host'), user=instance.get('username'), pwd=instance.get('password'), sslContext=context if not ssl_verify or ssl_capath else None) except Exception as e: err_msg = "Connection to %s failed: %s" % ( instance.get('host'), e) self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=err_msg) raise Exception(err_msg) self.server_instances[i_key] = server_instance # Test if the connection is working try: self.server_instances[i_key].RetrieveContent() self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.OK, tags=service_check_tags) except Exception as e: err_msg = "Connection to %s died unexpectedly: %s" % ( instance.get('host'), e) self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=err_msg) raise Exception(err_msg) return self.server_instances[i_key]
import websocket import asyncio, ssl loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.open_connection('10.87.0.34', 11443, ssl=ssl.SSLContext())) print("the end..") async def test_conn(host, port): _, writer = await asyncio.open_connection(host, port, ssl=ssl.SSLContext()) writer.write(b'ping\n') print("the end..") asyncio.get_event_loop().run_until_complete(test_conn('10.87.0.34', 11443))
def ReadUrl(url): if sys.version_info.major == 3: import urllib.request as urllib2 elif sys.version_info.major == 2: import urllib2 try: import ssl CONTEXT = ssl.SSLContext(ssl.PROTOCOL_SSLv23) except: CONTEXT = None TIMEOUT_URL = 15 print(_("ReadUrl1:\n url = %s") % url) try: req = urllib2.Request(url) req.add_header('User-Agent', RequestAgent()) try: r = urllib2.urlopen(req, None, TIMEOUT_URL, context=CONTEXT) except Exception as e: r = urllib2.urlopen(req, None, TIMEOUT_URL) print("CreateLog Codifica ReadUrl: %s." % str(e)) link = r.read() r.close() dec = "Null" dcod = 0 tlink = link if str(type(link)).find('bytes') != -1: try: tlink = link.decode("utf-8") dec = "utf-8" except Exception as e: dcod = 1 print("ReadUrl2 - Error: ", str(e)) if dcod == 1: dcod = 0 try: tlink = link.decode("cp437") dec = "cp437" except Exception as e: dcod = 1 print("ReadUrl3 - Error:", str(e)) if dcod == 1: dcod = 0 try: tlink = link.decode("iso-8859-1") dec = "iso-8859-1" except Exception as e: dcod = 1 print("CreateLog Codific ReadUrl: ", str(e)) link = tlink elif str(type(link)).find('str') != -1: dec = "str" print("CreateLog Codifica ReadUrl: %s." % dec) except Exception as e: print("ReadUrl5 - Error: ", str(e)) link = None return link
import ssl import atexit sys.path.append("..") import rest from nsx_basic_input import * from case18_nsx_port_rate_input import * from pyVim.connect import SmartConnect, Disconnect from pyVmomi import vim caseName = 'case18_nsx_port_rate' restclient = rest.Rest(NSX_IP, NSX_USER, NSX_PWD, True) context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_NONE serviceInstance = SmartConnect(host=VC_IP, user=VC_USER, pwd=VC_PWD, port=443, sslContext=context) atexit.register(Disconnect, serviceInstance) serviceContent = serviceInstance.RetrieveContent() def getPortRate(): # get lsId and portKey from input parameter NSX_PORT_ID pids = NSX_PORT_ID.split('.') if len(pids) != 2: print "[Error] NSX_PORT_ID:%s is wrong format." % (NSX_PORT_ID)
def __init__(self, ssl_version, *args, **kwargs): context = kwargs['context'] = ssl.SSLContext(ssl_version) cf = kwargs.pop('cert_file') context.load_verify_locations(cf) context.verify_mode = ssl.CERT_REQUIRED httplib.HTTPSConnection.__init__(self, *args, **kwargs)
def mysql_server(unused_port, docker, session_id, mysql_image, mysql_tag, request): print('\nSTARTUP CONTAINER - {0}\n'.format(mysql_tag)) if not request.config.option.no_pull: docker.pull('{}:{}'.format(mysql_image, mysql_tag)) # bound IPs do not work on OSX host = "127.0.0.1" host_port = unused_port() # As TLS is optional, might as well always configure it ssl_directory = os.path.join(os.path.dirname(__file__), 'ssl_resources', 'ssl') ca_file = os.path.join(ssl_directory, 'ca.pem') tls_cnf = os.path.join(os.path.dirname(__file__), 'ssl_resources', 'tls.cnf') ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) ctx.check_hostname = False ctx.load_verify_locations(cafile=ca_file) # ctx.verify_mode = ssl.CERT_NONE container_args = dict(image='{}:{}'.format(mysql_image, mysql_tag), name='aiomysql-test-server-{}-{}'.format( mysql_tag, session_id), ports=[3306], detach=True, host_config=docker.create_host_config( port_bindings={3306: (host, host_port)}, binds={ ssl_directory: { 'bind': '/etc/mysql/ssl', 'mode': 'ro' }, tls_cnf: { 'bind': '/etc/mysql/conf.d/tls.cnf', 'mode': 'ro' }, }), environment={'MYSQL_ROOT_PASSWORD': '******'}) container = docker.create_container(**container_args) try: docker.start(container=container['Id']) # MySQL restarts at least 4 times in the container before its ready time.sleep(10) server_params = { 'host': host, 'port': host_port, 'user': '******', 'password': '******', 'ssl': ctx } delay = 0.001 for i in range(100): try: connection = pymysql.connect( db='mysql', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor, **server_params) with connection.cursor() as cursor: cursor.execute("SHOW VARIABLES LIKE '%ssl%';") result = cursor.fetchall() result = { item['Variable_name']: item['Value'] for item in result } assert result['have_ssl'] == "YES", \ "SSL Not Enabled on docker'd MySQL" cursor.execute("SHOW STATUS LIKE 'Ssl_version%'") result = cursor.fetchone() # As we connected with TLS, it should start with that :D assert result['Value'].startswith('TLS'), \ "Not connected to the database with TLS" # Create Databases cursor.execute('CREATE DATABASE test_pymysql ' 'DEFAULT CHARACTER SET utf8 ' 'DEFAULT COLLATE utf8_general_ci;') cursor.execute('CREATE DATABASE test_pymysql2 ' 'DEFAULT CHARACTER SET utf8 ' 'DEFAULT COLLATE utf8_general_ci;') # Do MySQL8+ Specific Setup if mysql_tag in ('8.0', ): # Create Users to test SHA256 cursor.execute('CREATE USER user_sha256 ' 'IDENTIFIED WITH "sha256_password" ' 'BY "pass_sha256"') cursor.execute('CREATE USER nopass_sha256 ' 'IDENTIFIED WITH "sha256_password"') cursor.execute('CREATE USER user_caching_sha2 ' 'IDENTIFIED ' 'WITH "caching_sha2_password" ' 'BY "pass_caching_sha2"') cursor.execute('CREATE USER nopass_caching_sha2 ' 'IDENTIFIED ' 'WITH "caching_sha2_password" ' 'PASSWORD EXPIRE NEVER') cursor.execute('FLUSH PRIVILEGES') break except Exception as err: time.sleep(delay) delay *= 2 else: pytest.fail("Cannot start MySQL server") container['host'] = host container['port'] = host_port container['conn_params'] = server_params yield container finally: print('\nTEARDOWN CONTAINER - {0}\n'.format(mysql_tag)) docker.kill(container=container['Id']) docker.remove_container(container['Id'])
def main(): # args = get_args() ls = [] while True: vm_name = raw_input("enter the vm name or ip if u know") if vm_name == 'done': break else: if len(vm_name) > 0: ls.append(vm_name) else: continue requests.packages.urllib3.disable_warnings() # Disabling SSL certificate verification context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE # connect this thing si = SmartConnect(host='1.1.1.1', user='******', pwd='abcd', port=443, sslContext=context) # disconnect this thing atexit.register(Disconnect, si) for i in ls: print 'give information for vm', i vm = None if re.search('^[0-9].*', i): search_index = si.content.searchIndex vm = search_index.FindByIp(ip=i, vmSearch=True) print "vm found using ip hahahahaha" elif re.search('^[A-za-z]*', i): content = si.RetrieveContent() vm = get_obj(content, [vim.VirtualMachine], i) print "vm found using name hahahahaha" if vm: choice = raw_input('Wanna Add or delete the disk say add or del') if choice == 'ADD': disk_size = raw_input("enter the disk size in GB") disk_type = raw_input( "enter the disk type either thin or thick") add_disk(vm, si, disk_size, disk_type) elif choice == 'del': confirm = raw_input("DO you want to delete this disk yes/no") if confirm == 'yes': number = raw_input("Enter the number of the disk:") lang = raw_input("Enter the language used in the Vcenter") delete_virtual_disk(si, vm, number, lang) print('VM HDD "{}" successfully deleted.'.format(number)) else: print 'please do some other job' else: print "VM not found hehehehe"
def lookup_journal_in_doaj(issn, bypass_cert_verification=False): """ Take an ISSN and check if the corresponding journal exists in DOAJ. This method looks up an ISSN in the Directory of Open Access Journals (DOAJ, https://doaj.org). This is a simple existence check and will not return any additional metadata (except for the journal title). It is also important to note that there is no additional effort to test the validity of the given ISSN - if a negative result is returned, the ISSN might be invalid, but it might also belong to a journal which is not registered in DOAJ. Args: issn: A string representing an issn Returns: A dict with a key 'data_received'. If data was received from DOAJ, this key will have the value True and the dict will have a second entry 'data' which contains the lookup result: {'in_doaj': True, 'title': 'Frontiers in Human Neuroscience', } or {'in_doaj': False} If data extraction failed, 'data_received' will be False and the dict will contain a second entry 'error_msg' with a string value stating the reason. """ headers = {"Accept": "application/json"} ret_value = {'data_received': True} url = "https://doaj.org/api/v1/search/journals/issn:" + issn req = urllib2.Request(url, None, headers) try: if bypass_cert_verification: empty_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) response = urllib2.urlopen(req, context=empty_context) else: response = urllib2.urlopen(req) content_string = response.read() json_dict = json.loads(content_string) ret_data = {} if "results" in json_dict and len(json_dict["results"]) > 0: ret_data["in_doaj"] = True # Try to extract the journal title - useful for error correction journal = json_dict["results"][0] try: ret_data["title"] = journal["bibjson"]["title"] except KeyError: ret_data["title"] = "" else: ret_data["in_doaj"] = False ret_value['data'] = ret_data except urllib2.HTTPError as httpe: ret_value['data_received'] = False code = str(httpe.getcode()) ret_value['error_msg'] = "HTTPError: {} - {}".format( code, httpe.reason) except ValueError as ve: ret_value['data_received'] = False msg = "ValueError while parsing JSON: {}" ret_value['error_msg'] = msg.format(ve.message) return ret_value
def build_server(self) -> ssl.SSLContext: context = ssl.SSLContext(PROTOCOL) context.load_cert_chain(certfile=self._certfile, keyfile=self._keyfile) return context
def __init__(self, context=None, version=None, certify=None, hostify=None, certedhost="", keypath=None, certpath=None, cafilepath=None, **kwa): """ Initialization method for instance. IF no context THEN create one IF no version THEN create using library default IF certify is not None then use certify else use default IF hostify is not none the use hostify else use default Parameters: context = context object for tls/ssl If None use default version = ssl version If None use default certify = cert requirement If None use default ssl.CERT_NONE = 0 ssl.CERT_OPTIONAL = 1 ssl.CERT_REQUIRED = 2 keypath = pathname of local client side PKI private key file path If given apply to context certpath = pathname of local client side PKI public cert file path If given apply to context cafilepath = Cert Authority file path to use to verify server cert If given apply to context hostify = verify server hostName If None use default certedhost = server's certificate common name (hostname) to check against """ super(ClientTls, self).__init__(**kwa) self._connected = False # attributed supporting connected property if context is None: # create context if not version: # use default context context = ssl.create_default_context( purpose=ssl.Purpose.SERVER_AUTH) hostify = hostify if hostify is not None else context.check_hostname context.check_hostname = hostify certify = certify if certify is not None else context.verify_mode context.verify_mode = certify else: # create context with specified protocol version context = ssl.SSLContext(version) # disable bad protocols versions context.options |= ssl.OP_NO_SSLv2 context.options |= ssl.OP_NO_SSLv3 # disable compression to prevent CRIME attacks (OpenSSL 1.0+) context.options |= getattr(ssl._ssl, "OP_NO_COMPRESSION", 0) context.verify_mode = certify = ssl.CERT_REQUIRED if certify is None else certify context.check_hostname = hostify = True if hostify else False self.context = context self.certedhost = certedhost or self.hostname if cafilepath: context.load_verify_locations(cafile=cafilepath, capath=None, cadata=None) elif context.verify_mode != ssl.CERT_NONE: context.load_default_certs(purpose=ssl.Purpose.SERVER_AUTH) if keypath or certpath: context.load_cert_chain(certfile=certpath, keyfile=keypath) if hostify and certify == ssl.CERT_NONE: raise ValueError("Check Hostname needs a SSL context with " "either CERT_OPTIONAL or CERT_REQUIRED")
def __init__(self, parent, timeout): self.host = parent._parent.host self.port = parent._parent.port self._read_buffer = None self._socket = None self.ssl = parent._parent.ssl deadline = time.time() + timeout try: self._socket = socket.create_connection((self.host, self.port), timeout) self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) if len(self.ssl) > 0: try: if hasattr(ssl, 'SSLContext'): # Python2.7 and 3.2+, or backports.ssl ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) if hasattr(ssl_context, "options"): ssl_context.options |= getattr(ssl, "OP_NO_SSLv2", 0) ssl_context.options |= getattr(ssl, "OP_NO_SSLv3", 0) ssl_context.verify_mode = ssl.CERT_REQUIRED ssl_context.check_hostname = True # redundant with match_hostname ssl_context.load_verify_locations(self.ssl["ca_certs"]) self._socket = ssl_context.wrap_socket(self._socket, server_hostname=self.host) else: # this does not disable SSLv2 or SSLv3 self._socket = ssl.wrap_socket( self._socket, cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_SSLv23, ca_certs=self.ssl["ca_certs"]) except IOError as err: self._socket.close() if 'EOF occurred in violation of protocol' in str( err) or 'sslv3 alert handshake failure' in str(err): # probably on an older version of OpenSSL raise ReqlDriverError( "SSL handshake failed, likely because Python is linked against an old version of OpenSSL " "that does not support either TLSv1.2 or any of the allowed ciphers. This can be worked " "around by lowering the security setting on the server with the options " "`--tls-min-protocol TLSv1 --tls-ciphers " "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:AES256-SHA` (see server log for more " "information): %s" % str(err) ) else: raise ReqlDriverError( "SSL handshake failed (see server log for more information): %s" % str(err)) try: match_hostname(self._socket.getpeercert(), hostname=self.host) except CertificateError: self._socket.close() raise parent._parent.handshake.reset() response = None while True: request = parent._parent.handshake.next_message(response) if request is None: break # This may happen in the `V1_0` protocol where we send two requests as # an optimization, then need to read each separately if request is not "": self.sendall(request) # The response from the server is a null-terminated string response = b'' while True: char = self.recvall(1, deadline) if char == b'\0': break response += char except (ReqlAuthError, ReqlTimeoutError): self.close() raise except ReqlDriverError as ex: self.close() error = str(ex)\ .replace('receiving from', 'during handshake with')\ .replace('sending to', 'during handshake with') raise ReqlDriverError(error) except socket.timeout as ex: self.close() raise ReqlTimeoutError(self.host, self.port) except Exception as ex: self.close() raise ReqlDriverError("Could not connect to %s:%s. Error: %s" % (self.host, self.port, str(ex)))
def _get_server_instance(self, instance): i_key = self._instance_key(instance) tags = instance.get('tags', []) service_check_tags = [ 'vcenter_server:{0}'.format(instance.get('name')), 'vcenter_host:{0}'.format(instance.get('host')), ] + tags service_check_tags = list(set(service_check_tags)) # Check for ssl configs and generate an appropriate ssl context object ssl_verify = instance.get('ssl_verify', True) ssl_capath = instance.get('ssl_capath', None) if not ssl_verify: context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_NONE elif ssl_capath: context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(capath=ssl_capath) # If both configs are used, log a message explaining the default if not ssl_verify and ssl_capath: self.log.debug("Your configuration is incorrectly attempting to " "specify both a CA path, and to disable SSL " "verification. You cannot do both. Proceeding with " "disabling ssl verification.") if i_key not in self.server_instances: self.log.debug("Creating server_instance for instance %s", i_key) try: # Object returned by SmartConnect is a ServerInstance # https://www.vmware.com/support/developer/vc-sdk/visdk2xpubs/ReferenceGuide/vim.ServiceInstance.html server_instance = connect.SmartConnect( host=instance.get('host'), user=instance.get('username'), pwd=instance.get('password'), sslContext=context if not ssl_verify or ssl_capath else None) except Exception as e: err_msg = "Connection to %s failed: %s" % ( instance.get('host'), e) self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=err_msg) raise Exception(err_msg) self.server_instances[i_key] = server_instance # Test if the connection is working try: self.log.debug("Testing connection to the server_instance for %s", i_key) self.server_instances[i_key].RetrieveContent() self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.OK, tags=service_check_tags) except Exception as e: err_msg = "Connection to %s died unexpectedly: %s" % ( instance.get('host'), e) self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=err_msg) raise Exception(err_msg) self.log.debug( "Successfully connected to server_instance %s on host %s", self.server_instances[i_key], instance.get("host")) return self.server_instances[i_key]
# Make filepaths relative to settings. path = lambda root, *a: os.path.join(root, *a) ROOT = os.path.dirname(os.path.abspath(__file__)) define("config", default=None, help="tornado config file") define("debug", default=True, help="debug mode") SITE_ROOT = path(ROOT, "sites") CERT_ROOT = "/etc/letsencrypt/live/www.tun0.com/" # Enable basic logging. options.parse_command_line() # TLSv1.2 only. ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2) # PFS only, AES only, GCM before CBC. ssl_context.set_ciphers( "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA" ) # Enforce cipher prefernce order server side. ssl_context.options += ssl.OP_CIPHER_SERVER_PREFERENCE # Generate new ECDH seeding material for each and every TLS handshake. ssl_context.options += ssl.OP_SINGLE_ECDH_USE # Load up our cert and key. ssl_context.load_cert_chain(certfile=os.path.join(CERT_ROOT, "fullchain.pem"), keyfile=os.path.join(CERT_ROOT, "privkey.pem"))
def _request(url, post=False, user=None, passwd=None, allow_TLSv1=False, **kwargs): timeout = float(kwargs.pop('timeout', g_timeout)) url_values = urlencode(kwargs) if url_values: url += '?' + url_values logger.debug('Accessing URL %s' % url) url_args = {'timeout': timeout} if allow_TLSv1: url_args['context'] = ssl.SSLContext(ssl.PROTOCOL_TLSv1) opener = None req = Request(url) if post: logger.debug('POST data: \n%s' % post.decode('utf8')) req.data = post req.add_header('Accept', '*/*') itry = 0 while True: itry += 1 try: urlopen_ = opener.open if opener else urlopen while True: try: resp = urlopen_(req, **url_args) break except TypeError: del url_args['context'] # context not avail before 3.4.3 logger.debug('Response: %s' % resp.getcode()) if resp.getcode() == 204: raise EmptyResult(url) return resp except HTTPError as e: if e.code == 413: raise RequestEntityTooLarge(url) elif e.code == 401: headers = getattr(e, 'headers', e.hdrs) realm = get_realm_from_auth_header(headers) if itry == 1 and user is not None: auth_handler = HTTPDigestAuthHandler() auth_handler.add_password(realm=realm, uri=url, user=user, passwd=passwd or '') opener = build_opener(auth_handler) continue else: logger.error('authentication failed for realm "%s" when ' 'accessing url "%s"' % (realm, url)) raise e else: logger.error('error content returned by server:\n%s' % e.read()) raise e break
def _get_service_instance(host, username, password, protocol, port, mechanism, principal, domain): ''' Internal method to authenticate with a vCenter server or ESX/ESXi host and return the service instance object. ''' log.trace('Retrieving new service instance') token = None if mechanism == 'userpass': if username is None: raise salt.exceptions.CommandExecutionError( 'Login mechanism userpass was specified but the mandatory ' 'parameter \'username\' is missing') if password is None: raise salt.exceptions.CommandExecutionError( 'Login mechanism userpass was specified but the mandatory ' 'parameter \'password\' is missing') elif mechanism == 'sspi': if principal is not None and domain is not None: try: token = get_gssapi_token(principal, host, domain) except Exception as exc: raise salt.exceptions.VMwareConnectionError(str(exc)) else: err_msg = 'Login mechanism \'{0}\' was specified but the' \ ' mandatory parameters are missing'.format(mechanism) raise salt.exceptions.CommandExecutionError(err_msg) else: raise salt.exceptions.CommandExecutionError( 'Unsupported mechanism: \'{0}\''.format(mechanism)) try: log.trace('Connecting using the \'{0}\' mechanism, with username ' '\'{1}\''.format(mechanism, username)) service_instance = SmartConnect(host=host, user=username, pwd=password, protocol=protocol, port=port, b64token=token, mechanism=mechanism) except TypeError as exc: if 'unexpected keyword argument' in exc.message: log.error('Initial connect to the VMware endpoint failed with {0}'. format(exc.message)) log.error( 'This may mean that a version of PyVmomi EARLIER than 6.0.0.2016.6 is installed.' ) log.error('We recommend updating to that version or later.') raise except Exception as exc: default_msg = 'Could not connect to host \'{0}\'. ' \ 'Please check the debug log for more information.'.format(host) try: if (isinstance(exc, vim.fault.HostConnectFault) and '[SSL: CERTIFICATE_VERIFY_FAILED]' in exc.msg) or \ '[SSL: CERTIFICATE_VERIFY_FAILED]' in str(exc): import ssl service_instance = SmartConnect( host=host, user=username, pwd=password, protocol=protocol, port=port, sslContext=ssl._create_unverified_context(), b64token=token, mechanism=mechanism) else: err_msg = exc.msg if hasattr(exc, 'msg') else default_msg log.trace(exc) raise salt.exceptions.VMwareConnectionError(err_msg) except Exception as exc: if 'certificate verify failed' in str(exc): import ssl context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE try: service_instance = SmartConnect(host=host, user=username, pwd=password, protocol=protocol, port=port, sslContext=context, b64token=token, mechanism=mechanism) except Exception as exc: err_msg = exc.msg if hasattr(exc, 'msg') else str(exc) log.trace(err_msg) raise salt.exceptions.VMwareConnectionError( 'Could not connect to host \'{0}\': ' '{1}'.format(host, err_msg)) else: err_msg = exc.msg if hasattr(exc, 'msg') else default_msg log.trace(exc) raise salt.exceptions.VMwareConnectionError(err_msg) atexit.register(Disconnect, service_instance) return service_instance
def build_client(self) -> ssl.SSLContext: context = ssl.SSLContext(PROTOCOL) context.load_verify_locations(self._certfile) context.verify_mode = ssl.CERT_REQUIRED return context
# Author: Vikas Shitole # Website: www.vThinkBeyondVM.com # Product: vCenter server/EVC (Enhanced Compatibility Mode) # Description: Script to get EVC cluster state, current EVC Mode, cpu feature capability, maksed feature set # Reference: http://vthinkbeyondvm.com/tutorial-how-to-manage-enhanced-vmotion-compatibility-evc-using-vsphere-python-sdk-pyvmomi # How to setup pyVmomi environment?: http://vthinkbeyondvm.com/how-did-i-get-started-with-the-vsphere-python-sdk-pyvmomi-on-ubuntu-distro/ from pyVim.connect import SmartConnect, Disconnect from pyVmomi import vim import atexit import ssl import sys #Script to get Max EVC Mode supported on all the hosts in the cluster s = ssl.SSLContext(ssl.PROTOCOL_TLSv1) s.verify_mode = ssl.CERT_NONE si = SmartConnect(host="10.160.50.60", user="******", pwd="VMware#12", sslContext=s) content = si.content cluster_name = "vThinkBVMCluster" # Below method helps us to get MOR of the object (vim type) that we passed. def get_obj(content, vimtype, name): obj = None container = content.viewManager.CreateContainerView( content.rootFolder, vimtype, True) for c in container.view: if name: if c.name == name:
cassandra_username = settings.get('USERNAME', fallback=None) cassandra_password = settings.get('PASSWORD', fallback=None) # cassandra_local_datacenter = settings.get('LOCAL_DATACENTER', fallback=None) cassandra_keyspace = settings.get('KEYSPACE', fallback=None) # SSL cassandra_use_ssl = settings.getboolean('USE_SSL', fallback=False) cassandra_ssl_cert_file = settings.get('SSL_CERT_FILE', fallback=None) cassandra_ssl_key_file = settings.get('SSL_KEY_FILE', fallback=None) cassandra_ssl_password = settings.get('SSL_PASSWORD', fallback=None) cassandra_ssl = None if cassandra_use_ssl: cassandra_ssl = ssl.SSLContext(ssl.PROTOCOL_TLS) cassandra_ssl.load_cert_chain(certfile=cassandra_ssl_cert_file, keyfile=cassandra_ssl_key_file, password=cassandra_ssl_password) class Client: """ Cassandra client. """ cassandra_connection = None @classmethod def _open_connection(cls): """
log("Server Cleaned", message)) if (userData == "lowVoltage"): print("IntelliCoffee needs some juice!\n\n") if (userData == "connected"): print("IntelliCoffee is connected") await websocket.send("") except Exception as e: pass except Exception as e: pass except Exception as e: pass finally: try: await unregister(websocket) except Exception as e: pass except Exception as e: pass ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) start_server = websockets.serve(data, "0.0.0.0", 20001) print('Server has started') asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()
# coding=utf-8 """ Python SSL Server ref:https://docs.python.org/2/library/ssl.html :copyright: (c) 2016 by fangpeng(@beginman.cn). :license: MIT, see LICENSE for more details. """ import socket import ssl import _ssl # The Class `SSLContext`: Create a new SSL context with protocol context = ssl.SSLContext(_ssl.PROTOCOL_TLSv1) # ssl.PROTOCOL_TLSv1 # Load a private key and the corresponding certificate # If keyfile is None, we need the third argument password context.load_cert_chain(certfile="cert.pem", keyfile="key.pem") bindsocket = socket.socket() bindsocket.bind(('127.0.0.1', 8890)) bindsocket.listen(5) def do_something(connstream, data): print len(data) return True def deal_with_client(connstream): data = connstream.recv(1024)
import backports.ssl_match_hostname ssl_match_hostname = backports.ssl_match_hostname.match_hostname SSLCertificateError = backports.ssl_match_hostname.CertificateError if hasattr(ssl, 'SSLContext'): if hasattr(ssl, 'create_default_context'): # Python 2.7.9+, 3.4+ # Note that the naming of ssl.Purpose is confusing; the purpose # of a context is to authentiate the opposite side of the connection. _client_ssl_defaults = ssl.create_default_context( ssl.Purpose.SERVER_AUTH) _server_ssl_defaults = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH) else: # Python 3.2-3.3 _client_ssl_defaults = ssl.SSLContext(ssl.PROTOCOL_SSLv23) _client_ssl_defaults.verify_mode = ssl.CERT_REQUIRED _client_ssl_defaults.load_verify_locations(certifi.where()) _server_ssl_defaults = ssl.SSLContext(ssl.PROTOCOL_SSLv23) if hasattr(ssl, 'OP_NO_COMPRESSION'): # Disable TLS compression to avoid CRIME and related attacks. # This constant wasn't added until python 3.3. _client_ssl_defaults.options |= ssl.OP_NO_COMPRESSION _server_ssl_defaults.options |= ssl.OP_NO_COMPRESSION else: # Python 2.6-2.7.8 _client_ssl_defaults = dict(cert_reqs=ssl.CERT_REQUIRED, ca_certs=certifi.where()) _server_ssl_defaults = {}
def run_New_Test(dirPath, confFile, loggerHandler): ''' The method start a new test asking the technician which csv file to load from the test repository create a new log file for the test in allTest folder and create if wanted specific log for the test in specific folder that the technician will choose running the flask server using the port and ip taken from the config file ''' loggerHandler.start_Test(consts.CLI_SESSION) loggerHandler.print_To_Terminal(consts.SET_CSV_FILE_MESSAGE) inputAnswer = get_input() if (inputAnswer != "quit"): try: ### initialize the test definition from the csv file csvFileParser = CsvFileParser( os.path.normpath( os.path.join( str(dirPath), confFile.getElementsByTagName("testRepoPath") [0].firstChild.data, inputAnswer)), confFile, dirPath) testDefinition = TestDefinition( csvFileParser.initializeTestDefinition(), csvFileParser.find_Number_Of_Cols()) except IOError as e: ### in case there is file not found error try to enter new csv file name loggerHandler.print_To_Terminal(e.message) run_New_Test(dirPath, confFile, loggerHandler) insertToFolderAnswer = add_Log_Of_Test_To_Specific_Folder( loggerHandler) if (insertToFolderAnswer == "yes"): loggerHandler.print_To_Terminal(consts.TYPE_NAME_OF_FOLDER) insertToFolderAnswer = raw_input() try: loggerHandler.start_Test(inputAnswer, insertToFolderAnswer) # if decided to enter to folder create two logs one in the all test folder ### if decided to enter to folder create two logs one in the all test folder except Exception as E: loggerHandler.print_To_Terminal(E.message) run_New_Test(dirPath, confFile, loggerHandler) loggerHandler.print_to_Logs_Files( consts.SELECT_TO_ADD_TEST_MESSAGE + inputAnswer + consts.SELECT_TO_ADD_FOLDER_MESSAGE + insertToFolderAnswer, True) loggerHandler.print_To_Terminal('The test is starting now!') else: loggerHandler.start_Test(inputAnswer) loggerHandler.print_to_Logs_Files( consts.SELECTED_TEST_FROM_USER_MESSAGE + str(inputAnswer) + " is starting now", True) cliHandler = CLIHandler(inputAnswer, confFile, dirPath, loggerHandler, testDefinition) # initialize cli session handler cliHandler.start() flaskServer.enodeBController = ENodeBController(cliHandler.engine) ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) # use TLS to avoid POODLE ctx.verify_mode = ssl.CERT_REQUIRED ctx.set_ciphers(consts.WINNF_APPROVED_CIPHERS) ctx.load_verify_locations( os.path.normpath( os.path.join(str(dirPath), get_Element_From_Config_File(confFile, "caCerts")))) ctx.load_cert_chain( os.path.normpath( os.path.join( str(dirPath), get_Element_From_Config_File(confFile, "pemFilePath"))), os.path.normpath( os.path.join( str(dirPath), get_Element_From_Config_File(confFile, "keyFilePath")))) # get the certificates for https from config file cliHandler.server = flaskServer.runFlaskServer( get_Element_From_Config_File(confFile, "hostIp"), int(get_Element_From_Config_File(confFile, "port")), ctx) # run flask server using the host name and port from conf file if (cliHandler.engine.check_Validation_Error()): cliHandler.stop_Thread_Due_To_Exception() if (inputAnswer == "quit"): loggerHandler.print_To_Terminal(consts.QUIT_PROGRAM_MESSAGE) sys.exit()
import ssl from asyncio import StreamWriter, StreamReader, BaseEventLoop, wait_for, TimeoutError from typing import Coroutine SECURE_CONTEXT = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) SECURE_CONTEXT.check_hostname = True INSECURE_CONTEXT = ssl.SSLContext() INSECURE_CONTEXT.check_hostname = False class Connection: __slots__ = ("loop", "reader", "writer", "pool") def __init__(self, loop: BaseEventLoop, reader: StreamReader, writer: StreamWriter, pool): self.loop = loop self.reader = reader self.writer = writer self.pool = pool def sendall(self, data: bytes) -> Coroutine: """ :param data: :return: """ self.writer.write(data) return self.writer.drain()
if __name__ == "__main__": parser = argparse.ArgumentParser(description="FaceRTC") parser.add_argument("--cert-file", help="SSL certificate file (for HTTPS)") parser.add_argument("--key-file", help="SSL key file (for HTTPS)") parser.add_argument("--port", type=int, default=8080, help="Port for HTTP server (default: 8080)") parser.add_argument("--verbose", "-v", action="count") args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG) if args.cert_file: ssl_context = ssl.SSLContext() ssl_context.load_cert_chain(args.cert_file, args.key_file) else: ssl_context = None app = web.Application() app.on_shutdown.append(on_shutdown) app.router.add_get("/", index) app.router.add_get("/sample.html", sample_html) app.router.add_get("/js/main.js", main_js) app.router.add_get("/js/video_stream.js", video_stream_js) app.router.add_get("/js/sample.js", sample_js) app.router.add_post("/offer", offer) MTCNNGraph = FaceRecGraph() FaceGraph = FaceRecGraph() face_detect = MTCNNDetect(
def __init__(self, tag=None, hostname=None, api_key=None, timeout=None, http=False, ssl_context=None): self._log = logging.getLogger(__name__).log self.tag = tag self.hostname = hostname self.api_key = None self.timeout = timeout self.ssl_context = ssl_context self._log(DEBUG3, 'Python version: %s', sys.version) self._log(DEBUG3, 'xml.etree.ElementTree version: %s', etree.VERSION) self._log(DEBUG3, 'ssl: %s', ssl.OPENSSL_VERSION) self._log(DEBUG3, 'pan-python version: %s', __version__) if self.timeout is not None: try: self.timeout = int(self.timeout) if not self.timeout > 0: raise ValueError except ValueError: raise PanWFapiError('Invalid timeout: %s' % self.timeout) if self.ssl_context is not None: try: ssl.SSLContext(ssl.PROTOCOL_SSLv23) except AttributeError: raise PanWFapiError('SSL module has no SSLContext()') elif _have_certifi: self.ssl_context = self._certifi_ssl_context() # handle Python versions with no ssl.CertificateError if hasattr(ssl, 'CertificateError'): self._certificateerror = ssl.CertificateError else: self._certificateerror = NotImplementedError # XXX Can't happen init_panrc = {} # .panrc args from constructor if hostname is not None: init_panrc['hostname'] = hostname if api_key is not None: init_panrc['api_key'] = api_key try: panrc = pan.rc.PanRc(tag=self.tag, init_panrc=init_panrc) except pan.rc.PanRcError as msg: raise PanWFapiError(str(msg)) if 'api_key' in panrc.panrc: self.api_key = panrc.panrc['api_key'] if 'hostname' in panrc.panrc: self.hostname = panrc.panrc['hostname'] else: self.hostname = _cloud_server if self.api_key is None: raise PanWFapiError('api_key required') if http: self.uri = 'http://%s' % self.hostname else: self.uri = 'https://%s' % self.hostname
def __init__(self, tag=None, api_username=None, api_password=None, api_key=None, hostname=None, port=None, serial=None, use_http=False, use_get=False, timeout=None, ssl_context=None): self._log = logging.getLogger(__name__).log self.tag = tag self.api_username = None self.api_password = None self.api_key = None self.hostname = None self.port = port self.serial = serial self.use_get = use_get self.timeout = timeout self.ssl_context = ssl_context self._log(DEBUG3, 'Python version: %s', sys.version) self._log(DEBUG3, 'xml.etree.ElementTree version: %s', etree.VERSION) self._log(DEBUG3, 'pan-python version: %s', __version__) if self.port is not None: try: self.port = int(self.port) if self.port < 1 or self.port > 65535: raise ValueError except ValueError: raise PanXapiError('Invalid port: %s' % self.port) if self.timeout is not None: try: self.timeout = int(self.timeout) if not self.timeout > 0: raise ValueError except ValueError: raise PanXapiError('Invalid timeout: %s' % self.timeout) if self.ssl_context is not None: try: ssl.SSLContext(ssl.PROTOCOL_SSLv23) except AttributeError: raise PanXapiError('SSL module has no SSLContext()') init_panrc = {} # .panrc args from constructor if api_username is not None: init_panrc['api_username'] = api_username if api_password is not None: init_panrc['api_password'] = api_password if api_key is not None: init_panrc['api_key'] = api_key if hostname is not None: init_panrc['hostname'] = hostname if port is not None: init_panrc['port'] = port if serial is not None: init_panrc['serial'] = serial try: panrc = pan.rc.PanRc(tag=self.tag, init_panrc=init_panrc) except pan.rc.PanRcError as msg: raise PanXapiError(str(msg)) # If we get a api_username and api_password in the constructor # and no api_key, delete api_key inherited from .panrc if any. # Prevent confusion when you specify a api_username and # api_password but they are not used due to existence of # api_key in .panrc. if ('api_key' in panrc.panrc and api_username is not None and api_password is not None and api_key is None): del panrc.panrc['api_key'] self._log(DEBUG1, 'ignoring .panrc inherited api_key') if 'api_username' in panrc.panrc: self.api_username = panrc.panrc['api_username'] if 'api_password' in panrc.panrc: self.api_password = panrc.panrc['api_password'] if 'api_key' in panrc.panrc: self.api_key = panrc.panrc['api_key'] if 'hostname' in panrc.panrc: self.hostname = panrc.panrc['hostname'] if 'port' in panrc.panrc: self.port = panrc.panrc['port'] try: self.port = int(self.port) if self.port < 1 or self.port > 65535: raise ValueError except ValueError: raise PanXapiError('Invalid port from .panrc: %s' % self.port) if 'serial' in panrc.panrc: self.serial = panrc.panrc['serial'] if self.hostname is None: raise PanXapiError('hostname argument required') if self.api_key is None and (self.api_username is None or self.api_password is None): raise PanXapiError('api_key or api_username and ' + 'api_password arguments required') if use_http: scheme = 'http' else: scheme = 'https' self.uri = '%s://%s' % (scheme, self.hostname) if self.port is not None: self.uri += ':%s' % self.port self.uri += '/api/' if _legacy_urllib: self._log(DEBUG2, 'using legacy urllib')
async def test_conn(host, port): _, writer = await asyncio.open_connection(host, port, ssl=ssl.SSLContext()) writer.write(b'ping\n') print("the end..")
def run_server(loop, *, listen_addr=('127.0.0.1', 0), use_ssl=False, router=None): properties = {} transports = [] class HttpRequestHandler: def __init__(self, addr): if isinstance(addr, tuple): host, port = addr self.host = host self.port = port else: self.host = host = 'localhost' self.port = port = 0 self.address = addr self._url = '{}://{}:{}'.format('https' if use_ssl else 'http', host, port) def __getitem__(self, key): return properties[key] def __setitem__(self, key, value): properties[key] = value def url(self, *suffix): return urllib.parse.urljoin(self._url, '/'.join(str(s) for s in suffix)) class TestHttpServer(server.ServerHttpProtocol): def connection_made(self, transport): transports.append(transport) super().connection_made(transport) def handle_request(self, message, payload): if properties.get('close', False): return if properties.get('noresponse', False): yield from asyncio.sleep(99999) for hdr, val in message.headers.items(): if (hdr == 'EXPECT') and (val == '100-continue'): self.transport.write(b'HTTP/1.0 100 Continue\r\n\r\n') break if router is not None: body = yield from payload.read() rob = router(self, properties, self.transport, message, body) rob.dispatch() else: response = aiohttp.Response(self.writer, 200, message.version) text = b'Test message' response.add_header('Content-type', 'text/plain') response.add_header('Content-length', str(len(text))) response.send_headers() response.write(text) response.write_eof() if use_ssl: here = os.path.join(os.path.dirname(__file__), '..', 'tests') keyfile = os.path.join(here, 'sample.key') certfile = os.path.join(here, 'sample.crt') sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23) sslcontext.load_cert_chain(certfile, keyfile) else: sslcontext = None def run(loop, fut): thread_loop = asyncio.new_event_loop() asyncio.set_event_loop(thread_loop) if isinstance(listen_addr, tuple): host, port = listen_addr server_coroutine = thread_loop.create_server( lambda: TestHttpServer(keep_alive=0.5), host, port, ssl=sslcontext) else: try: os.unlink(listen_addr) except FileNotFoundError: pass server_coroutine = thread_loop.create_unix_server( lambda: TestHttpServer(keep_alive=0.5), listen_addr, ssl=sslcontext) server = thread_loop.run_until_complete(server_coroutine) waiter = asyncio.Future(loop=thread_loop) loop.call_soon_threadsafe( fut.set_result, (thread_loop, waiter, server.sockets[0].getsockname())) try: thread_loop.run_until_complete(waiter) finally: # call pending connection_made if present run_briefly(thread_loop) # close opened transports for tr in transports: tr.close() run_briefly(thread_loop) # call close callbacks server.close() thread_loop.stop() thread_loop.close() gc.collect() fut = asyncio.Future(loop=loop) server_thread = threading.Thread(target=run, args=(loop, fut)) server_thread.start() thread_loop, waiter, addr = loop.run_until_complete(fut) try: yield HttpRequestHandler(addr) finally: thread_loop.call_soon_threadsafe(waiter.set_result, None) server_thread.join()
trustAZ1_subnet = os.environ['trustAZ1Subnet'] trustAZ2_subnet = os.environ['trustAZ2Subnet'] untrustAZ1_subnet = os.environ['untrustAZ1Subnet'] untrustAZ2_subnet = os.environ['untrustAZ2Subnet'] vpc_summary_route = os.environ['VpcSummaryRoute'] vpc_cidr_block = os.environ['VpcCidrBlock'] fw1instanceId = os.environ['fw1instanceId'] fw2instanceId = os.environ['fw2instanceId'] api_key = os.environ['apikey'] logger = logging.getLogger() logger.setLevel(logging.INFO) lambda_client = boto3.client('lambda') ec2_client = boto3.client('ec2') gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) subnets = [] class FWNotUpException(Exception): # Constructor or Initializer def __init__(self, value): self.value = value # __str__ is to print() the value def __str__(self): return (repr(self.value))
from pyVmomi import vim alarm_name = os.getenv('VMWARE_ALARM_NAME', 'debug_VMWARE_ALARM_NAME') alarm_target_name = os.getenv('VMWARE_ALARM_TARGET_NAME', 'debug_VMWARE_ALARM_TARGET_NAME') event_decscription = os.getenv('VMWARE_ALARM_EVENTDESCRIPTION', 'debug_VMWARE_ALARM_EVENTDESCRIPTION') alarm_value = os.getenv('VMWARE_ALARM_ALARMVALUE', 'debug_VMWARE_ALARM_EVENTDESCRIPTION') alarm_vm = os.getenv('VMWARE_ALARM_EVENT_VM', 'debug_VMWARE_ALARM_EVENT_VM') alarm_user = os.getenv('VMWARE_ALARM_EVENT_USERNAME', 'debug_VMWARE_ALARM_EVENT_USERNAME') if alarm_vm != 'debug_VMWARE_ALARM_EVENT_VM': s = ssl.SSLContext(ssl.PROTOCOL_SSLv23 ) # For VC 6.5/6.0 s=ssl.SSLContext(ssl.PROTOCOL_TLSv1) s.verify_mode = ssl.CERT_NONE # The pwd variable will need to be to a real password. # Perhaps using a lookup from a vault. # This is not built into this script # Of course "vcenter" and "user" will need to be updated as well si = SmartConnect(host="vcenter", user="******", pwd="password", sslContext=s) content = si.content def find_vm_obj(content, vimtype, name): obj = {}