Safely Download File With Authenticated Domain User With Python

Barnabás Nagy
1 min readFeb 21, 2020

I wanted to download file — actually a batch of files — from a site which needed domain user authentication. I saw several examples which uses the simple Username/Password authentication, but I wanted to avoid to hardcode my domain password into the python script…

I just found a nice python package for a solution: requests-negotiate-sspi: Windows SSPI-based Negotiate authentication support for Requests:

An implementation of HTTP Negotiate authentication for Requests. This module provides single-sign-on using Kerberos or NTLM using the Windows SSPI interface.

This module supports Extended Protection for Authentication (aka Channel Binding Hash), which makes it usable for services that require it, including Active Directory Federation Services.

Let’s see a simple implementation with shutil.copyfileobj. As the url is opened via stream, it write the bytes direcly to the disk, so the RAM s no limit on the filesize to download. It will request the file from site with your logged in user on the local machine:

Add an error handling. It will not avoid the error, but at least the script will not brake and it will inform you on the error:

Final addition, download the file into a temporary file first to avoid partial download if any errors occurred. You can check/test later if any .temp file remained after the run.

--

--

Barnabás Nagy

I’m an intl PM in localization, BI Developer and a certified Google Professional Data Engineer. My hobby projects: Data apps, open source apps and DIY stuffs