1

I have been on this site and cannot find a suitable resolution to this problem.

I can connect to my system via Powershell using the following;

$auth = '{"username":' + '"' + $user + '","password":' + '"' + $Pass + '"}'  
$body = $auth
$hdrs = @{}
$hdrs.Add("X-API-KEY", "???")

$r = Invoke-RestMethod -Uri http://$URLSystem/login -Method Post -Body $body -ContentType 'application/json' -Headers $hdrs

I get a response back of 200 and I can get session keys etc...

I have tried a number of things in Python to connect to the same system. I tried this basic approach;

import requests
from requests.auth import HTTPBasicAuth

basic = HTTPBasicAuth('user1','pass1')

r = requests.get("http://URLSystem/login", auth=basic)

print(r.headers)
print(r) 

I get a 405 response code. I have tried changing the get to a POST and get a 415 error response.

I am new to Python and having a little difficulty getting this going. Any help would be greatly appreciated.

nsaint
  • 11
  • 2
  • 1
    Should you be using `requests.post(…)` to match your powershell example? Maybe [this answer](https://stackoverflow.com/a/36634227/2280890) will be useful. – import random Sep 06 '22 at 23:34
  • you also forgot to add `headers` with `X-API-KEY` in request. `API-KEY` can be very important to access page. – furas Sep 06 '22 at 23:46
  • maybe first `print( r.text )` - server may send some extra information which can explain what makes problem. – furas Sep 06 '22 at 23:47
  • 1
    BTW: you can test both version with url `https://httpbin.org/post` and it will send back all your headers, cookies, etc. and you can compare values for both versions - and you may see what is wrong with request in Python code. – furas Sep 06 '22 at 23:49

1 Answers1

0

Thank you for the response.

I will look at the resources you pointed out - this was helpful.

Yes, I thought I should be using request.post(...) but could not get the right format for headers and params to use.

I did find this post @this web site and it worked for me with some slight modification, so I am good for now...

Posting the solution here for anyone else if they have similar issues.

import requests
import json

URL = 'http://your-url'

headers = {
"accept": "application/json", 
"Content-Type": "application/json"
}

params = { 
"username": "yourusername", 
"password": "yourpassword" 
}

resp = requests.post(URL, headers = headers ,data=json.dumps(params))
session = json.loads(resp.text)['SessionToken']

if resp.status_code != 200:
    print('error: ' + str(resp.status_code))
else:
    print('Response Code: ' + str(resp.status_code) + ', Session-Token: ' + str(session))
nsaint
  • 11
  • 2