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

@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