Reputation: 21
I am new to Python. I am trying to convert below bash script command to Python using subprocess. I don't get any output nor do I see any failure when I execute my Python script.
This is the bash command that needs to be ported to Python.
curl -u 'lawn:oldlawn!' -k -s -H 'Content-Type: application/json' -X GET 'https://192.168.135.20:443/api/json/v2/types/dev-objs/1'
My python code:
get_curl():
curl = """curl -u 'lawn:oldlawn!' -k -s -H 'Content-Type: application/json' -X GET 'https://192.168.135.20:443/api/json/v2/types/dev-objs/1'"""
args = curl.split()
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout
print stderr
# End of python code
After I execute get_curl()
, print stdout
and print stderr
does not print anything though dev-objs/1
exists.
When I execute the same command as bash command it works and I see the REST API output.
Can anyone help me what may be going wrong here? Thanks
Upvotes: 0
Views: 602
Reputation: 180401
You could use requests:
headers = {
'Content-Type': 'application/json',
}
import requests
proxies = {
'https': 'https://lawn:[email protected]:443',
}
req = requests.get('https:...', proxies=proxies, verify=False, headers=headers)
I don't think there is a -s flag for requests as no data will be output unless you print what is returned with req.json().
I thought you had a capital U
not a u
so all you really need is to do is to use basic-authentication passing auth = (user, pass)
, set verify=False
as per Brendans answer.
Why your subprocess code did not work was because you have some args quoted like "'lawn:oldlawn!'"
, what you want is:
args = ['curl',
'-u',
'lawn:oldlawn!',
'-k',
'-s',
'-H',
'Content-Type: application/json',
'-X',
'GET',
'https://192.168.135.20:443/api/json/v2/types/dev-objs/1']
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
Upvotes: 3
Reputation: 37509
Using requests
will make your http(s) requests far simpler:
import requests
response = requests.get('https://192.168.135.20:443/api/json/v2/types/dev-objs/1',
verify=False, auth=('lawn', 'oldlawn!'))
print response.json()
Upvotes: 1