简体   繁体   中英

How would you implement this curl command in python Requests or urllib2 or even pycurl?

How would you implement this curl command in python Requests or urllib2 or even pycurl? I've looked at tons of examples on stackoverflow and elsewhere that come close to what I'm looking for, but none shows an example that uses both username/password AND token to authenticate (two-factor authentication). I'm trying to login to a site using two-factor authentication, then using cookies request json data.
So I have a login form that requires posting of "urserId", "password" and "token" (I believe the site is using Google Authenticator token). Here is the working curl commands that do what I need, I'd like to translate what these two command do to python.

curl -X POST  -H "Accept: Application/json" -H "Content-Type: application/json" http://example.com/rest/auth/login -d '{"userId":"myuserid", "password":"mypa$$word", "token":"321"}'

curl http://example.com/rest/search?q=e43f6f3bd6a0f0c0415accfh285f6a00b55552666b7s --cookie 'connect.sid=s%3BJAUAVY68925VclAlLZCV.Gy902343-x%20343seMBMsQodfdo-35'

I tried many different combinations including the following which uses requests:

payload = {"userId":"myuserid", "password":"mypa$$word", "token":"321"}
headers={'Accept': 'Application/json','Content-Type': 'application/json'}

with requests.session() as c:
    c.post('http://example.com/rest/auth/login', headers=headers, data=payload )
    cookies=c.cookies.get_dict()
    c.get('http://example.com/rest/global/config', cookies=cookies)

Unfortunately, it results in a Response [400], which tells me I'm not using the credentials correctly.

From requests docs :

There are many times that you want to send data that is not form-encoded. If you pass in a string instead of a dict , that data will be posted directly.

ie what you were posting was not application/json , but (I assume) application/x-www-form-urlencoded , and your request headers are lying :)

Try with data=json.dumps(payload) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM