将PEM文件解析为Object

时间:2018-05-01 19:19:06

标签: python parsing pem

我有一个包含一些证书的PEM文件。我想将它们解析为一个具有sha_hash,pem和expiration变量的对象。

我已经创建了对象并且它有效。我创建了一个对象列表。我遇到的问题是解析。请参阅下面的完整代码。问题是让我说我​​点击SHA或BEGIN或END的情况..它将线添加到对象..但然后它击中了其他情况..并再次添加它。

完成其中一个if语句后,我想要做的就是转到下一行!

class Certificate(object):
    """A class for parsing and storing information about
    certificates:"""

    def __init__(self, sha_hash="", pem="", expiration=""):
        super(Certificate, self).__init__()
        self.sha_hash = sha_hash
        self.pem = pem
        self.expiration = expiration


def main():
    cert_file = '/Users/ludeth/Desktop/testCerts.pem'
    myList = []
    cert = Certificate()

    with open(cert_file, 'r') as myFile:
        cert = Certificate()
        for line in myFile:
            if "SHA" in line:
                cert.sha_hash = line
            if "BEGIN" in line:
                cert.pem = cert.pem + line
            if "END" in line:
                cert.pem = cert.pem + line
                myList.append(cert)
                break
            else:
                cert.pem = cert.pem + line

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

之所以发生这种情况,是因为您最后有多个if和一个if/else。如果你想要总是匹配其中一个条件,你可以改为

if "SHA" in line:
    cert.sha_hash = line
elif "BEGIN" in line:
    cert.pem = cert.pem + line
elif "END" in line:
    cert.pem = cert.pem + line
    myList.append(cert)
    break
else:
    cert.pem = cert.pem + line