如何在aiogram3的AiohttpSession中禁用SSL验证以解决企业代理下的SSL校验错误?
如何在aiogram3的AiohttpSession中禁用SSL验证以解决企业代理下的SSL校验错误?
你好,我正在用Python 3.12 + aiogram 3 + asyncio写一个小机器人,打算部署在公司的服务器上。公司的安全政策要求必须通过企业代理才能访问外网,所以我引入了aiohttp来配置代理。但现在遇到了SSL验证错误,翻了十几页谷歌搜索结果、试过AI工具和官方文档,都没找到正确的禁用SSL验证的方法,希望能得到帮助。
我的代码如下:
import aiohttp import asyncio import logging from aiogram import Bot, Dispatcher, types from aiogram.filters.command import Command from aiohttp import BasicAuth from aiogram.client.session.aiohttp import AiohttpSession auth = BasicAuth(login='Login', password='Pass') session = AiohttpSession(proxy=('http://proxy.corp.company.ru:8080', auth)) logging.basicConfig(level=logging.INFO) bot = Bot(token="token", session=session) dp = Dispatcher() @dp.message(Command("start")) async def cmd_start(message: types.Message): await message.answer("Hello!") async def main(): await dp.start_polling(bot) if __name__ == "__main__": asyncio.run(main())
运行后出现了SSL验证错误(核心报错为SSL: CERTIFICATE_VERIFY_FAILED相关的证书校验失败)。
我已经尝试过这些方法但都没解决:
- 使用
TCPConnector(ssl=False)但没找对正确的配置位置 - 尝试通过bat文件启用/禁用代理
- 创建并配置ssl_context,但不知道怎么在
AiohttpSession中使用
解决方案
要在aiogram 3的AiohttpSession中禁用SSL验证,你需要将配置好的TCPConnector实例传递给AiohttpSession的connector参数,具体步骤如下:
- 导入TCPConnector
在代码顶部的导入部分添加:
from aiohttp import TCPConnector
- 创建禁用SSL验证的连接器
# 禁用SSL证书验证 connector = TCPConnector(ssl=False)
- 将连接器传入AiohttpSession
修改session的初始化代码,新增connector参数:
session = AiohttpSession( proxy=('http://proxy.corp.company.ru:8080', auth), connector=connector )
修改后的完整代码如下:
import aiohttp import asyncio import logging from aiogram import Bot, Dispatcher, types from aiogram.filters.command import Command from aiohttp import BasicAuth, TCPConnector from aiogram.client.session.aiohttp import AiohttpSession auth = BasicAuth(login='Login', password='Pass') # 配置禁用SSL验证的连接器 connector = TCPConnector(ssl=False) session = AiohttpSession( proxy=('http://proxy.corp.company.ru:8080', auth), connector=connector ) logging.basicConfig(level=logging.INFO) bot = Bot(token="token", session=session) dp = Dispatcher() @dp.message(Command("start")) async def cmd_start(message: types.Message): await message.answer("Hello!") async def main(): await dp.start_polling(bot) if __name__ == "__main__": asyncio.run(main())
说明
aiogram 3的AiohttpSession底层基于aiohttp实现,它的构造函数支持接收connector参数,通过这个参数我们可以传递自定义的aiohttp连接器配置。将ssl=False传入TCPConnector后,aiohttp在发起请求时会跳过SSL证书的校验,从而解决你遇到的CERTIFICATE_VERIFY_FAILED错误。
备注:内容来源于stack exchange,提问作者Александр Бражников




