SSH环境下Python上传Zip到Google Drive的认证问题求助
解决SSH环境下PyDrive Google Drive认证无法连接本地主机的问题
问题场景
你尝试通过以下Python代码结合settings.yaml,在SSH环境下将Zip文件上传至Google Drive,但在浏览器认证步骤中因无法连接本地主机失败:
上传代码
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive import os # 补充原代码缺失的os模块导入 gauth = GoogleAuth() drive = GoogleDrive(gauth) upload_file_list = ['checkpoint-5824.zip'] exist_file_list = drive.ListFile({'q': "'{}' in parents and trashed=false".format("1PtwHBXcXdmamofSgZZNpgw7wo...")}).GetList() for upload_file in upload_file_list: if (not os.path.exists(upload_file)): continue fileName = os.path.basename(upload_file) for file1 in exist_file_list: if file1['title'] == fileName: file1.Delete() gfile = drive.CreateFile({'parents': [{'id': "1PtwHBXcXdmamofSgZZNpgw7..."}], 'title': fileName}) # 读取文件并设置为实例内容 gfile.SetContentFile(upload_file) gfile.Upload() # 上传文件
配置文件settings.yaml
client_config_backend: settings client_config: client_id: 你的客户端ID client_secret: 你的客户端密钥 save_credentials: True save_credentials_backend: file save_credentials_file: credentials.json get_refresh_token: True oauth_scope: - https://www.googleapis.com/auth/drive.file - https://www.googleapis.com/auth/drive.install
问题原因
SSH远程环境通常无图形界面,且本地端口无法被远程进程直接访问,PyDrive默认的本地浏览器授权模式无法正常工作。
可行解决办法
方法1:离线生成凭证后上传至服务器
- 在本地有图形界面的机器上,填写好
settings.yaml中的client_id和client_secret - 运行一次上传代码,完成浏览器授权流程,生成
credentials.json文件 - 将生成的
credentials.json上传到SSH服务器的代码目录下 - 服务器上运行代码时,PyDrive会自动读取已有的凭证,跳过浏览器认证步骤
方法2:使用命令行授权模式
修改代码中的认证初始化部分,强制启用命令行授权:
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive import os gauth = GoogleAuth() # 启用命令行授权模式 gauth.CommandLineAuth() drive = GoogleDrive(gauth) # 后续上传代码保持不变 upload_file_list = ['checkpoint-5824.zip'] # ... 剩余代码省略
运行代码后,终端会输出一个授权URL:
Go to the following link in your browser:
https://accounts.google.com/o/oauth2/auth?xxxx
在本地浏览器打开该链接,完成Google账号授权后,会得到一个授权验证码,将验证码输入到SSH终端中即可完成认证,之后会自动生成credentials.json,下次运行无需重复认证。
注意事项
- 确保
settings.yaml中的client_id和client_secret是从Google Cloud Console正确创建的OAuth 2.0客户端ID信息(需选择"桌面应用"类型) - 若使用方法2,确保服务器能访问Google的授权域名
内容的提问来源于stack exchange,提问作者tjns
相关产品推荐
相关产品推荐

