开发者

File object in memory using Python

I'm not sure how to word this exactly but I have a script that downloads an SSL certificate from a web server to check it's expiration date.

To do this, I need to download the CA certificates. Currently I write them to a temporary file in the /tmp directory and read it back later but I am sure there must be a way to do this without writing to disk.

Here's the portion that's downloading the certificates

CA_FILE = '/tmp/ca_certs.txt'

root_cert = urllib.urlopen('https://www.cacert.org/certs/root.txt')
class3_cert = urllib.urlopen('https://www.cacert.org/certs/class3.txt')

temp_file = open(CA_FILE, 'w')    
temp_file.write(root_cert.read())
temp_file.write(class3_cert.read())
temp_file.close()

EDIT

Here's the portion that uses the file to get the certificate

 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
开发者_运维问答 ssl_sock = ssl.wrap_socket(s, ca_certs=CA_FILE, cert_reqs=ssl.CERT_REQUIRED)
 ssl_sock.connect(('mail.google.com', 443))

 date = ssl_sock.getpeercert()['notAfter']


the response from urllib is a file object. just use those wherever you are using the actual files instead. This is assuming that the code that consumes the file objects doesn't need to write to them of course.


Wow, don't do this. You're hitting cacert's site every time? That's INCREDIBLY rude and needlessly eats their resources. It's also ridiculously bad security practice. You're supposed to get the root certificate once and validate that it's the correct root cert and not some forgery, otherwise you can't rely on the validity of certificates signed by it.

Cache their root cert, or better yet, install it with the rest of the root certificates on your system like you're supposed to.


In the following line:

temp_file.write(root_cert.read())

you are actually reading the certificate into memory, and writing it out again. That line is equivalent to:

filedata = root_cert.read()
temp_file.write(filedata)

Now filedata is a variable containing the bytes of the root certificate, that you can use in any way you like (including not writing it to temp_file and doing something else with it instead).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜