Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use existing authenticated session from browser to perform https request on python

Is it possible to take an existing logged in session (say in Chrome) and pipe that session to a python script to perform an https request?

To be clear on what I want to do, there's a website whose content can only be accessed if you're logged in, however curling the credentials for simple http auth is not viable since it actually has captcha. So what I'm trying to do is, log in on say a browser, and extract that session to a python script, and request the url through that session. Am I making sense?

import requests

url="http://stackoverflow.com/"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36"}
cookie = {
    "domain": ".stackoverflow.com",
    "expirationDate": "1427212131.77312",
    "hostOnly": "false",
    "httpOnly": "true",
    "name": "usr",
    "path": "/",
    "secure": "false",
    "session": "false",
    "storeId": "0",
    "value": "SOMEVALUE",
    "id": "5"
}

t = open("response.txt", "w")


t.write(requests.get(url, headers=headers, cookies=cookie).text.encode("ascii", "ignore"))

So I tried this out, and it doesn't seem to be getting me anywhere. If I look at the response, I see that it's actually the page without any user logged into it. Not sure what else am I missing...

like image 311
Stupid.Fat.Cat Avatar asked Sep 24 '14 14:09

Stupid.Fat.Cat


People also ask

Does Python requests use https?

Requests verifies SSL certificates for HTTPS requests, just like a web browser.


2 Answers

Why don't you parse out the generated CAPTCHA, display the image and manually input the solution? It may be an easier approach to your problem than actually hijacking a session. Plus, it would result in a more portable and stable script (probably).

like image 52
Jonathan Avatar answered Oct 19 '22 11:10

Jonathan


This should be possible if you reuse your browser's cookies and user agent. As far as I can see, any such solution would be browser-specific though: I have come across a script that uses SQLite to extract Chrome cookies and use them to make HTTP requests with the Requests library.

The script's chrome_cookies method returns a dictionary containing cookies. If you use the Requests library, you can pass the dictionary as a keyword argument when making requests:

import requests
import pyCookieCheat

url = 'http://www.example.com'

s = requests.Session()
cookies = pyCookieCheat.chrome_cookies(url)
s.get(url, cookies = cookies)
like image 26
amgaera Avatar answered Oct 19 '22 10:10

amgaera