0

A friend is trying to run a script to check which notebooks are using the most memory, but their server is password protected. I'm trying to figure out how to configure authentication using urllib2 since I don't believe there is a username, only a password.

Community
  • 1
  • 1
aiguofer
  • 1,393
  • 14
  • 29

4 Answers4

2

The @aiguofer answer did not work for me because jupyter now uses '_xsrf' in cookie. The follwoing woked for me:

s = requests.Session()
url='http://127.0.0.1:8888/login/'
resp=s.get(url)
xsrf_cookie = resp.cookies['_xsrf']

params={'_xsrf':xsrf_cookie,'password': password}
s.post(url, data=params)

After that s can be used to call the apis.

Hassan
  • 408
  • 5
  • 12
1

After digging into the notebook code and through some trial and error, I figured out how to do this (and I switched to using requests).

I can't guarantee that this is the best way to do it, but it certainly worked for me. I actually set my vars elsewhere in the code but included here for completeness

import requests

hostname = '127.0.0.1'
port = '8888'
password = 'mypassword'

base_url = 'http://{0}:{1}/'.format(hostname, port)
h = {}
if password:
    r = requests.post(base_url + 'login', params={
        'password': password
    })
    h = r.request.headers
sessions = requests.get(base_url + 'api/sessions', headers=h).json()

I believe this works because when you hit the /login endpoint, it redirects you with the right headers set. I guess requests keeps the headers of the redirect, so we can reuse those for the other call. It might be better to extract only the cookies and use those, but this works for now :)

aiguofer
  • 1,393
  • 14
  • 29
1

It seems there are some changes with new version. url '/login' does not work for me, I need to add next parameters

url='http://localhost:8050/login?next=%2F'

For the login request. The rest just like Hassan answer

hunzter
  • 499
  • 4
  • 10
0

i found when use jupyter put api upload file response 403,

need add "X-XSRFToken" header can solve it..

data= json.dumps({
            "name": "test.jpg",
            "path": "path",
            "type":"file",
            "format": "base64",
            "content": "base64 data"
        })

headers["X-XSRFToken"] = xsrf_cookie
s.put(url, data=data, headers=headers)
蔡東東
  • 1
  • 1