Skip to content

Instantly share code, notes, and snippets.

@KyleJamesWalker
Last active June 7, 2017 13:49
Show Gist options
  • Save KyleJamesWalker/f7799fdd5122f4567974 to your computer and use it in GitHub Desktop.
Save KyleJamesWalker/f7799fdd5122f4567974 to your computer and use it in GitHub Desktop.
Login to Google (browser style)
# encoding: utf-8
from __future__ import unicode_literals
import os
import requests
import sys
def get_google_auth_session(username, password):
session = requests.Session()
google_accounts_url = 'http://accounts.google.com'
authentication_url = 'https://accounts.google.com/ServiceLoginAuth'
r = session.get(google_accounts_url)
galx = r.cookies['GALX']
session.headers['User-Agent'] = \
'Lynx/2.8.8dev.3 libwww-FM/2.14 SSL-MM/1.4.1'
payload = {'GALX': galx,
'continue': 'https://www.google.com/?gws_rd=ssl',
'hl': 'en',
'_utf8': '☃',
# This is normally in the request.
# bgresponse: this is a js function on post gaia_onLoginSubmit()
'bgresponse', 'js_disabled',
'pstMsg': 1,
'dnConn': '',
'checkConnection': 'youtube:206:1',
'checkedDomains': 'youtube',
'Email': username,
'Passwd': password,
'PersistentCookie': 'yes',
'signIn': 'Sign in'}
r = session.post(authentication_url, data=payload)
if r.url != authentication_url:
print "Logged in"
else:
print "login failed"
sys.exit(1)
return session
if __name__ == '__main__':
name = 'valid-user@valid-domain.com'
pswd = 'user password plain text'
g_session = get_google_auth_session(name, pswd)
# Example Google URL that requires login.
dl_file = 'https://sandbox.google.com/storage/example_path/file.zip'
save_file = dl_file.rsplit('/', 1)[-1]
if not os.path.isfile(save_file):
r = g_session.get(dl_file, stream=True)
if r.status_code != 200:
print "Error: Downloading: {}".format(save_file)
else:
with open(save_file, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
print "Success: {} downloaded".format(save_file)
else:
print "Skipped: {} already exits".format(save_file)
@KyleJamesWalker
Copy link
Author

Note: Is may not work perfectly, it fails until I login once on the local machine. When I'm running on a server, lynx works just fine. I think there's something on google's end that might be monitoring the bgresponse field, or maybe I need to add a slight delay for the post. I'll try and get around it once I'm blocked again, since once it's working it works great for quite a while.

@evyatar54
Copy link

Hi, how would you deal with two steps verification ?

@KyleJamesWalker
Copy link
Author

@evyatar54 just saw your comment I don't have the code for it right now but I've used pyotp library for getting the two step key to enter. Then simply catch the response on the first post, and post the two step reply.

https://github.com/pyotp/pyotp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment