• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socket.ssl函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中socket.ssl函数的典型用法代码示例。如果您正苦于以下问题:Python ssl函数的具体用法?Python ssl怎么用?Python ssl使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: new_open_ssl

def new_open_ssl(self, host = '', port = IMAP4_SSL_PORT):
        """Setup connection to remote server on "host:port".
            (default: localhost:standard IMAP4 SSL port).
        This connection will be used by the routines:
            read, readline, send, shutdown.
        """
        self.host = host
        self.port = port
        #This connects to the first ip found ipv4/ipv6
        #Added by Adriaan Peeters <[email protected]> based on a socket
        #example from the python documentation:
        #http://www.python.org/doc/lib/socket-example.html
        res = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM)
        # Try all the addresses in turn until we connect()
        last_error = 0
        for remote in res:
            af, socktype, proto, canonname, sa = remote
            self.sock = socket.socket(af, socktype, proto)
            last_error = self.sock.connect_ex(sa)
            if last_error == 0:
                break
            else:
                self.sock.close()
        if last_error != 0:
            # FIXME
            raise socket.error(last_error)
        if sys.version_info[0] <= 2 and sys.version_info[1] <= 2:
            self.sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
        else:
            self.sslobj = socket.ssl(self.sock._sock, self.keyfile, self.certfile)
        self.sslobj = sslwrapper(self.sslobj)
开发者ID:avsm,项目名称:lifedb-plugins,代码行数:32,代码来源:imaplibutil.py


示例2: handle_accept

 def handle_accept( self ):
     socket,address = self.accept()
     if self.sslKeyFile:
         socket.ssl(socket,self.sslKeyFile,self.sslCertFile)
     conn = Connection(address, sock=socket, listener=self)
     conn.onRequest = self.onRequest
     if self.onConnected:
         self.onConnected(conn)
开发者ID:alexsystemf,项目名称:deathtroid,代码行数:8,代码来源:BLIP.py


示例3: __init__

 def __init__(self, sock, keyfile=None, certfile=None):
     log.trace()
     self.sock = sock
     self.sock.setblocking(1)
     if keyfile and certfile:
         self.ssl = socket.ssl(self.sock, keyfile, certfile)
     else:
         self.ssl = socket.ssl(self.sock)
     self.buf = ''
     self.bufsize = 128
开发者ID:GymWenFLL,项目名称:tpp_libs,代码行数:10,代码来源:_pop3ssl.py


示例4: is_ssl

def is_ssl(hostname, port=443):
    """<comment-ja>
    指定したホスト:ポートがSSLに対応しているか調べる。

    @param hostname: ホスト名
    @type hostname: str
    @param port: ポート番号
    @type port: int
    @return: SSL対応=True | SSL非対応=False
    @rtype: bool
    </comment-ja>
    <comment-en>
    English Comment
    </comment-en>
    """
    try:
        _s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        _s.settimeout(5.0)
        _s.connect((hostname, port))
        if socket.ssl(_s):
            return True
        else:
            return False
    except:
        return False
开发者ID:goura,项目名称:karesansui,代码行数:25,代码来源:http.py


示例5: open

 def open(self, host, port):
         """Setup 'self.sock' and 'self.file'."""
         self.port = IMAP4_PORT
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.sock.connect((self.host, self.port))
         self.ssl = socket.ssl(self.sock._sock,None,None)
         self.file = self.makefile('r')
开发者ID:juanjux,项目名称:animail,代码行数:7,代码来源:imapslib.py


示例6: dossl

 def dossl(self):
     """ enable ssl on the socket. """
     if self.stopped: return
     try: import ssl ; self.connection = ssl.wrap_socket(self.sock)
     except ImportError: self.connection = socket.ssl(self.sock)
     if self.connection: return True
     else: return False
开发者ID:code2u,项目名称:jsb,代码行数:7,代码来源:core.py


示例7: connect

	def connect(self, server, port):
		socket.setdefaulttimeout(300)
		self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.socket.connect((server, port))
		self.sock = socket.ssl(self.socket)
		
		self._loop()
开发者ID:ejrh,项目名称:xbot,代码行数:7,代码来源:irc.py


示例8: __negotiatehttps

 def __negotiatehttps(self, destaddr, destport):
     # now connect, very simple recv and error checking
     try:
         self._sock = _socket.ssl(self._sock)
         self.__negotiatehttp(destaddr, destport)
     except Exception, e:
         raise _socket.error(e)
开发者ID:mikedougherty,项目名称:SocksiPy,代码行数:7,代码来源:socks.py


示例9: _connect

  def _connect(self,host,port,login,password,delay):
    self.host=host
    self.port=port
    self.login=login
    self.password=password
    self.line_delay=delay

    log_info('Connecting to IRC at %s:%u' % (host, port))
    self.last_send_time=0
    self.last_ping_time = time.time()
    self.quitting = False
    self.buffered_data = ""
    self.userstable=dict()
    self.registered_users=set()
    try:
      self.irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
      if self.use_ssl:
        try:
          raise RuntimeError('')
          self.irc_ssl_context = ssl.create_default_context()
          self.sslirc = self.irc_ssl_context.wrap_socket(self.irc, host)
          self.sslirc.connect ( ( host, port ) )
        except Exception,e:
          log_warn('Failed to create SSL context, using fallback code: %s' % str(e))
          self.irc.connect ( ( host, port ) )
          self.sslirc = socket.ssl(self.irc)
    except Exception, e:
      log_error( 'Error initializing IRC: %s' % str(e))
      return False
开发者ID:clintar,项目名称:tippero,代码行数:29,代码来源:irc.py


示例10: connect

    def connect(self, server, port, nickname, password=None, username=None,
                ircname=None, localaddress="", localport=0, ssl=False, ipv6=False):
        """Connect/reconnect to a server.

        Arguments:

            server -- Server name.

            port -- Port number.

            nickname -- The nickname.

            password -- Password (if any).

            username -- The username.

            ircname -- The IRC name ("realname").

            localaddress -- Bind the connection to a specific local IP address.

            localport -- Bind the connection to a specific local port.

            ssl -- Enable support for ssl.

            ipv6 -- Enable support for ipv6.

        This function can be called to reconnect a closed connection.

        Returns the ServerConnection object.
        """

        if self.connected:
            self.disconnect("Changing servers")

        self.previous_buffer = ""
        self.handlers = {}
        self.real_server_name = ""
        self.real_nickname = nickname
        self.server = server
        self.port = port
        self.nickname = nickname
        self.username = username or nickname
        self.ircname = ircname or nickname
        self.password = password
        self.localaddress = localaddress
        self.localport = localport
        self.localhost = socket.gethostname()
        if ipv6:
            self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.socket.bind((self.localaddress, self.localport))
            self.socket.connect((self.server, self.port))
            if ssl:
                self.ssl = socket.ssl(self.socket)
        except socket.error, x:
            self.socket.close()
            self.socket = None
            raise ServerConnectionError, "Couldn't connect to socket: %s" % x
开发者ID:willmoffat,项目名称:Acrebot,代码行数:60,代码来源:irclib.py


示例11: tryHttpsServer

    def tryHttpsServer(self, port):
        try:
            socket.setdefaulttimeout(self.timeout)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((self.target, int(port)))
            
            ssl_sock = socket.ssl(s)
            #print "Server:", ssl_sock.server()
            #print "Issuer:", ssl_sock.issuer()

            ssl_sock.write("GET / HTTP/1.0\n\n\n")
            data = ssl_sock.read(1024)
            del ssl_sock
            s.close()

            if data.lower().find("http/") == 0:
                self.addToDict(self.target + "_services", str(port) + "/https")
                pos = data.lower().find("server:")

                if self.verbose:
                    self.gom.echo( "Response: %s" % repr(data) )

                if pos > -1:
                    data = data[pos+len("server:"):]
                    data = data[:data.find("\n")]
                    return data
                else:
                    return "HTTP-SSL Server"
            else:
                return False
        except:
            return False
开发者ID:caoimhinp,项目名称:inguma,代码行数:32,代码来源:CServiceIdentify.py


示例12: test_timeout

def test_timeout():
    test_support.requires('network')

    if test_support.verbose:
        print "test_timeout ..."

    # A service which issues a welcome banner (without need to write
    # anything).
    # XXX ("gmail.org", 995) has been unreliable so far, from time to time
    # XXX non-responsive for hours on end (& across all buildbot slaves,
    # XXX so that's not just a local thing).
    ADDR = "gmail.org", 995

    s = socket.socket()
    s.settimeout(30.0)
    try:
        s.connect(ADDR)
    except socket.timeout:
        print >> sys.stderr, """\
    WARNING:  an attempt to connect to %r timed out, in
    test_timeout.  That may be legitimate, but is not the outcome we hoped
    for.  If this message is seen often, test_timeout should be changed to
    use a more reliable address.""" % (ADDR,)
        return

    ss = socket.ssl(s)
    # Read part of return welcome banner twice.
    ss.read(1)
    ss.read(1)
    s.close()
开发者ID:facchinm,项目名称:SiRFLive,代码行数:30,代码来源:test_socket_ssl.py


示例13: authenticate

    def authenticate(self, username=None, password=None):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(('www.princeton.edu', 443))

        ssl_sock = socket.ssl(s)

        # Set a simple HTTP request -- use httplib in actual code.
        ssl_sock.write("GET /~point/validate/validate.html HTTP/1.0\r\nAuthorization: Basic " + base64.b64encode(username+":"+password) + "\r\nHost: www.princeton.edu\r\nConnection: close\r\n\r\n")

        # Read a chunk of data.  Will not necessarily
        # read all the data returned by the server.
        data = ssl_sock.read()

        # Note that you need to close the underlying socket, not the SSL object.
        del ssl_sock
        s.close()

        if data.startswith('HTTP/1.1 200 OK'):
            u = User.objects.get_or_create(username=username, defaults={'is_staff':False,'is_active':True,'is_superuser':False,'email':username+'@princeton.edu'})
            u = u[0]
            u.set_password(password)
            u.save()
            return u
        else:
            return None
开发者ID:PrincetonUSG,项目名称:USG-srv-dev,代码行数:25,代码来源:ldapBackend.py


示例14: Request

  def Request(self, request):
    """Connects and sends a single HTTP request."""
    self.log.Log(2, '=== sending to %s:%d ===\n%s\n=== end of request ===\n' %
                 (self.host, self.port, request))
    
    # Get a file object for an appropriate socket (with or without SSL).
    sock = socket.socket()
    sock.connect((self.host, self.port))
    if self.scheme == 'https':
      sockfile = socket.ssl(sock)
    else:
      sockfile = sock.makefile()

    # Send the HTTP request.
    sockfile.write(request)
    if hasattr(sockfile, 'flush'):
      sockfile.flush()

    # Read back the entire reply.
    reply = []
    try:
      while reply[-1:] != ['']:
        reply.append(sockfile.read())
    except socket.error, e:
      # Usually SSL_ERROR_EOF just means we reached end-of-file.
      if e.args[0] != socket.SSL_ERROR_EOF:
        raise
开发者ID:johnblackmore,项目名称:cc128-php-extractor,代码行数:27,代码来源:google_meter.py


示例15: test_https_socket

def test_https_socket():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('www.verisign.com', 443))
    ssl_sock = socket.ssl(s)
    ssl_sock.server()
    ssl_sock.issuer()
    s.close()    
开发者ID:CalSimCalLite,项目名称:CalLiteGUI,代码行数:7,代码来源:test_socket_ssl.py


示例16: connect

	def connect(self, host='localhost', port=0):
		if not port and (host.find(':') == host.rfind(':')):
			i = host.rfind(':')
			if i >= 0:
				host, port = host[:i], host[i+1:]
				try: port = int(port)
				except ValueError:
					raise socket.error, "nonnumeric port"
		if not port: port = self.SSMTP_PORT
		if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
		msg = "getaddrinfo returns an empty list"
		self.sock = None
		for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
			af, socktype, proto, canonname, sa = res
			try:
				self.sock = socket.socket(af, socktype, proto)
				if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
				self.sock.connect(sa)
				# MB: Make the SSL connection.
				sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
			except socket.error, msg:
				if self.debuglevel > 0: 
					print>>stderr, 'connect fail:', (host, port)
				if self.sock:
					self.sock.close()
				self.sock = None
				continue
			break
开发者ID:smarkm,项目名称:ovm,代码行数:28,代码来源:ssmtplib.py


示例17: proxy_ssl

    def proxy_ssl(self):
        host = '%s:%d' % (self.host, self.port)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.connect((self.proxy, int(self.proxy_port)))
        except:
            raise
        boto.log.debug("Proxy connection: CONNECT %s HTTP/1.0\r\n", host)
        sock.sendall("CONNECT %s HTTP/1.0\r\n" % host)
        sock.sendall("User-Agent: %s\r\n" % UserAgent)
        if self.proxy_user and self.proxy_pass:
            for k, v in self.get_proxy_auth_header().items():
                sock.sendall("%s: %s\r\n" % (k, v))
            # See discussion about this config option at
            # https://groups.google.com/forum/?fromgroups#!topic/boto-dev/teenFvOq2Cc
            if config.getbool('Boto', 'send_crlf_after_proxy_auth_headers', False):
                sock.sendall("\r\n")
        else:
            sock.sendall("\r\n")
        resp = httplib.HTTPResponse(sock, strict=True, debuglevel=self.debug)
        resp.begin()

        if resp.status != 200:
            # Fake a socket error, use a code that make it obvious it hasn't
            # been generated by the socket library
            raise socket.error(-71,
                               "Error talking to HTTP proxy %s:%s: %s (%s)" %
                               (self.proxy, self.proxy_port, resp.status, resp.reason))

        # We can safely close the response, it duped the original socket
        resp.close()

        h = httplib.HTTPConnection(host)

        if self.https_validate_certificates and HAVE_HTTPS_CONNECTION:
            boto.log.debug("wrapping ssl socket for proxied connection; "
                           "CA certificate file=%s",
                           self.ca_certificates_file)
            key_file = self.http_connection_kwargs.get('key_file', None)
            cert_file = self.http_connection_kwargs.get('cert_file', None)
            sslSock = ssl.wrap_socket(sock, keyfile=key_file,
                                      certfile=cert_file,
                                      cert_reqs=ssl.CERT_REQUIRED,
                                      ca_certs=self.ca_certificates_file)
            cert = sslSock.getpeercert()
            hostname = self.host.split(':', 0)[0]
            if not https_connection.ValidateCertificateHostname(cert, hostname):
                raise https_connection.InvalidCertificateException(
                        hostname, cert, 'hostname mismatch')
        else:
            # Fallback for old Python without ssl.wrap_socket
            if hasattr(httplib, 'ssl'):
                sslSock = httplib.ssl.SSLSocket(sock)
            else:
                sslSock = socket.ssl(sock, None, None)
                sslSock = httplib.FakeSocket(sock, sslSock)

        # This is a bit unclean
        h.sock = sslSock
        return h
开发者ID:raorn,项目名称:boto,代码行数:60,代码来源:connection.py


示例18: execPPPd

def execPPPd(params):
    tunnel_host = params["tunnel_host0"]
    tunnel_port = int(params["tunnel_port0"])

    serviceid = "f5vpn-%s" % tunnel_host

    request = """GET /myvpn?sess=%s HTTP/1.0\r
Cookie: MRHSession=%s\r
\r
""" % (
        params["Session_ID"],
        params["Session_ID"],
    )

    for i in range(5):
        try:
            ssl_socket = proxy_connect(tunnel_host, tunnel_port)
            ssl_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
            ssl = socket.ssl(ssl_socket)
            ssl.write(request)
            initial_data = ssl.read()
            break
        except socket.sslerror, e:
            # Sometimes the server seems to respond with "EOF occurred in violation of protocol"
            # instead of establishing the connection. Try to deal with this by retrying...
            if e.args[0] != 8:
                raise
            sys.stderr.write("VPN socket unexpectedly closed during connection setup, retrying (%d/5)...\n" % (i + 1))
开发者ID:pungoyal,项目名称:shadow-poll,代码行数:28,代码来源:f5vpn-login.py


示例19: connect

    def connect(self, options):
        """
        Connects to an IRC server and initializes the connection.
        
        Required options:
        'server' 'port' 'nickname' 'username' 'realname'
        Other options:
        'password'
        'channels' -- List. Channels to autojoin.
        'ssl' -- Boolean.
        """
        # Initialize the socket.
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((options['server'], options['port']))
        try:
            if options['ssl']: # SSL ftw!
                print 'Congratulations! You have a SSL-encrypted connection.'
                self.ssl = True
                self.ssl_socket = socket.ssl(self.socket)
                print 'Server SSL Certificate:', repr(self.ssl_socket.server())
                print 'Issuer SSL Certificate:', repr(self.ssl_socket.issuer())
                print 'IMPORTANT: If you do not trust the issuer, press \
control-C to disconnect now!'
        except KeyError:
            pass
开发者ID:brandenburgmk,项目名称:irc_lib,代码行数:25,代码来源:irc.py


示例20: connect

    def connect(self):
      # TODO(frew): When we drop support for <2.6 (in the far distant future),
      # change this to socket.create_connection.
      self.sock = _create_connection((self.host, self.port))

      if self._tunnel_host:
        self._tunnel()

      # ssl and FakeSocket got deprecated. Try for the new hotness of wrap_ssl,
      # with fallback. Note: Since can_validate_certs() just checks for the
      # ssl module, it's equivalent to attempting to import ssl from
      # the function, but doesn't require a dynamic import, which doesn't
      # play nicely with dev_appserver.
      if can_validate_certs():
        self.sock = ssl.wrap_socket(self.sock,
                                    keyfile=self.key_file,
                                    certfile=self.cert_file,
                                    ca_certs=self.ca_certs,
                                    cert_reqs=self.cert_reqs)

        if self.cert_reqs & ssl.CERT_REQUIRED:
          cert = self.sock.getpeercert()
          hostname = self.host.split(":", 0)[0]
          if not self._validate_certificate_hostname(cert, hostname):
            raise InvalidCertificateException(hostname, cert,
                                              "hostname mismatch")
      else:
        ssl_socket = socket.ssl(self.sock,
                                keyfile=self.key_file,
                                certfile=self.cert_file)
        self.sock = httplib.FakeSocket(self.sock, ssl_socket)
开发者ID:GavinHwa,项目名称:appscale,代码行数:31,代码来源:__init__.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socket.timeout函数代码示例发布时间:2022-05-27
下一篇:
Python socket.socketpair函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap