You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python脚本在GCP虚拟机上访问Google Drive存储的文件

GCE 虚拟机通过服务账号访问 Google Drive 文件(Python 实现指南)

1. 环境依赖安装

首先登录你的 Compute Engine 虚拟机,执行以下命令安装所需 Python 依赖库:

pip install google-api-python-client google-auth-httplib2 google-auth oauth2client

2. 服务账号权限确认

  • 确认你关联虚拟机的服务账号已被添加到目标 Google Drive 文件夹的共享列表,权限至少为「查看者」
  • 确认 GCE 实例的 Cloud API 访问范围已开启 Google Drive 权限:若未开启,可进入GCP控制台对应实例详情页点击「编辑」,找到「Cloud API 访问范围」板块,将Google Drive选项设置为启用,保存后重启实例即可。

3. 核心代码实现

3.1 初始化 Drive 服务

你可以选择两种方式获取服务账号凭证:

  1. 直接使用GCE虚拟机自带的服务账号凭证,无需手动上传密钥文件:
from google.auth import compute_engine
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
import io

# 配置权限范围
SCOPES = ['https://www.googleapis.com/auth/drive']
credentials = compute_engine.Credentials(scopes=SCOPES)

# 初始化Drive服务
service = build('drive', 'v3', credentials=credentials)
  1. 手动上传服务账号JSON密钥到虚拟机的场景:
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
import io

SCOPES = ['https://www.googleapis.com/auth/drive']
# 替换为你的密钥文件在虚拟机上的路径
SERVICE_ACCOUNT_FILE = '/path/to/your/service-account-key.json'
credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

service = build('drive', 'v3', credentials=credentials)

3.2 列出指定文件夹下的所有文件

# 替换为你要访问的Google Drive文件夹ID
TARGET_FOLDER_ID = '替换为你的文件夹ID'

# 执行查询
results = service.files().list(
    q=f"'{TARGET_FOLDER_ID}' in parents and trashed=false",
    pageSize=50,
    fields="nextPageToken, files(id, name)"
).execute()
file_list = results.get('files', [])

if not file_list:
    print('该文件夹下无文件')
else:
    print('文件夹下文件列表:')
    for file in file_list:
        print(f'文件名:{file["name"]},文件ID:{file["id"]}')

3.3 下载指定文件到本地

# 替换为你要下载的文件ID
FILE_ID = '替换为目标文件ID'
# 替换为你要保存到虚拟机本地的路径
SAVE_PATH = './target_file'

request = service.files().get_media(fileId=FILE_ID)
file_handler = io.FileIO(SAVE_PATH, 'wb')
downloader = MediaIoBaseDownload(file_handler, request)
download_finished = False

while not download_finished:
    status, download_finished = downloader.next_chunk()
    print(f'下载进度:{int(status.progress() * 100)}%')

print('文件下载完成')

4. 常用说明

  • 文件/文件夹ID获取方式:打开Google Drive网页版,进入目标文件夹或打开目标文件,URL中d/后面、/view前面的字符串就是对应ID
  • 如果遇到权限报错,优先检查服务账号的共享权限配置是否正确,以及Drive API是否在GCP项目中已启用

内容的提问来源于stack exchange,提问作者Pramod yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:45:00