Accessing sharepoint site in python with windows authentication
I am trying to work with a sharepoint site using my windows authentication. I can use a module requests
to access the site, but for that I have to explicitly provide my Windows password.
import requests
from requests_ntlm import HttpNtlmAuth
SITE = "https://sharepointsite.com/"
PASSWORD = "pw"
USERNAME = "domain\\user"
response = requests.get(SITE, auth=HttpNtlmAuth(USERNAME,PASSWORD))
print response.status_code
Is there a way for Python to access the site via Windows Authentication so I don't need to provide my password? It seems like it's possible with help requests_nltm
, but I can't figure out how to do it.
source to share
If you don't want to explicitly specify your Windows password, you can use the module getpass
:
import requests
from requests_ntlm import HttpNtlmAuth
import getpass
SITE = "https://sharepointsite.com/"
USERNAME = "domain\\user"
response = requests.get(SITE, auth=HttpNtlmAuth(USERNAME, getpass.getpass()))
print response.status_code
This way, you don't need to save the password in plain text.
Looking at the code for requests_ntlm
there is no way to use it without providing your password or hash of your password beforeHttpNtlmAuth
source to share
Have you considered storing the username and password as an environment variable on the machine running the script? This will prevent you from storing sensitive information in the script itself. Then only the machine administrator can access / change the confidential information.
cmd prompt
Set the desired variables through (below is the syntax for a Windows machine):
SET username=domain\\user
SET password=your_password
To make sure you set the variables correctly, type SET
in cmd prompt
and see if the variables are specified.
Once properly installed, use the python module os
to access the variables and use as desired:
import os
import requests
from requests_ntlm import HttpNtlmAuth
username = os.environ.get('username')
password = os.environ.get('password')
SITE = "https://sharepointsite.com/"
response = requests.get(SITE, auth=HttpNtlmAuth(username, password))
IMPORTANT NOTES:
- If you close the window
cmd prompt
, the environment variables you just set will be removed and your script will throw a "I can't find my environment variables" error. To avoid this, either always keep the windowcmd
open while the script is running, or set environment variables all the time (instructions here are for Windows. Note: instructions are for changing an environment variablePATH
, but you will get an idea of how to create / modify your own variables). - Be careful not to overwrite an existing environment variable. First double check that the name is available by listing all the variables (type
SET
incmd prompt
). - Environment variables are stored as a string
source to share