2

我想使用 MechanicalSoup 从我的路由器中检索一些数据。但是,当我尝试时,我得到“证书验证失败”。如我所见,我有两个选择

  1. 找到禁用 SSL 验证的方法
  2. 告诉 MechanicalSoup 在哪里可以找到 pem 文件(我使用“openssl s_connect ....”创建它)

到目前为止,我的代码如下所示:

import argparse
import mechanicalsoup
from getpass import getpass

parser = argparse.ArgumentParser(description="Get data from router")
parser.add_argument("-u", "--username", help="User", type=str,
                    required=True)
parser.add_argument("-s", "--server", help="server", type=str,
                    required=True)
parser.add_argument("-p", "--port", help="Port", type=str,
                    required=False, default="8443")
parser.add_argument("-v", "--verbose", help="Verbose output. Add " +
                    "additional v to increase level.",
                    action="count", default=0)
args = parser.parse_args()

args.password = getpass("Password:")

browser = mechanicalsoup.StatefulBrowser(
    soup_config={'features': 'lxml'},
    raise_on_404=True,
    user_agent='getdata.py/0.1',
)

browser.set_verbose(args.verbose)

browser.open("https://" + args.server + ":" + args.port)

来自堆栈末尾的完整错误消息:

Traceback (most recent call last):
  File "perfcreate.py", line 33, in <module>
    browser.open("https://" + args.server + ":" + args.port)
  File "/home/andyw/mypy_env/lib/python3.6/site-packages/mechanicalsoup/stateful_browser.py", line 133, in open
    resp = self.get(url, *args, **kwargs)
  File "/home/andyw/mypy_env/lib/python3.6/site-packages/mechanicalsoup/browser.py", line 124, in get
    response = self.session.get(*args, **kwargs)
  File "/home/andyw/mypy_env/lib/python3.6/site-packages/requests/sessions.py", line 546, in get
    return self.request('GET', url, **kwargs)
  File "/home/andyw/mypy_env/lib/python3.6/site-packages/requests/sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/andyw/mypy_env/lib/python3.6/site-packages/requests/sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "/home/andyw/mypy_env/lib/python3.6/site-packages/requests/adapters.py", line 514, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='192.168.1.1', port=8443): Max retries exceeded with url: / (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),))
4

2 回答 2

1

也许你可以使用:browser.open("https://" + args.server + ":" + args.port, verify=False)

于 2019-12-11T23:30:37.217 回答
0

MechanicalSoup 不对 SSL 证书做任何特定的事情,而是browser.open将其参数转发给requests.Session.request的构造函数,其中包括:

verify –(可选)布尔值,在这种情况下,它控制我们是否验证服务器的 TLS 证书,或者是字符串,在这种情况下,它必须是要使用的 CA 包的路径。默认为真。

cert –(可选)如果是字符串,则为 ssl 客户端证书文件 (.pem) 的路径。如果是元组,则 ('cert', 'key') 对。

因此,您可以verify=False按照其他答案的建议使用(不安全),或者从网站下载证书并使用cert="/path/to/certificate.pem.

于 2019-12-13T16:32:09.793 回答