如何使用python3

时间:2018-03-27 12:36:46

标签: python python-3.x request python-requests urllib

我正在尝试使用python3访问使用HTTPBasicAuth保护的网络资源。我提供正确的凭据仍然显示401未经授权的错误。

我正在使用urllib来执行此操作,因为我因为ssl和代理错误而无法使用请求模块执行此操作。在urllib中它只显示401未经授权的错误,因此我能够访问该网站。

有任何建议如何解决这个问题? (出于安全原因,我无法公开发布凭据,这就是我刚刚使用*的原因)

import urllib.request
import urllib.parse
import ssl
import requests
from requests.auth import HTTPBasicAuth
line =1
try:

    line += 1#2
    myssl = ssl.create_default_context()#Bypass SSL verification when trying to access a secured website
    myssl.check_hostname = False
    myssl.verify_mode = ssl.CERT_NONE#SSL verification disabled
    USERNAME = '******'
    PASSWORD = '******'
    login_data = dict(username=USERNAME, password=PASSWORD)


    headers = {}
    headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
    p = urllib.request.HTTPPasswordMgrWithPriorAuth()
    p.add_password(None,'https://bmh309668.rbeigcn.com:44330/sap/opu/odata/sap/IBAS_PLANT_MAINTENANCE_SRV/CodeGroups/',USERNAME,PASSWORD)
    handler = urllib.request.HTTPBasicAuthHandler(p)
    opener = urllib.request.build_opener(handler)
    urllib.request.install_opener(opener)


    line += 1#3
    data = urllib.parse.urlencode(login_data)
    data = data.encode('utf-8')#while using post we can send a byte format not a string so encode it to utf-8
    line += 1#4
    req = urllib.request.Request('https://bmh309668.rbeigcn.com:44330/sap/opu/odata/sap/IBAS_PLANT_MAINTENANCE_SRV/CodeGroups/',data=data, headers = headers)#request for the web page
    line += 1#5
    response = urllib.request.urlopen(req,context=myssl,data=data)#by using context=myssl we disable SSL verification
    line += 1#6
    #x = urllib.request.urlopen('https://bmh309668.rbeigcn.com:44330/sap/opu/odata/sap/IBAS_PLANT_MAINTENANCE_SRV/CodeGroups/',context=myssl,data=data)
    line += 1#7
    print(response.read())#print the data

except Exception as e:
    print("Exception raised at line number: ",line)
    print(str(e))

在第5行获取例外

2 个答案:

答案 0 :(得分:0)

我可以看到您导入请求但不使用它。 它是这个用例的绝佳库。

您的核心问题似乎是您希望从具有自签名TLS / SSL证书的站点获取数据,该证书也受HTTPBasicAuth保护。

我已经在我自己的服务器上验证了类似的设置,以下代码应该适用于该情况。

import requests

# Your configuration
USERNAME = "***"
PASSWORD = "***"
URI = "https://bmh309668.rbeigcn.com:44330/sap/opu/odata/sap/IBAS_PLANT_MAINTENANCE_SRV/CodeGroups/"
# Do you need to specify the user agent? Does the site run a white/blacklist?
USER_AGENT = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
# WARNING: You should point this to your cert file for the server to actually
# verify the host. Skips verification if set to false
CERT_FILE = False

# Create a Session to contain you basic AUTH, it will also persist your cookies
authed_session = requests.Session()

# Add your credentials
authed_session.auth = (USERNAME, PASSWORD)

# Cert verification, will not verify on false
authed_session.verify = CERT_FILE

authed_session.headers.update({'User-Agent': USER_AGENT})

# Fetch the actual data
fetched_data = authed_session.get(URI)
print(fetched_data.text)

它将CERT_FILE设置为false,但我强烈建议为您使用的主机指定certfile的路径,以便它可以实际验证主机。

答案 1 :(得分:0)

从Hultner的代码中获取帮助,然后禁用urllib3警告。现在它正在发挥作用。

import requests
import urllib3

line = 1 #line number denotes the exact place where the exception is raised
try:
    # Your configuration
    USERNAME = "******"
    PASSWORD = "******"
    URI = "https://bmh309668.rbeigcn.com:44330/sap/opu/odata/sap/IBAS_PLANT_MAINTENANCE_SRV/CodeGroups/"
    # specify the user agent
    USER_AGENT = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
    # verify the host. Skips verification if set to false
    CERT_FILE = False
    #diable the warnings
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    urllib3.disable_warnings(urllib3.exceptions.HTTPError)

    # Create a Session to contain you basic AUTH, it will also persist your cookies
    line += 1#2
    authed_session = requests.Session()

    # Add your credentials
    line += 1#3
    authed_session.auth = (USERNAME, PASSWORD)

    # Cert verification, will not verify on false
    line += 1#4
    authed_session.verify = CERT_FILE

    line += 1#5
    authed_session.headers.update({'User-Agent': USER_AGENT})

    # Fetch the actual data
    line += 1#6
    fetched_data = authed_session.get(URI)
    line += 1#7
    print(fetched_data.text)
except Exception as e:
    print(line)
    print(str(e))