Last active
May 9, 2018 18:35
-
-
Save fduran/4543001 to your computer and use it in GitHub Desktop.
Python script to test/monitor if a Django site using authentication is up
This file contains 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
# www.fduran.com | |
# python script to test/monitor if a Django site using authentication is up | |
# with logging output to a file including response times | |
# use in cronjob and output to log file, for ex: python /path/to/script.py >> /var/log/webmonitor.log | |
# bash: install pip if not already in system | |
apt-get install python-setuptools python-dev build-essential | |
easy_install -U pip | |
# bash: install requests | |
pip install requests | |
# python script: | |
import requests | |
import datetime, sys | |
# constants | |
url = 'https://example.com/login/' | |
username = 'valid user' | |
password = 'valid password' | |
expected = 'string in landing authenticated page' # easier if not in login page | |
timeout = 2 # seconds | |
# send alert | |
def alert(message): | |
print message | |
# send email, SMS etc | |
sys.exit() | |
# end alert | |
# main | |
t1 = datetime.datetime.now() | |
print "----" | |
print t1 | |
r = requests.models.Response() | |
try: | |
r = requests.get(url, timeout=timeout) | |
except requests.ConnectionError: | |
alert("ALERT: page connection error") | |
except requests.Timeout: | |
alert("ALERT: page connection timedout more than seconds: " + timeout) | |
t2 = datetime.datetime.now() | |
print "Request time: " | |
print (t2 - t1) | |
if r.status_code != 200: | |
# alert page down | |
alert("ALERT: Page down") | |
else: | |
sessionid = r.cookies['sessionid'] | |
csrftoken = r.cookies['csrftoken'] | |
cookies = {'sessionid':sessionid, 'csrftoken':csrftoken} | |
payload = {'username':username, 'password':password, 'csrfmiddlewaretoken':csrftoken, 'next':''} | |
headers = {'Referer': url} | |
t1 = datetime.datetime.now() | |
try: | |
r = requests.post(url, cookies=cookies, data=payload, headers=headers, timeout=timeout) | |
except requests.ConnectionError: | |
alert("ALERT: post connection error") | |
except requests.Timeout: | |
alert("ALERT: post connection timedout") | |
t2 = datetime.datetime.now() | |
print "Post time: " | |
print (t2 - t1) | |
if r.status_code == 200: | |
if r.text.find('Please try again') != -1: | |
alert("ALERT: Wrong username or password") | |
elif r.text.find(expected) != -1: | |
# all good | |
print "All good" | |
else: | |
# alert | |
alert("ALERT: expected content not found") | |
else: | |
# alert | |
alert("ALERT: cannot authenticate/page not found") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment