参考文档:https://blog.csdn.net/wuliganggang/article/details/78428866
实现:
1. 单向认证:client需要一个ca.crt,校验服务器的合法性。
def connectSSL(self, _tcp_ip, _tcp_port, _ca_certs='ca.crt'): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs=_ca_certs) try: sk.connect((_tcp_ip, _tcp_port)) except Exception, e: logging.error(str(e)) exit(1)
2. 双向认证:client对server进行校验,同时server也对client进行校验,client需要client.key 、client.crt 、ca.crt
def connectSSL(self, _tcp_ip='192.168.1.100', _tcp_port=10000, _keyfile='user.key', _certfile='user.pem', _ca_certs='ca.crt'): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk = ssl.wrap_socket(s, keyfile=_keyfile, certfile=_certfile, cert_reqs=ssl.CERT_REQUIRED, ca_certs=_ca_certs) try: sk.connect((_tcp_ip, _tcp_port)) print "cert type: " , sk.getpeercert() except Exception, e: logging.error(str(e)) exit(1)
注:python2.7.9版本后支持对证书加密