|
| 1 | +#!/usr/bin/python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +Created by PyCharm. |
| 5 | +File Name: LinuxBashShellScriptForOps:get-ssl-cert-info-from-pem-file.py |
| 6 | +Version: 0.0.1 |
| 7 | +Author: dgden |
| 8 | +Author Email: dgdenterprise@gmail.com |
| 9 | +URL: https://github.com/DingGuodong/LinuxBashShellScriptForOps |
| 10 | +Download URL: https://github.com/DingGuodong/LinuxBashShellScriptForOps/tarball/master |
| 11 | +Create Date: 2021/3/24 |
| 12 | +Create Time: 11:11 |
| 13 | +Description: get SSL certificate from PEM file |
| 14 | +Long Description: |
| 15 | +References: |
| 16 | +Prerequisites: [] |
| 17 | +Development Status: 3 - Alpha, 5 - Production/Stable |
| 18 | +Environment: Console |
| 19 | +Intended Audience: System Administrators, Developers, End Users/Desktop |
| 20 | +License: Freeware, Freely Distributable |
| 21 | +Natural Language: English, Chinese(Simplified) |
| 22 | +Operating System: POSIX :: Linux, Microsoft :: Windows |
| 23 | +Programming Language: Python :: 2.6 |
| 24 | +Programming Language: Python :: 2.7 |
| 25 | +Topic: Utilities |
| 26 | + """ |
| 27 | + |
| 28 | +# from ssl import DER_cert_to_PEM_cert |
| 29 | +import OpenSSL |
| 30 | +from OpenSSL.crypto import load_certificate |
| 31 | +from dateutil import parser |
| 32 | + |
| 33 | +with open("5366531_www.example.com.pem") as fp: |
| 34 | + content = fp.read() |
| 35 | + |
| 36 | +cert = load_certificate(OpenSSL.crypto.FILETYPE_PEM, content) |
| 37 | + |
| 38 | + |
| 39 | +def to_unicode_or_bust(obj, encoding='utf-8'): |
| 40 | + """ |
| 41 | + convert non-unicode object to unicode object |
| 42 | + :param obj: str object or unicode |
| 43 | + :param encoding: |
| 44 | + :return: |
| 45 | + """ |
| 46 | + if isinstance(obj, basestring): |
| 47 | + if not isinstance(obj, unicode): |
| 48 | + obj = unicode(obj, encoding) |
| 49 | + else: |
| 50 | + return str(obj) |
| 51 | + |
| 52 | + return obj |
| 53 | + |
| 54 | + |
| 55 | +def print_v2(*args): |
| 56 | + print("".join([to_unicode_or_bust(x) for x in args])) |
| 57 | + |
| 58 | + |
| 59 | +print_v2("颁发者: ", cert.get_issuer().commonName) |
| 60 | +print_v2("颁发给: ", dict(cert.get_subject().get_components()).get('CN')) |
| 61 | +print_v2("有效期从: ", parser.parse(cert.get_notBefore()).strftime('%Y-%m-%d %H:%M:%S')) |
| 62 | +print_v2("到: ", parser.parse(cert.get_notAfter()).strftime('%Y-%m-%d %H:%M:%S')) |
| 63 | +print_v2("证书是否已经过期: ", cert.has_expired()) |
| 64 | + |
| 65 | +cert_name_map = { |
| 66 | + "CN": "通用名称 ", |
| 67 | + "OU": "机构单元名称", |
| 68 | + "O": "机构名 ", |
| 69 | + "L": "地理位置", |
| 70 | + "S": "州/省名", |
| 71 | + "C": "国名" |
| 72 | +} |
| 73 | + |
| 74 | +for item in cert.get_issuer().get_components(): |
| 75 | + print_v2(cert_name_map.get(item[0]), ": ", item[1]) |
0 commit comments