本文整理汇总了Python中OpenSSL.SSL.Connection.shutdown方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.shutdown方法的具体用法?Python Connection.shutdown怎么用?Python Connection.shutdown使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OpenSSL.SSL.Connection
的用法示例。
在下文中一共展示了Connection.shutdown方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: server_ok
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import shutdown [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
示例2: verify_cert
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import shutdown [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
示例3: verify_servercert
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import shutdown [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
示例4: TLSMemoryBIOProtocol
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import shutdown [as 别名]
#.........这里部分代码省略.........
transport.
"""
try:
bytes = self._tlsConnection.bio_read(2 ** 15)
except WantReadError:
# There may be nothing in the send BIO right now.
pass
else:
self.transport.write(bytes)
def _flushReceiveBIO(self):
"""
Try to receive any application-level bytes which are now available
because of a previous write into the receive BIO. This will take
care of delivering any application-level bytes which are received to
the protocol, as well as handling of the various exceptions which
can come from trying to get such bytes.
"""
# Keep trying this until an error indicates we should stop or we
# close the connection. Looping is necessary to make sure we
# process all of the data which was put into the receive BIO, as
# there is no guarantee that a single recv call will do it all.
while not self._lostTLSConnection:
try:
bytes = self._tlsConnection.recv(2 ** 15)
except WantReadError:
# The newly received bytes might not have been enough to produce
# any application data.
break
except ZeroReturnError:
# TLS has shut down and no more TLS data will be received over
# this connection.
self._shutdownTLS()
# Passing in None means the user protocol's connnectionLost
# will get called with reason from underlying transport:
self._tlsShutdownFinished(None)
except Error as e:
# Something went pretty wrong. For example, this might be a
# handshake failure (because there were no shared ciphers, because
# a certificate failed to verify, etc). TLS can no longer proceed.
# Squash EOF in violation of protocol into ConnectionLost; we
# create Failure before calling _flushSendBio so that no new
# exception will get thrown in the interim.
if e.args[0] == -1 and e.args[1] == 'Unexpected EOF':
failure = Failure(CONNECTION_LOST)
else:
failure = Failure()
self._flushSendBIO()
self._tlsShutdownFinished(failure)
else:
# If we got application bytes, the handshake must be done by
# now. Keep track of this to control error reporting later.
self._handshakeDone = True
ProtocolWrapper.dataReceived(self, bytes)
# The received bytes might have generated a response which needs to be
# sent now. For example, the handshake involves several round-trip
# exchanges without ever producing application-bytes.
self._flushSendBIO()
def dataReceived(self, bytes):
"""
示例5: Context
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import shutdown [as 别名]
from OpenSSL.SSL import Connection, Context, SSLv3_METHOD, TLSv1_2_METHOD
host = 'www.baidu.com'
try:
ssl_connection_setting = Context(SSLv3_METHOD)
except ValueError:
ssl_connection_setting = Context(TLSv1_2_METHOD)
ssl_connection_setting.set_timeout(30)
s = socket()
s.connect((host, 443))
c = Connection(ssl_connection_setting, s)
c.set_connect_state()
c.do_handshake()
cert = c.get_peer_certificate()
print "Issuer: ", cert.get_issuer()
print "Subject: ", cert.get_subject().get_components()
subject_list = cert.get_subject().get_components()
print "Common Name:", dict(subject_list).get("CN")
print "notAfter(UTC time): ", cert.get_notAfter()
UTC_FORMAT = "%Y%m%d%H%M%SZ"
utc_to_local_offset = datetime.datetime.fromtimestamp(time.time()) - datetime.datetime.utcfromtimestamp(time.time())
utc_time = time.mktime(time.strptime(cert.get_notAfter(), UTC_FORMAT))
local_time = utc_time + utc_to_local_offset.seconds
print "notAfter(Local Time): ", datetime.datetime.fromtimestamp(local_time)
print "is_expired:", cert.has_expired()
c.shutdown()
s.close()
示例6: SocketClient
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import shutdown [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
#.........这里部分代码省略.........
示例7: verify_cert
# 需要导入模块: from OpenSSL.SSL import Connection [as 别名]
# 或者: from OpenSSL.SSL.Connection import shutdown [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