【问题标题】:How to use a service account with Google's python api and drive?如何将服务帐户与 Google 的 python api 和驱动器一起使用?
【发布时间】:2026-01-06 10:50:01
【问题描述】:

我尝试编写 python 2.7 脚本将文件上传到我的个人谷歌驱动器文件夹中。

经过几个问题我卡住了才知道。这是我当前的错误:

NotImplementedError:PyCrpto 库不支持 PKCS12 格式。如果可以选择本机代码,请尝试转换为“PEM”(openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > privatekey.pem)或使用 PyOpenSSL。

正如questionanswer 中所述,我已经尝试运行此命令。

openssl pkcs12 -in privatekey.p12 -nodes -nocerts > privatekey.pem
openssl pkcs8 -nocrypt -in privatekey.pem -passin pass:notasecret -topk8 -out pk.pem

我从新的现代花式谷歌开发者控制台下载的 privatekey.p12 最初命名为something-0123eed.json,看起来像这样1

{
  "private_key_id": "9ced108fe72345373b75b03d7e967a3f8c0084ca",
  "private_key": "-----BEGIN PRIVATE KEY-----\nxe91Tr6RHs57LKX2HivFmOQwcFoJkUPrbB6Gwy8prE...Pc9jNExo5Krp1kLrkJYxAOmUWxWwPJ4pCx7Lxc6uQQnAlKyRmnfVpdS2I0\n-----END PRIVATE KEY-----\n",
  "client_email": "0KsVeSAa91UtEGvY9lil@developer.gserviceaccount.com",
  "client_id": "0KsVeSAa91UtEGvY9lil.apps.googleusercontent.com",
  "type": "service_account"
}

我的 python 代码如下所示:

#!/bin/env python2.7

from apiclient.discovery import build
from apiclient.http import MediaFileUpload
import httplib2
from oauth2client.client import SignedJwtAssertionCredentials


credentials = SignedJwtAssertionCredentials(
        service_account_name='0KsVeSAa91UtEGvY9lil@developer.gserviceaccount.com',
        private_key=key,
        scope = [
                'https://www.googleapis.com/auth/drive',
                'https://www.googleapis.com/auth/drive.file',
                'https://www.googleapis.com/auth/drive.appdata',
                'https://www.googleapis.com/auth/drive.apps.readonly'
        ]
)

http = httplib2.Http()
http = credentials.authorize(http)

drive_folder_id = 'jhIKHOG6supMhpjPJFHffZarwxP6'


service = build('drive', 'v2', http=http)


media_body = MediaFileUpload('/path/to/superfile.gpg'), mimetype='application/pgp-encrypted')
body = {
        'title': 'superfile.gpg',
        'description': '',
        'mimeType': 'application/pgp-encrypted',
        'parents': [{'id': drive_folder_id}]
}

file = service.files().insert(
        body=body,
        media_body=media_body).execute()

1:(当然,我用垃圾改变了值)

【问题讨论】:

    标签: python google-api pycrypto google-api-python-client pkcs#12


    【解决方案1】:

    我找到了answer in this gist

    openssl pkcs12 -passin pass:notasecret -in privatekey.p12 -nocerts -passout pass:notasecret -out key.pem
    openssl pkcs8 -nocrypt -in key.pem -passin pass:notasecret -topk8 -out privatekey.pem
    rm key.pem
    

    但在此之前,我必须重新生成一个新的私钥,但采用 P12 格式。

    【讨论】:

    • google datastore 包中的调试消息建议如下:'尝试转换为“PEM”(openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > privatekey.pem)'。
    • 但结果是您必须手动删除标题,如this answer
    最近更新 更多