通过Python从SharePoint检索文件时出错

0 投票
1 回答
52 浏览
提问于 2025-04-14 17:56

我在用Python从SharePoint下载文件时遇到了一个错误。错误信息是:在从XML响应中获取令牌时发生了错误:AADSTS53003:访问被条件访问策略阻止。这个访问策略不允许发放令牌。有没有人能帮我解决这个问题?以下是我的代码:

import shutil
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
 
sharepoint_url = "Sharepoint_site_url"
site_url = "site url"
username = "My_username"
password = "Password"
 
# File path components
library_name = "Shared Documents"
folder_name = "ABCD"
 
# Construct the full file path
file_path = f"https://xyz.sharepoint.com/sites/site_name/{library_name}/{folder_name}/"
 
# Encode the file path
encoded_file_path = file_path.replace(" ", "%20")  # Replace spaces with %20
print(encoded_file_path)
 
# Authenticate with SharePoint
ctx_auth = AuthenticationContext(sharepoint_url)
 
if ctx_auth.acquire_token_for_user(username, password):
    # Connect to SharePoint site
    ctx = ClientContext(site_url, ctx_auth)
    web = ctx.web
    ctx.load(web)

    # Get all files in the SharePoint folder
    files = ctx.web.get_folder_by_server_relative_path(file_path).files
    ctx.load(files)
    ctx.execute_query()
 
    # Create a folder on the C drive
    c_drive_folder1 = "C:/ENTERP/Raw"
    c_drive_folder2 = "C:/ENTERPR/Processed"
    os.makedirs(c_drive_folder1, exist_ok=True)
    os.makedirs(c_drive_folder2, exist_ok=True)
 
# Download and save each file to the C drive folder
for file in files:
        print(1)
        file_name = file.properties["Name"]
        file_url = f"{site_url}/{library_name}/{folder_name}/{file_name}"
        file_content = ctx.web.get_file_by_server_relative_path(file_url).read().execute_query()
 
        # Save the file to the C drive folder
        file_path_on_c_drive = os.path.join(c_drive_folder1, file_name)
        with open(file_path_on_c_drive, "wb") as local_file:
            local_file.write(file_content)
 
        print(f"Downloaded and saved: {file_name} to {file_path_on_c_drive}")
        print("Download process completed.")
else:
        print("Failed to authenticate with SharePoint.")```
        

        


I tried others codes too, but everytime i am getting the same error.

1 个回答

0

你遇到的错误信息说明有一个条件访问政策在起作用,这个政策阻止了令牌的发放,因此你无法访问SharePoint资源。通常,这种情况发生在你的Azure AD租户中配置的安全政策根据某些条件(比如位置、设备合规性或其他因素)限制了访问。

要解决这个问题,你可能需要调整你Azure AD租户中的条件访问政策,以允许在你正在使用的场景中发放令牌,或者你可能需要将与你的Python脚本相关的应用程序或服务主体从这些政策中排除。

撰写回答