2016-12-27 37 views
0

我想加载远程服务器证书并将其保存在本地磁盘中。这是我使用的python脚本:无法使用python将证书保存到本地磁盘

from M2Crypto.X509 import FORMAT_PEM 

import StringIO 
import traceback 
from M2Crypto.Err import SSLError 
import ssl 
import socket 
import pprint 
import M2Crypto 
from M2Crypto import X509, RSA 
from datetime import datetime 

context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) 
context.verify_mode = ssl.CERT_NONE 
context.check_hostname = False 
context.verify_mode = ssl.CERT_NONE 
port = 443 
host='216.58.212.67' #google 

#creating ssl socket 
ssock = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=host) 

#ssl connection 
try: 
    ssock.connect((host, port)) 
except socket.error: #if tls connection is not possible 
    print "Faile connection with: " + host 

#get the certificate 
cert = ssock.getpeercert(True) 
x509 = M2Crypto.X509.load_cert_der_string(cert) 
x509_file= M2Crypto.X509.load_cert('C:/Users/xxx/Documents/temp',format=FORMAT_PEM) 

当我运行它,我得到这个错误:

Traceback (most recent call last): 
    File "C:/Users/ealas/PycharmProjects/tlsScan/test.py", line 36, in <module> 
    x509_file= M2Crypto.X509.load_cert('C:/Users/xxx/Documents/temp',format=FORMAT_PEM) 
    File "C:\Python27\lib\site-packages\M2Crypto\X509.py", line 609, in load_cert 
    bio = BIO.openfile(file) 
    File "C:\Python27\lib\site-packages\M2Crypto\BIO.py", line 186, in openfile 
    return File(open(filename, mode)) 
IOError: [Errno 13] Permission denied: 'C:/Users/xxx/Documents/temp' 

什么是错在我的代码吗?

+1

那么,该文件的权限是什么?看起来你的代码没有任何问题。 –

+0

这是一个文件夹。脚本应该在其上写入证书。 – user2192774

+0

这就是问题所在。您无法将数据写入文件夹,您必须在该文件夹中指定一个文件。 –

回答

0

当您指定文件时,您正在指定一个文件夹。按照documentation for the M2Crypto.X509.load_cert function,你应该指定一个文件的路径,而不是一个文件夹:

Load certificate from file.

@type file: string
@param file: Name of file containing certificate in either DER or PEM format.

如果你尝试和负载或写入数据到一个文件夹,而不是一个文件,你会得到一个“权限否认“错误,至少在Windows上。为了验证这一点,我创建了一个名为temp文件夹,并试图从中读取和写入数据到它,我得到了确切的同样的错误在你的问题:

Traceback (most recent call last): 
    File "test.py", line 4, in <module> 
    with open(r'C:\Users\Random\Documents\temp', 'w') as f: 
IOError: [Errno 13] Permission denied: 'C:\\Users\\Random\\Documents\\temp' 

Traceback (most recent call last): 
    File "test.py", line 4, in <module> 
    with open(r'C:\Users\Random\Documents\temp', 'r') as f: 
IOError: [Errno 13] Permission denied: 'C:\\Users\\Random\\Documents\\temp' 

在未来,你应该看看在你正在使用的函数的文档中,确保你不仅传递正确类型的变量,而且数据本身就是函数所期望的。

此外,在你的问题中,你说你试图写入一个文件,但是你正在使用一个从文件中读取的函数。我建议通过并确保你在做你认为你在做的事情。再次,阅读您正在使用的库的文档将会很有帮助。