You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Databricks中访问外部URL遇到SSL错误的解决求助

问题描述

在Databricks环境中执行以下Python代码访问外部URL:

import requests

try:
    # Make an HTTPS GET request to the URL
    response = requests.get("https://www.google.com/")
    
    # Check if the response status code indicates success (2xx)
    if response.status_code // 100 == 2:
        print("Connection successful!")
    else:
        print(f"Failed to connect. Status code: {response.status_code}")
except Exception as e:
    print(f"Failed to connect: {e}")

运行后抛出SSL错误:

Failed to connect: HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLEOFError(8, '[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1007)')))

作为Python新手,已知Java中可通过添加证书至cacerts解决类似问题,不清楚Python/Databricks中的处理方式,寻求解决方案。

解决方案

1. 临时跳过SSL验证(仅用于测试,不推荐生产环境)

如果只是验证网络连通性,可临时关闭证书验证,但这会带来安全风险:

import requests
import urllib3

# 关闭不安全请求警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

try:
    response = requests.get("https://www.google.com/", verify=False)
    if response.status_code // 100 == 2:
        print("Connection successful!")
    else:
        print(f"Failed to connect. Status code: {response.status_code}")
except Exception as e:
    print(f"Failed to connect: {e}")

2. 指定CA证书文件(推荐生产环境)

如果已有目标站点的CA证书,可将证书上传至DBFS,然后在请求中指定证书路径:

  1. 将CA证书(如ca.crt)上传至DBFS,路径示例:dbfs:/certs/ca.crt
  2. 修改代码,在requests.get中添加verify参数,注意DBFS路径需转换为本地可访问的/dbfs/开头路径:
import requests

try:
    # 指定CA证书路径
    response = requests.get("https://www.google.com/", verify="/dbfs/certs/ca.crt")
    if response.status_code // 100 == 2:
        print("Connection successful!")
    else:
        print(f"Failed to connect. Status code: {response.status_code}")
except Exception as e:
    print(f"Failed to connect: {e}")

3. 集群层面配置信任证书(全局生效)

如果需要所有Python任务都信任该证书,可通过Databricks集群配置实现:

  1. 将CA证书上传至DBFS(如dbfs:/certs/ca.crt)
  2. 编辑集群,进入高级选项 -> 环境变量,添加环境变量:
    REQUESTS_CA_BUNDLE=/dbfs/certs/ca.crt
    
  3. 重启集群后,所有requests请求会自动使用该证书进行验证,无需修改代码。

补充说明

  • Databricks集群的节点可直接访问/dbfs/开头的路径,对应DBFS中的文件
  • 若证书是JKS格式(Java常用),需先转换为PEM格式才能被Python的requests库识别,可使用keytool或openssl工具转换

内容的提问来源于stack exchange,提问作者Prashant Aghara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 15:27:50