当前位置: 首页>>代码示例>>Python>>正文


Python Connection.close方法代码示例

本文整理汇总了Python中OpenSSL.SSL.Connection.close方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.close方法的具体用法?Python Connection.close怎么用?Python Connection.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在OpenSSL.SSL.Connection的用法示例。


在下文中一共展示了Connection.close方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: server_ok

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import close [as 别名]
def server_ok(serverarg, capath, timeout):
        "Check if the server is active and responsive"

        server_ctx = Context(TLSv1_METHOD)
        server_ctx.load_verify_locations(None, capath)

        def verify_cb(conn, cert, errnum, depth, ok):
                return ok

        server_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)

        serverarg = re.split("/*", serverarg)[1]
        if ':' in serverarg:
                serverarg = serverarg.split(':')
                server = serverarg[0]
                port = int(serverarg[1] if not '?' in serverarg[1] else serverarg[1].split('?')[0])
        else:
                server = serverarg
                port = DEFAULT_PORT

        try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.connect((server, port))

                server_conn = Connection(server_ctx, sock)
                server_conn.set_connect_state()

                try:
                        def handler(signum, frame):
                                raise socket.error([('Timeout', 'after', str(timeout) + 's')])

                        signal.signal(signal.SIGALRM, handler)
                        signal.alarm(timeout)
                        server_conn.do_handshake()
                        signal.alarm(0)

                except socket.timeout as e:
                        nagios_out('Critical', 
			'Connection error %s - %s' % (server + ':' + str(port), errmsg_from_excp(e)),2)
                server_conn.shutdown()
                server_conn.close()

        except (SSLError, socket.error) as e:
                if 'sslv3 alert handshake failure' in errmsg_from_excp(e):
                        pass
                else:
                        nagios_out('Critical', 
			'Connection error %s - %s' % (server + ':' + str(port), errmsg_from_excp(e)), 2)

        return True
开发者ID:osct,项目名称:swift-nagios-probe,代码行数:52,代码来源:nagios-plugins-openstack-swift_v2.py

示例2: verify_cert

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import close [as 别名]
    def verify_cert(host, ca, timeout):
        server_ctx = Context(TLSv1_METHOD)
        server_cert_chain = []

        if os.path.isdir(ca):
            server_ctx.load_verify_locations(None, ca)
        else:
            server_ctx.load_verify_locations(ca, None)

        def verify_cb(conn, cert, errnum, depth, ok):
            server_cert_chain.append(cert)
            return ok
        server_ctx.set_verify(VERIFY_PEER, verify_cb)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setblocking(1)
        sock.settimeout(timeout)
        sock.connect((host, 443))

        server_conn = Connection(server_ctx, sock)
        server_conn.set_connect_state()

        def iosock_try():
            ok = True
            try:
                server_conn.do_handshake()
                sleep(0.5)
            except SSLWantReadError as e:
                ok = False
                pass
            except Exception as e:
                raise e
            return ok

        try:
            while True:
                if iosock_try():
                    break

            server_subject = server_cert_chain[-1].get_subject()
            if host != server_subject.CN:
                raise SSLError('Server certificate CN does not match %s' % host)

        except SSLError as e:
            raise e
        finally:
            server_conn.shutdown()
            server_conn.close()

        return True
开发者ID:vrdel,项目名称:argo-egi-connectors,代码行数:52,代码来源:tools.py

示例3: verify_servercert

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import close [as 别名]
def verify_servercert(host, timeout, capath):
    server_ctx = Context(TLSv1_METHOD)
    server_ctx.load_verify_locations(None, capath)
    server_cert_chain = []

    def verify_cb(conn, cert, errnum, depth, ok):
        server_cert_chain.append(cert)
        return ok
    server_ctx.set_verify(VERIFY_PEER, verify_cb)

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setblocking(1)
    sock.settimeout(timeout)
    sock.connect((host, 443))

    server_conn = Connection(server_ctx, sock)
    server_conn.set_connect_state()

    def iosock_try():
        ok = True
        try:
            server_conn.do_handshake()
            sleep(0.5)
        except SSLWantReadError as e:
            ok = False
            pass
        except Exception as e:
            raise e
        return ok

    try:
        while True:
            if iosock_try():
                break

        global server_expire
        server_expire = server_cert_chain[-1].get_notAfter()

    except PyOpenSSLError as e:
        raise e
    finally:
        server_conn.shutdown()
        server_conn.close()

    return True
开发者ID:ARGOeu,项目名称:argo-probes,代码行数:47,代码来源:poem.py

示例4: OpenSSLSNI

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import close [as 别名]
class OpenSSLSNI(object):
    """This class implements the functionality of obtaining certificates secure connection using
        apache TLS Extension Server Name Indication (SNI)
    """
    def connection(func):
        def wrapped(self):
            self._connect()
            try:
                return func(self)
            finally:
                self._close()
        return wrapped

    def __init__(self, host, port):
        #Set host name
        self._host = str(host).split('//')[-1].split(':')[0]
        #Set port
        self._port = int(port) if str(port).isdigit() else 443

    def _connect(self):
        """This method implements the functionality of establishing a secure connection using TLS Extension"""
        self._socket_client = socket()
        self._socket_client.connect((self._host, self._port))
        self._ssl_client = Connection(Context(TLSv1_METHOD), self._socket_client)
        self._ssl_client.set_connect_state()
        self._ssl_client.set_tlsext_host_name(self._host)
        self._ssl_client.do_handshake()

    def _close(self):
        """This method implements the functional termination created connection"""
        self._ssl_client.close()
        del self._socket_client

    @property
    @connection
    def serial_number(self):
        """Returns  certificates serial number"""
        return self._ssl_client.get_peer_certificate().get_serial_number()

    @property
    @connection
    def certificate(self):
        """Returns  certificate"""
        return OpenSSL.crypto.dump_certificate(FILETYPE_PEM, self._ssl_client.get_peer_certificate())
开发者ID:pombredanne,项目名称:revizor-tests,代码行数:46,代码来源:web_common.py

示例5: netflix_openssl_test_retry

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import close [as 别名]
 def netflix_openssl_test_retry(ip):
     client = socket()
     
     print 'Connecting...',
     stdout.flush()
     client.connect((ip, port))
     print 'connected', client.getpeername()
     
     client_ssl = Connection(Context(TLSv1_METHOD), client)
     client_ssl.set_connect_state()
     client_ssl.set_tlsext_host_name(hostname)
     client_ssl.do_handshake()
     cert = client_ssl.get_peer_certificate().get_subject()
     cn = [comp for comp in cert.get_components() if comp[0] in ['CN']]
     client_ssl.close()
     print cn
     if hostname in cn[0][1]:
         return True
     else:
         return False
开发者ID:cjrowson,项目名称:netflix-proxy,代码行数:22,代码来源:__testbuild.py

示例6: _validate_certificate_hostname_pyopenssl

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import close [as 别名]
    def _validate_certificate_hostname_pyopenssl(self):
      """ Use pyOpenSSL check if the host's certifcate matches the hostname.

      Python < 2.7.9 is not able to provide a server hostname for SNI, so this
      is a fallback that opens an additional connection if the initial
      validation failed.

      Returns:
        bool: Whether or not the hostname is valid on the certificate.
      """
      client = socket.socket()
      client.connect((self.host, self.port))
      client_ssl = Connection(Context(TLSv1_METHOD), client)
      client_ssl.set_connect_state()
      client_ssl.set_tlsext_host_name(self.host)
      client_ssl.do_handshake()
      cert = client_ssl.get_peer_certificate()
      client_ssl.close()

      common_name = cert.get_subject().commonName
      return self._cert_host_matches_hostname(common_name, self.host)
开发者ID:AppScale,项目名称:appscale,代码行数:23,代码来源:__init__.py

示例7: main

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import close [as 别名]
def main():
    """
    Connect to an SNI-enabled server and request a specific hostname, specified
    by argv[1], of it.
    """
    if len(argv) < 2:
        print 'Usage: %s <hostname>' % (argv[0],)
        return 1

    client = socket()

    print 'Connecting...',
    stdout.flush()
    client.connect(('127.0.0.1', 8443))
    print 'connected', client.getpeername()

    client_ssl = Connection(Context(TLSv1_METHOD), client)
    client_ssl.set_connect_state()
    client_ssl.set_tlsext_host_name(argv[1])
    client_ssl.do_handshake()
    print 'Server subject is', client_ssl.get_peer_certificate().get_subject()
    client_ssl.close()
开发者ID:15580056814,项目名称:hue,代码行数:24,代码来源:client.py

示例8: SocketClient

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import close [as 别名]
class SocketClient(object):
    """This class sends all info to the server
    """

    cacertpath = "ca/cacert.pem"
    BUFF = 8192

    def __init__(self,HOST='130.236.219.232', PORT = 443):
        self.mutex = threading.Semaphore(1)
        self.connected = False
        self.connect()
        self.host_addr = HOST
        self.host_port = PORT

    def connect(self):
        print "You are trying to connect..."
        for x in range(7):
            if not self.connected:
                try:
                    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    context = Context(TLSv1_METHOD)
                    context.use_certificate_file(self.cacertpath)
                    context.set_timeout(2)
                    self.sslsocket = Connection(context,s)
                    self.sslsocket.connect((self.host_addr,self.host_port))
                    #starting a thread that listen to what server sends which the clients need to be able to send and recive data at the same time
                    t = threading.Thread(target=self.receive)
                    t.daemon = True
                    t.start()
                    if self.sslsocket:
                        self.connected = True
                    print "connection established"
                    #self.authentication("Kalle", "te")
                    t = threading.Thread(target=self.sendinput)
                    t.start()
                except socket.error:
                    print "You failed to connect, retrying......."
                    time.sleep(5)

    def authentication(self, username, password):
        self.sslsocket.send(username)
        self.sslsocket.send(password)

    #sending string to server
    def send(self,str):
        try:
            self.sslsocket.write("start")
            totalsent =  0
            while totalsent < str.__len__():
                sent = self.sslsocket.write(str[totalsent:])
                if sent == 0:
                    raise RuntimeError, "socket connection broken"
                totalsent = totalsent + sent
            self.sslsocket.write("end")
        except SSL.SysCallError:
            print "your server is dead, you have to resend data"
            self.connected = False
            self.sslsocket.shutdown()
            self.sslsocket.close()
            self.mutex.acquire()
            print "Du är inne i connect via send SysCallError"
            self.connect()
            self.mutex.release()
        except SSL.Error:
            self.connected = False
            self.mutex.acquire()
            print "Du är inne i connect via send ssl error"
            self.connect()
            self.mutex.release()

    #Sending input to server
    def sendinput(self):
        try:
            while True:
                input = raw_input()
                self.send(input)
        except KeyboardInterrupt:
            print "du är inne i sendinput"
            self.sslsocket.shutdown()
            self.sslsocket.close()
            exit(0)

    #getting data from server
    def receive(self):
        output = ""
        try:
            while True:
                data = self.sslsocket.recv(self.BUFF)
                if data == "start":
                    while True: 
                        data = self.sslsocket.recv(self.BUFF)
                        if data == "end":
                            print output
                            output = ""
                            break
                        output = output + data
        except SSL.SysCallError:
            print "OMG Server is down"
            self.connected = False
            print self.connected
#.........这里部分代码省略.........
开发者ID:dreamwave,项目名称:rad,代码行数:103,代码来源:socketclient.py

示例9: verify_cert

# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import close [as 别名]
def verify_cert(host, capath, timeout, cncheck=True):
    server_ctx = Context(TLSv1_METHOD)
    server_cert_chain = []
    server_ctx.load_verify_locations(None, capath)

    host = re.split("/*", host)[1]
    if ':' in host:
        host = host.split(':')
        server = host[0]
        port = int(host[1] if not '?' in host[1] else host[1].split('?')[0])
    else:
        server = host
        port = 443

    def verify_cb(conn, cert, errnum, depth, ok):
        server_cert_chain.append(cert)
        return ok
    server_ctx.set_verify(VERIFY_PEER, verify_cb)

    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setblocking(1)
        sock.settimeout(timeout)
        sock.connect((server, port))
    except (socket.error, socket.timeout) as e:
        nagios_out('Critical', 'Connection error %s - %s' % (server + ':' + str(port),
                                                            errmsg_from_excp(e)),
                                                            2)

    server_conn = Connection(server_ctx, sock)
    server_conn.set_connect_state()

    def iosock_try():
        ok = True
        try:
            server_conn.do_handshake()
            sleep(0.5)
        except SSLWantReadError as e:
            ok = False
            pass
        except Exception as e:
            raise e
        return ok

    try:
        while True:
            if iosock_try():
                break

        if cncheck:
            server_subject = server_cert_chain[-1].get_subject()
            if server != server_subject.CN:
                nagios_out('Critical', 'Server certificate CN %s does not match %s' % (server_subject.CN, server), 2)

    except SSLError as e:
        if 'sslv3 alert handshake failure' in errmsg_from_excp(e):
            pass
        else:
            nagios_out('Critical', 'Connection error %s - %s' % (server + ':' + str(port),
                                                                errmsg_from_excp(e, level=1)),
                                                                2)
    finally:
        server_conn.shutdown()
        server_conn.close()

    return True
开发者ID:enolfc,项目名称:nagios-plugins-fedcloud,代码行数:68,代码来源:helpers.py


注:本文中的OpenSSL.SSL.Connection.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。