简体   繁体   English

将PEM文件解析为对象

[英]Parsing PEM file into Object

I have a PEM file which contains some certificates. 我有一个包含一些证书的PEM文件。 I want to parse them into an object which has a sha_hash, pem and expiration variables. 我想将它们解析为具有sha_hash,pem和expiration变量的对象。

I have created the object and it works. 我已经创建了对象,并且可以正常工作。 I created a list of objects. 我创建了一个对象列表。 The issue I am having is with Parsing. 我遇到的问题是解析。 Please see the full code below. 请查看下面的完整代码。 The issue is lets say I hit the SHA or BEGIN or END case.. it adds the line to the object.. but then it hits the else case.. and adds it a second time. 问题是说我碰到SHA或BEGIN或END情况..它将行添加到对象..但是随后碰到了else情况..并第二次添加了它。

What I want to to do once it finishes one of the if statements is to go to the next line! 一旦它完成了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()

It's happens because you have multiple if s and a if/else at the end. 发生这种情况是因为您在末尾有多个if s和if/else If you want to always match exactly one of these conditionals you could instead do 如果您希望始终完全匹配这些条件之一,则可以改成

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM