如何用Python访问带双因素认证(VIP Access)的SharePoint并下载文件
普通用户名密码登录方式在启用双因素认证(MFA)的SharePoint站点上会失效,你需要使用支持MFA的认证流程来处理VIP Access的OTP验证。下面是基于office365-rest-python-client库的具体实现方案:
1. 升级库到最新版本
旧版本库对MFA支持有限,先确保安装最新版:
pip install --upgrade office365-rest-python-client
2. 设备代码流认证(适配无图形界面/手动输入OTP)
这种方式适合服务器或无图形界面环境,需要你手动在浏览器完成OTP验证:
from office365.runtime.auth.authentication_context import AuthenticationContext from office365.sharepoint.client_context import ClientContext from office365.runtime.auth.device_code_provider import DeviceCodeProvider # 替换为你的SharePoint站点URL和Office365用户名 site_url = "https://your-domain.sharepoint.com/sites/your-site" username = "your-office365-account@your-domain.com" # 初始化认证上下文 ctx_auth = AuthenticationContext(site_url) device_provider = DeviceCodeProvider(ctx_auth, username) # 输出认证提示 print("请按以下步骤完成验证:") print(device_provider.get_message()) # 等待用户完成MFA验证(输入VIP Access的OTP) ctx_auth.acquire_token_with_device_code(device_provider) # 验证登录并获取站点信息 ctx = ClientContext(site_url, ctx_auth) web = ctx.web ctx.load(web) ctx.execute_query() print(f"已成功登录站点: {web.properties['Title']}") # 下载目标文件(替换为你的文件路径和本地保存路径) file_server_path = "/sites/your-site/Shared Documents/your-file.pdf" local_save_path = "./downloaded-file.pdf" target_file = ctx.web.get_file_by_server_relative_url(file_server_path) with open(local_save_path, "wb") as local_file: target_file.download(local_file) ctx.execute_query() print(f"文件已下载到: {local_save_path}")
操作流程
- 运行代码后,控制台会显示一个验证网址(如
https://microsoft.com/devicelogin)和一串设备代码 - 打开浏览器访问该网址,输入设备代码,然后登录你的Office365账号
- 在验证环节输入VIP Access推送的OTP验证码,完成认证
- 回到程序,会自动获取认证令牌并执行文件下载
3. 交互式认证(适用于有图形界面的环境)
如果你的运行环境支持图形界面,这种方式会自动弹出浏览器窗口引导你完成MFA验证,代码更简洁:
from office365.sharepoint.client_context import ClientContext from office365.runtime.auth.interactive_auth_provider import InteractiveAuthProvider site_url = "https://your-domain.sharepoint.com/sites/your-site" username = "your-office365-account@your-domain.com" # 初始化交互式认证 auth_provider = InteractiveAuthProvider(site_url, username) ctx = ClientContext(site_url, auth_provider) # 验证登录 web = ctx.web ctx.load(web) ctx.execute_query() print(f"已成功登录站点: {web.properties['Title']}") # 下载文件代码同前 file_server_path = "/sites/your-site/Shared Documents/your-file.pdf" local_save_path = "./downloaded-file.pdf" target_file = ctx.web.get_file_by_server_relative_url(file_server_path) with open(local_save_path, "wb") as local_file: target_file.download(local_file) ctx.execute_query() print(f"文件已下载到: {local_save_path}")
注意事项
- 确保你的Office365账号拥有目标SharePoint站点和文件的访问权限
- 设备代码流的认证令牌有有效期,如需长期复用,可通过库的令牌缓存机制保存令牌到本地
- 无图形界面环境下必须使用设备代码流,交互式认证依赖图形界面支持
内容的提问来源于stack exchange,提问作者Krishna Namani
相关产品推荐
相关产品推荐

