本文整理汇总了Python中socket.ssl函数的典型用法代码示例。如果您正苦于以下问题:Python ssl函数的具体用法?Python ssl怎么用?Python ssl使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ssl函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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
示例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
示例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')
示例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
示例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()
示例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)
示例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
示例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
示例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
示例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()
示例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
示例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
示例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()