Logging in to this website using requests module in python3 - python-3.x

Here's what I have done so far. I had to extract the CSFRToken manually (I don't know regex, so that part is messy). Is CSFR part of cookies? Because my cookies only shows two other ID type params, so I dropped the cookie part and did it this way.
import requests
URL = r'http://login.cheezburger.com/'
client = requests.session()
login_page = client.get(URL)
index = login_page.text.find("CSRFToken")
token = login_page.text[index:index+90].split('"')[-2] # This works, I guarantee :)
#print(token) I checked it manually
login_data = {'rlm': 'Shopper',
'for': r'http://login.cheezburger.com/',
'username': 'myusername',
'password': 'mypassword',
'CSRFToken': token}
req = client.post(URL, data=login_data)
Now, there is no error per say, but I am not logging in to this site either. The text of this request shows that I am still stuck in the login page!
The parameters send are (as shown in the dev tools of firefox):
rlm: 'Shopper'
for: 'http://login.cheezburger.com/'
username: 'myusername',
password: 'mypassword',
CSRFToken: '8uhhbf67-1233-fff3-123g1-123123fsdfs22'
The websites source is as follows (the part that contains the form data):
<div class="contents-msl">
<h2>Client Login</h2>
<p>Enter username and password</p>
<div class="form-all-msl">
<form action="/login.action" id="loginForm" method="post"
enctype="application/x-www-form-urlencoded"><input type=hidden name=rlm
value="Shopper"><input
type=hidden
name=for
value="http%3a%2f%2flogin%cheezburger%2ecom%2f">
<ul class="form-section-msl">
<label class="form-label-left-msl" for="loginUserName">
Username<span class="form-required">*</span>
</label>
<div class="form-input-msl">
<input type="text" class="form-textbox-msl" id="loginUserName" name="username"
size="20">
</div>
<label class="form-label-left-msl" for="loginPwd">
Password<span class="form-required-msl">*</span>
</label>
<div class="form-input-msl">
<input type="password" class="form-textbox-msl" id="loginPwd" name="password"
size="20">
</div>
<div class="form-input-msl">
<div class="form-single-column-msl">
</div>
</div>
</ul>
</div>
<button class="members-btn-msl" type="submit">Login</button>
<input type="hidden" name="CSRFToken" class="CSRFToken" value="8uhhbf67-1233-fff3-123g1-123123fsdfs22" /> </form>
</div>
</div>

You maybe want to add some headers
headers = {
'Accept':
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding':
'gzip, deflate, sdch',
'Accept-Language':
'en-US,en;q=0.8,vi;q=0.6',
'Cache-Control':
'max-age=0',
'Connection':
'keep-alive',
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
}
Then add headers to your code:
req = client.post(URL, data=login_data)
Good luck !

Related

Python: How to select form from URL response without 'name' tag

I try to select a form from a URL response with Python. This is the form and there is only on form available in the response.
<form id="login_form" data-redirect='{"type":"refresh","link":"\/"}'>
<div class="unlogged-input-container">
<input class="unlogged-input" type="email" id="login_mail" data-check="email" required value="" />
<label class="unlogged-label" for="login_mail">E-Mail-Adress</label>
</div>
<div class="unlogged-input-container">
<input class="unlogged-input unlogged-input-pwd" type="password" id="login_password" required />
<label class="unlogged-label" for="login_password">Password</label>
</div>
<div class="recaptcha-wrapper">
<div class="recaptcha-container">
<div id="recaptcha_enterprise_container"></div>
</div>
</div>
<button id="login_form_submit" class="auth-cta gap-m-top" type="submit">
<span class="unlogged-btn-label">Logon</span>
</button>
<input type="hidden" id="login_method" name="login_method" value="email">
</form>
With
print(br.select_form(nr=0))
it returns
None
But
print([f.attrs['id'] for f in br.forms()])
returns
['login_form']
and
for x in br.forms(): print(x)
returns
<GET https://www.<target_domain>/en/login application/x-www-form-urlencoded
<TextControl(<None>=)>
<PasswordControl(<None>=)>
<SubmitButtonControl(<None>=) (readonly)>
<HiddenControl(login_method=email) (readonly)>>
This is the sample code for it:
import mechanize
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_gzip(False)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_equiv(True)
br.addheaders = [
('User-Agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'),
('Accept-Encoding', 'deflate,br'),
('Content-Type', 'application/x-www-form-urlencoded'),
('Cache-Control', 'no-cache'),
('Connection', 'keep-alive')
]
url = 'https://<target_domain>/en/login'
br.open(url)
print([f.attrs['id'] for f in br.forms()])
print(br.select_form(nr=0))
for x in br.forms():
print(x)
But how to select this form?

Form data display on terminal & doesn't save in postgres database django

In my cause of learning django, I decided to start with small projects, I'm working on a simple registration page. I have my form on the home page (index.html). And I have a view.py page I pass all the data from the form to my postgres db. I realise data does not save in db, instead all the registration data display in terminal and the url bar. Here's my code;
Form (index.html)
<form action="/index/" method="POST">
{% csrf_token %}
<div><p><label for="fName">First Name</label></div>
<div><input type="text" name="fName"></input></div>
</p>
<p>
<label for="lName">Last Name</label>
<input type="text" name="lName"></input>
</p>
<p>
<label for="email">Email</label>
<input type="text" name="email"></input>
</p>
<div><p><label for="uName">Username</label></div>
<div><input type="text" name="uName"></input></div>
</p>
<p>
<label for="password1">Password</label>
<input type="password" name="Password1"></input>
</p>
<p>
<label for="password2">Confirm Password</label>
<input type="password" name="Password2"></input>
</p>
<div> <p><input type="submit"></input></p> </div>
</form>
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
def index(request):
if request.method == 'POST':
first_name = request.POST['fName']
last_name = request.POST['lName']
username = request.POST['uName']
password1 = request.POST['password1']
password2 = request.POST['password2']
email = request.POST['email']
user = User.objects.create_user(username=username, password=password1, email=email,
first_name=first_name, last_name=last_name)
user.save()
print('user created')
return redirect('/')
else:
return render(request, 'index.html')
Database setting on settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bookconf',
'USER': 'postgres',
'PASSWORD': 'olumide',
'HOST': 'localhost',
'PORT': '5432',
}
}
I suspect the data is collected and them skip to executed this return render(request, 'index.html') because after I enter submit, the home page(index.html) gets reloaded.
In addition, I'm certain psycopg2 is installed. No data gets saved in the db and no error messages except the message below.
Message on terminal
[03/Sep/2020 04:22:18] "GET / HTTP/1.1" 200 25753
[03/Sep/2020 04:22:37] "GET /?csrfmiddlewaretoken=LtMIZL5z9yGYElCkunBrkMt2mS7rMr90cyxlHPVUfiA6hpaF80Phfpjbrp6RUVpj&fName=Ken&lName=Cole&email=kcole%40mail.com&uName=k.cole&Password1=1122&Password2=1122 HTTP/1.1" 200 25753
Ideas on how to fix this will be much appreciated. Thanks

Response difference on local and EC2 server when hitting request in nodejs

Okay so I did not get anything from my last SO question may be I was not so clear in detailing the issue I am facing, so hoping this time I'll get solution for my issue:
var request = require("request");
var options = { method: 'GET',
url: 'https://shop.advanceautoparts.com/web/AAPStoresWithAvailableInventoryCmd',
qs:
{ quantity: '1',
partNumber: '2130015-P',
storeId: '10151',
catalogId: '10051',
langId: '-1',
loadStoresComponent: 'true',
latitude: '',
longitude: '',
prefStoreNickName: '8511' },
headers:
{ accept: 'application/json, text/plain, /',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
origin: 'https://shop.advanceautoparts.com' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
I am getting accurate data about what I need when I try this at local ENV.
BUT when the same code is executed at my EC2 server, I get an awkward response from the code above.
RESPONSE AT LOCAL
{
"loadStoresComponent": ["true"],
"langId": ["-1"],
"quantity": ["1"],
"prefStoreNickName": ["8511"],
"latitude": [""],
"longitude": [""],
"authToken": "-1002%2C3a0VN%2Bt240MbliDjfWLSDJxolLA%3D",
"catalogId": ["10051"],
"DM_PersistentCookieCreated": ["true"],
"partNumber": ["2130015-P"],
"storeId": ["10151"],
"Result": {
"view": "availableStoresList",
"storesListMap": [
{
"inStock": true,
"state": "NC",
"isPrefStore": false,
"distance": 0,
"storeBrand": "AAP",
"city": "MATTHEWS",
"latitude": "35.137527",
"address1": "9507 INDEPENDENCE BLVD.",
"zipCode": "281050000",
"nickName": "8511",
"phone": "704-845-5004",
"longitude": "-80.715079"
},
{
"inStock": true,
"state": "NC",
"isPrefStore": false,
"distance": 4,
.....
.....
}
RESPONSE AT SERVER
<div class="pagewidth">
<div class="logo"> </div>
<div id="tagline"> </div>
<div class="clear"> </div>
<div class="header"> </div>
<div class="content">
<p class="heading">We're offline for a tune-up, we'll be up and running smoothly very soon. </p>
<p class="heading">In the meantime, here are some other options available:</p>
<div class="section group">
<div class="col span_1_of_4"> Visit an <br />
<strong>Advance Auto Parts store</strong><br />
<img src="/MaintPage/images/DM150205_maintenance_page_07.png" width="200" height="125" border="0" /> </div>
<div class="col span_3_of_4"> Sign up for <br />
<strong>SpeedPerks Rewards</strong><br />
<img src="/MaintPage/images/sp-logo.png" width="204" height="100" border="0" style="margin-top:20px;" /> </div>
<div class="col span_4_of_4"> View us on Social Media <strong><br />
Facebook/Twitter/Blog</strong><br />
<img src="/MaintPage/images/DM150205_maintenance_page_12.png" width="110" height="125" border="0" /><img src="/MaintPage/images/DM150205_maintenance_page_16.png" width="92" height="125" border="0" /><img src="/MaintPage/images/button-m.png" width="90" height="125" border="0" style="margin-left:0px;" /> </div>
</div>
<div class="clear"> </div>
<p class="heading">We appreciate your patience – on your next visit, <strong>use coupon code PS20 for 20% off your purchase. </strong></p>
<p class="coupon"><img src="/MaintPage/images/DM150205_maintenance_page_21.png" width="354" height="134" /></p>
<p style="margin:30px; text-align:center;">We look forward to serving you,<br />
The Advance Team</p>
<p style="margin:30px; text-align:center;"> </p>
</div>
</div>
Basically it is an offline page(didn't paste whole HTML body and CSS), by which I feel that they are denying to return the response of my request.
I have tried adding x-forwarded-for in my call as well but no luck with that.
And I am getting an accurate response by adding x-forwarded-for in rails, but I guess there may be some extra headers or anything else I need to add in my request to get the desired result.
Any thoughts on my issue?

python requests to login or fill a form

How to fill a form and get the redirect url from the login.
Hi I am trying to submit a login page.
Tried multiple pages but didn't worked out.
<div class="form-group">
<input name="ctl00$MainContent$ctlLogin$_UserName" type="text" size="18" id="ctl00_MainContent_ctlLogin__UserName" accesskey="u" tabindex="60" placeholder="username" class="form-control" name="username" title="username" />
</div>
<div class="form-group">
<input name="ctl00$MainContent$ctlLogin$_Password" type="password" size="18" id="ctl00_MainContent_ctlLogin__Password" accesskey="p" tabindex="61" onkeyup="onkey(event, this.value, this)" placeholder="password" class="form-control" name="password" title="password" />
</div>
<input type="submit" name="ctl00$MainContent$ctlLogin$BtnSubmit" value="Login" id="ctl00_MainContent_ctlLogin_BtnSubmit" class="btn btn-danger" style="text-transform: uppercase;" />
<input name="ctl00$MainContent$ctlLogin$_IdBook" type="hidden" id="ctl00_MainContent_ctlLogin__IdBook" />
<input name="ctl00$MainContent$ctlLogin$Redir" type="hidden" id="ctl00_MainContent_ctlLogin_Redir" value="wager/welcome.aspx" />
import requests
import json
url = 'http://playsports365.com'
data = requests.get(url)
print(data.text)
form_data = {"username":"username","password":"password","action":"login"}
s = requests.session()
r = s.post(url,form_data)
but somehow it is still taking me the first or login page itself.
You have to scrape values of __VIEWSTATE, __VIEWSTATEGENERATOR, __EVENTVALIDATION, ctl00$MainContent$ctlLogin$BtnSubmit, ctl00$MainContent$ctlLogin$Redir from the home page and add it to your form_data.
import requests
import bs4 as bs
# Create session.
session = requests.Session()
headers = {
'Host': 'playsports365.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Content-Type': 'application/x-www-form-urlencoded',
'Origin': 'http://playsports365.com',
'Referer': 'http://playsports365.com/default.aspx',
}
# Add headers in session.
session.headers.update(headers)
# Login page request.
login_page_url = 'http://playsports365.com/default.aspx'
response = session.get(login_page_url)
soup = bs.BeautifulSoup(response.text, 'lxml')
# Extract payload data from login page.
event_target = soup.find('input', {'id': '__EVENTTARGET'}).get('value')
event_argument = soup.find('input', {'id': '__EVENTARGUMENT'}).get('value')
view_state = soup.find('input', {'id': '__VIEWSTATE'}).get('value')
view_state_generator = soup.find('input', {'id': '__VIEWSTATEGENERATOR'}).get('value')
event_validation = soup.find('input', {'id': '__EVENTVALIDATION'}).get('value')
btn_submit = soup.find('input', {'name': 'ctl00$MainContent$ctlLogin$BtnSubmit'}).get('value')
re_dir = soup.find('input', {'name': 'ctl00$MainContent$ctlLogin$Redir'}).get('value')
# Add data in payload.
form_data = {
'ctl00$MainContent$ctlLogin$_UserName': 'YOUR USERNAME',
'ctl00$MainContent$ctlLogin$_Password': 'YOUR PASSWORD',
'__EVENTTARGET': event_target,
'__EVENTARGUMENT': event_argument,
'__VIEWSTATE': view_state,
'__VIEWSTATEGENERATOR': view_state_generator,
'__EVENTVALIDATION': event_validation,
'ctl00$MainContent$ctlLogin$BtnSubmit': btn_submit,
'ctl00$MainContent$ctlLogin$Redir': re_dir,
}
# Request for login.
login_url = 'http://playsports365.com/default.aspx'
login_response = session.post(login_url, data=form_data)
print(login_response.status_code, response.text)

nginx / node.js sendmail form

Trying to send user feedback to email using an embedded contact form; without using a mailto:
I have a mostly static web page served up by nginx containing html/browser-javascript.
The strategy is very similar to this:
http://www.phpeasystep.com/phptu/8.html
My static page has a form section:
<form action="sendmail.js" method="post" id="contactForm">
<div class="sep">
<label for="name" class="txt">Name:</label>
<input type="text" name="name" value="" id="name">
</div>
<div class="sep">
<label for="email" class="txt">Email:</label>
<input type="text" name="email" value="" id="email">
</div>
<div class="sep">
<label for="tele" class="txt">Telephone:</label>
<input type="text" name="tele" value="" id="tele">
</div>
<div class="sep special">
<label for="last" class="txt">Don't fill this in:</label>
<input type="text" name="last" value="" id="last">
</div>
<div class="sep">
<label for="message" class="txt">Message:</label>
<textarea rows="5" name="message" id="message"></textarea>
</div>
<div class="buttonAlign submitbutton">
<button type="submit" class="button mediumButton" id="submit">Send Message</button>
</div>
</form>
I want the form elements passed to a server side node.js script, sendmail.js, and have that script compose an email with the form elements then dispatch.
I'm rather new to node.js and nginx and I'm not sure what I'm missing; but, its not working, the script is not running at all.
I've added nothing special to the nginx default.conf file.
The node.js script is in my base directory and if I rename it, I get a file not found error. So, I know nginx is looking for it. The first line of the script file has the node.js she-bang and its chmod'ed to executable.
Appreciate any help.
I get the following message in access.log
==> access.log <==
"POST /sendmail.js HTTP/1.1" 405 574 "https://xyzzy.net/index.html" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)" "-"
I'm not expecting a response to appear in the web page. I just want to execute the sendmail.js script and send an email containing the form data.
Here's a 'dummy' script which attempts to create/write a 'breadcrumbs' file in /tmp
#!/usr/local/bin/node
var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});

Resources