Last active
August 11, 2017 02:04
-
-
Save andreburto/1ba0bfbf3e574a2cd5fc8428b945a2cb to your computer and use it in GitHub Desktop.
Quickly login to the Django Admin screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python standard library | |
import os | |
import getpass | |
from urlparse import urlparse | |
# Third-party libraries | |
import requests | |
from bs4 import BeautifulSoup | |
__author__ = 'Andy Burton' | |
# The id used in a django suit admin login form. | |
FORM_ID = 'login-form' | |
# Holds the data from the program that will go in the POST request. | |
FILL_OUT_FORM = {} | |
def env_or_getpass(var_name, msg): | |
""" Check to see if the env var exists. If not let the user type it in. """ | |
if os.getenv(var_name): | |
return os.getenv(var_name) | |
return getpass.getpass(msg) | |
def generate_login_post_data(form_obj): | |
""" Create the data that with be sent to the login form as a POST. """ | |
REQUEST_DATA = {} | |
for tag in [input for input in form.find_all('input') if input.get('name')]: | |
REQUEST_DATA[tag['name']] = FILL_OUT_FORM.get(tag['name'], tag.get('value')) | |
return REQUEST_DATA | |
if __name__ == '__main__': | |
# Get the needed information from the environment or user. | |
ADMIN_ID = env_or_getpass('ADMIN_ID', 'Enter your admin username:') | |
ADMIN_PW = env_or_getpass('ADMIN_PW', 'Enter your admin password:') | |
ADMIN_URL = env_or_getpass('ADMIN_URL', 'Enter the admin login URL:') | |
# Set the initial state of the data that will go into the request | |
FILL_OUT_FORM = { | |
'username': ADMIN_ID, | |
'password': ADMIN_PW, | |
} | |
s = requests.Session() | |
html = s.get(ADMIN_URL, verify=False) | |
print('Completed GET request {}.'.format(ADMIN_URL)) | |
# If you can't GET to the login form initially then there's no need to proceed. | |
if html.status_code != 200: | |
raise ValueError('Status should be 200, but it is {}.'.format(html.status_code)) | |
bs = BeautifulSoup(html.content, 'html.parser') | |
# Grab the <form>...</form> section of the page. | |
form = bs.find(id=FORM_ID) | |
# Replace the initial path with the action from the form tag. | |
url_parts = urlparse(ADMIN_URL) | |
post_url = '{}://{}{}'.format(url_parts.scheme, url_parts.netloc, form.get('action')) | |
print('Starting POST request {}.'.format(post_url)) | |
REQUEST_DATA = generate_login_post_data(form) | |
# Post the login data. Django wants a referer address as a security feature. | |
resp = s.post(post_url, headers={'referer': html.url}, data=REQUEST_DATA, timeout=15, verify=False) | |
print('Finished with status code {}.'.format(resp.status_code)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment