Python, 기본 인증을 사용하는 HTTPS GET
파이썬을 사용하여 기본 인증으로 HTTPS GET을 시도하고 있습니다. 나는 파이썬을 처음 접했고 가이드는 다른 라이브러리를 사용하여 일을하는 것 같습니다. (http.client, httplib 및 urllib). 누구든지 그 방법을 보여줄 수 있습니까? 표준 라이브러리에 사용을 어떻게 알릴 수 있습니까?
Python 3에서는 다음이 작동합니다. 표준 라이브러리 의 하위 수준 http.client 를 사용하고 있습니다. 또한 기본 인증에 대한 자세한 내용은 rfc2617의 섹션 2를 확인하십시오 . 이 코드는 인증서가 유효한지 확인하지 않지만 https 연결을 설정합니다. 이를 수행하는 방법에 대해서는 http.client 문서를 참조하십시오 .
from http.client import HTTPSConnection
from base64 import b64encode
#This sets up the https connection
c = HTTPSConnection("www.google.com")
#we need to base 64 encode it
#and then decode it to acsii as python 3 stores it as a byte string
userAndPass = b64encode(b"username:password").decode("ascii")
headers = { 'Authorization' : 'Basic %s' % userAndPass }
#then connect
c.request('GET', '/', headers=headers)
#get the response back
res = c.getresponse()
# at this point you could check the status etc
# this gets the page text
data = res.read()
Python의 힘을 사용하고 최고의 라이브러리 중 하나 인 요청 에 의지하십시오.
import requests
r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
print(r.text)
변수 r (응답 요청)에는 사용할 수있는 더 많은 매개 변수가 있습니다. 가장 좋은 점은 인터랙티브 인터프리터에 들어가서 가지고 놀거나 요청 문서를 읽는 것 입니다.
ubuntu@hostname:/home/ubuntu$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
>>> dir(r)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>> r.content
b'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.text
'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.status_code
200
>>> r.headers
CaseInsensitiveDict({'x-powered-by': 'Express', 'content-length': '77', 'date': 'Fri, 20 May 2016 02:06:18 GMT', 'server': 'nginx/1.6.3', 'connection': 'keep-alive', 'content-type': 'application/json; charset=utf-8'})
업데이트 : OP는 Python 3을 사용 하므로 httplib2 를 사용하여 예제 추가
import httplib2
h = httplib2.Http(".cache")
h.add_credentials('name', 'password') # Basic authentication
resp, content = h.request("https://host/path/to/resource", "POST", body="foobar")
아래는 Python 2.6에서 작동합니다.
pycurl
하루에 천만 건 이상의 요청을 처리하는 프로세스를 위해 프로덕션에서 많이 사용 합니다.
먼저 다음을 가져와야합니다.
import pycurl
import cStringIO
import base64
기본 인증 헤더의 일부는 Base64로 인코딩 된 사용자 이름과 비밀번호로 구성됩니다.
headers = { 'Authorization' : 'Basic %s' % base64.b64encode("username:password") }
HTTP 헤더에서이 줄을 볼 수 있습니다 Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
. 인코딩 된 문자열은 사용자 이름과 암호에 따라 변경됩니다.
이제 HTTP 응답을 작성할 장소와 curl 연결 핸들이 필요합니다.
response = cStringIO.StringIO()
conn = pycurl.Curl()
We can set various curl options. For a complete list of options, see this. The linked documentation is for the libcurl API, but the options does not change for other language bindings.
conn.setopt(pycurl.VERBOSE, 1)
conn.setopt(pycurlHTTPHEADER, ["%s: %s" % t for t in headers.items()])
conn.setopt(pycurl.URL, "https://host/path/to/resource")
conn.setopt(pycurl.POST, 1)
If you do not need to verify certificate. Warning: This is insecure. Similar to running curl -k
or curl --insecure
.
conn.setopt(pycurl.SSL_VERIFYPEER, False)
conn.setopt(pycurl.SSL_VERIFYHOST, False)
Call cStringIO.write
for storing the HTTP response.
conn.setopt(pycurl.WRITEFUNCTION, response.write)
When you're making a POST request.
post_body = "foobar"
conn.setopt(pycurl.POSTFIELDS, post_body)
Make the actual request now.
conn.perform()
Do something based on the HTTP response code.
http_code = conn.getinfo(pycurl.HTTP_CODE)
if http_code is 200:
print response.getvalue()
A correct way to do basic auth in Python3 urllib.request
with certificate validation follows.
Note that certifi
is not mandatory. You can use your OS bundle (likely *nix only) or distribute Mozilla's CA Bundle yourself. Or if the hosts you communicate with are just a few, concatenate CA file yourself from the hosts' CAs, which can reduce the risk of MitM attack caused by another corrupt CA.
#!/usr/bin/env python3
import urllib.request
import ssl
import certifi
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(certifi.where())
httpsHandler = urllib.request.HTTPSHandler(context = context)
manager = urllib.request.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://domain.com/', 'username', 'password')
authHandler = urllib.request.HTTPBasicAuthHandler(manager)
opener = urllib.request.build_opener(httpsHandler, authHandler)
# Used globally for all urllib.request requests.
# If it doesn't fit your design, use opener directly.
urllib.request.install_opener(opener)
response = urllib.request.urlopen('https://domain.com/some/path')
print(response.read())
참고URL : https://stackoverflow.com/questions/6999565/python-https-get-with-basic-authentication
'developer tip' 카테고리의 다른 글
UIViewController가 탐색 스택에서 Popped를 가져 오는지 확인하고 있습니까? (0) | 2020.12.14 |
---|---|
C #을 사용하여 각 단어의 첫 문자 또는 전체 문자열의 첫 문자를 대문자로 바꾸는 방법은 무엇입니까? (0) | 2020.12.14 |
텍스트 편집시 자동 초점 비활성화 (0) | 2020.12.14 |
목록의 요소 합산 (0) | 2020.12.14 |
프로세스 ID를 캡처하고 존재하는 경우 종료하는 쉘 스크립트 (0) | 2020.12.14 |