Python Facebook access_token using mechanize redirect - python

i'm building a python app that is using a login interface to automatically sign in to facebook by passing the users login data directly. Main Goal is to get the access_token from facebook.
the facebook login skript looks like this:
import mechanize
br = mechanize.Browser()
br.set_handle_equiv( True )
br.set_handle_gzip( True )
br.set_handle_redirect( True )
br.set_handle_referer( True )
br.set_handle_robots( False )
br.set_handle_refresh( mechanize._http.HTTPRefreshProcessor(), max_time = 1)
br.addheaders = [ ( 'User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1' ) ]
user = 'me#mymail.com'
password = 'myPass'
# note that client_id is pseudo-nr
url = 'https://m.facebook.com/dialog/oauth?client_id=123456789012345&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token'
#Open URL and submit
br.open(url)
br.select_form(nr=0)
br.form['email'] = user
br.form['pass'] = password
br.submit()
result = br.geturl()
print result
Actually the script is working pretty fine, but there seems to be a redirecting problem after
br.submit()
When logging in to the given URL via Firefox, after manually adding username/password and pressing the submit button, the following URL is called:
https://www.facebook.com/login.php?login_attempt=1&next=https%3A%2F%2Fwww.facebook.com%2Fv2.0%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fwww.facebook.com%252Fconnect%252Flogin_success.html%26response_type%3Dtoken%26client_id%3D123456789012345%26ret%3Dlogin&lwv=100
this is the same URL, that is given by br.submit() command.
unfortunately Firefox is performing another redirect, first to:
https://www.facebook.com/v2.0/dialog/oauth?redirect_uri=https%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html&response_type=token&client_id=123456789012345&ret=login&ext=143846220&hash=KefDdKCLQeJo_hJR
followed by the final destination:
https://www.facebook.com/connect/login_success.html#access_token=CAAGXPLMhY0cYMlFbAPXJnPKtEPPQCP4NNZCyJkiRLE1B0iHeK6KonmgsyrzQu4uJbfe1TDV1YrmtyFb3SuYJAVhZBazHDr49oYh3i5WThZAfgTDmtHFsmpvn3ZBpeJ3NR718Dn9rm0PX4ZCpsBA6wAItUdHDcAiOZBIZACliuVEefqseFXtqCNFN2ZC9UGslohsZD&expires_in=3780
I don't know why mechanize is not performing this redirect. Any ideas how to solve this?

Related

Python mechanize to login to account - form not submitting

I am trying to login to my bank website using Python and mechanize.
https://chaseonline.chase.com/Logon.aspx
I have looked at all the previous posted but still can't login. I'm thinking it may have to do with the way I am submitting my form. The HTML for the submit button is:
<input type="image" id="logon"
src="https://chaseonline.chase.com/images/logon.gif" onclick="return
check_all_fields_logon_RSA_Auth(document.getElementById('UserID'),
document.getElementById('Password'));" width="58" height="21" border="0"
title="Log On" tabindex="7">
Here is the script I'm using:
import mechanize
from bs4 import BeautifulSoup
import urllib2
import cookielib
from time import sleep
chase_url = 'https://chaseonline.chase.com/Logon.aspx'
# Browser
br = mechanize.Browser()
# Enable cookie support for urllib2
cookiejar = cookielib.LWPCookieJar()
br.set_cookiejar( cookiejar )
# Broser options
br.set_handle_equiv( True )
br.set_handle_gzip( True )
br.set_handle_redirect( True )
br.set_handle_referer( True )
br.set_handle_robots( False )
# Refresh handle
br.set_handle_refresh( mechanize._http.HTTPRefreshProcessor(), max_time = 1 )
br.addheaders = [ ( 'User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1' ) ]
# authenticate
br.open(chase_url)
br.select_form( nr=0 )
br.form['UserID'] = 'joe1234'
br.form['Password'] = '123456'
br.submit()
print "Success!\n"
sleep(10)
print br.title()
If the login worked, then the page should be "Chase Online - My Account"
What am I doing wrong?
I was trying to do something similar but with ESPN a few months ago. Mechanize gave me problems, then someone gave me the answer.
The answer is selenium.
https://selenium-python.readthedocs.org/getting-started.html
Otherwise, what exactly is going wrong when you run your script? Does it produce an error? What does the error say?

Mechanize/OWA user/password error

I'm trying to use Mechanize to get emails from my Outlook web client, but I'm having troubles logging in. It gives me the errors listed below. I've verified that the user name and password are correct. Any ideas?
Here is my code:
import mechanize
b = mechanize.Browser()
cj = cookielib.LWPCookieJar()
b.set_cookiejar(cj)
b.open('https://mail.example.com/owa/')
br.select_form("logonForm")
b['username'] = 'myname'
b['password'] = 'password'
b.submit()
I can see that form components are being accessed correctly, but after submitting, the login page displays again with two errors:
The user name or password you entered isn't correct. Try entering it again.
Please enable cookies for this Web site.
I thought the b.set_cookiejar(cj) would take care of cookies. Could this be the root of my problem?
import mechanize
import cookielib
br = mechanize.Browser()
br.set_handle_robots( False )
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
br.open('https://webmail.server.com')
br.select_form(nr = 0)
br.form['username'] = 'username'
br.form['password'] = 'password'
br.submit()
Use this it works for me

Mechanize, 2-Step Authentication: How to fill out form within form

I've got a script set to log into a website. The challenge is that I'm running the script on EC2 and the website is asking for me to do additional verification by sending me a custom code.
I receive the email immediately but need to be able to update that field on the fly.
This is the script
import urllib2
import urllib2
import cookielib
import urllib
import requests
import mechanize
from bs4 import BeautifulSoup
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_refresh(False)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
# The site we will navigate into, handling it's session
br.open('https://www.website.com/login')
#select the first form
br.select_form(nr=0)
#user credentials
br['user_key'] = 'username#gmail.com'
br['user_password'] = 'somePassw0rd'
# Login
br.submit()
#enter verification code
input_var = raw_input("Enter something: ")
#put verification code in form
br['Verication'] = str(input_var)
#submit form
br.submit()
The challenge for me is that I keep getting an error saying:
AttributeError: mechanize._mechanize.Browser instance has no attribute __setitem__ (perhaps you forgot to .select_form()?)
What can I do to make this run as intended?
after you br.submit() you go straight into
br['Verication'] = str(input_var)
this is incorrect since using br.submit() will make your browser not have a form selected anymore.
after submitting i would try:
for form in br.forms():
print form
to see if there is another form to be selected
read up on the html code on the login site and check to see exactly what happens when you click login. You may have to reselect a form on that same page then assign the verification code to one of the controls

Login Forms for Hotmail Website using Mechanize/Python

I'm learning Mechanize/BeautifulSoup by following the instruction on this site: http://stockrt.github.io/p/handling-html-forms-with-python-mechanize-and-BeautifulSoup/
Instead of writing a login and check mail for Gmail, I want to do the same for hotmail. However, I cannot find the login form by using Mechanize. The result when im trying to do the following is empty:
for f in self.br.forms():
print 'form:', f
Those codes print out nothing. By inspecting the hotmail website (login.live.com) I can see the form name is 'F1' and 2 fields are 'username' and 'passwd' but Mechanize cannot be able to catch those.
Here is the complete code:
import os
import mechanize
import cookielib
from bs4 import BeautifulSoup
import html2text
import agent
class Hotmail:
def __init__(self):
self.br = mechanize.Browser()
cj = cookielib.LWPCookieJar() # Cookie Jar
self.br.set_cookiejar(cj)
# Browser options
self.br.set_handle_equiv(True)
#self.br.set_handle_gzip(True)
self.br.set_handle_redirect(True)
self.br.set_handle_referer(True)
self.br.set_handle_robots(False)
self.br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # Follows refresh 0 but not hangs on refresh > 0
self.br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] # User-Agent
def login(self, user, pswd):
self.br.open('http://login.live.com')
for f in self.br.forms():
print 'form:', f
if __name__ == '__main__':
test = Hotmail()
test.login('asd','asd')
I also tried to manually set the form 'F1' to br.form and fill out the values for it, but it doesn't work.
Any ideas why Mechanize cannot recognize any forms on Hotmail or how to get those forms?
Thank you so much!

Trying to log into PowerSchool website using Mechanize (Python) - failing

I'm trying to log into our PowerSchool server through Python and Mechanize, but I can't seem to successfully do it. A tricky part of this is that the login form only has a single field for inputting both my username and password, separated by a semicolon. Here is the webpage: https://powerschool.laalliance.org/admin/home.html
Can someone tell me if my code is correct?
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_refresh(False)
br.addheaders = [("User-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:26.0) Gecko/20100101 Firefox/26.0")]
br.open('https://powerschool.laalliance.org/admin/')
br.select_form(name='LoginForm')
br.set_all_readonly(False)
#br.find_control('pstoken').readonly = False
#br.form['pstoken'] = '123123asdfasdf123123'
br.form['password'] = 'jdoe;' + pw
br.method = 'POST'
response = br.submit()
print response.read()
Checked the website, and if you do right-click on the form, then 'inspect element' you will see that the name of the form is : "password"
Hence, you should replace your line:
br.select_form(name='LoginForm')
to
br.select_form(name='password')
Does that solve your problem?

Categories

Resources