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

Python requests使用代理访问报407错误:Windows正常Linux失败求助

代理407认证报错解决方案

407错误为代理服务器要求身份认证触发,Windows端集成了域内单点登录(NTLM/Kerberos认证)会自动传递身份凭证,Linux默认无对应域认证配置因此报错,可根据企业代理的认证类型选择以下方案修复:


可行解决方案

方案1:直接在代理配置中嵌入身份凭证(最简单,适用于普通账号密码认证场景)

修改代理配置格式,将用户名、密码直接写入代理URL,同时补全HTTPS代理配置、修正原代码的语法错误:

import requests
# 替换为实际的代理用户名、密码,特殊字符需要提前做URL编码
proxies = {
    'http': 'http://你的用户名:你的密码@192.168.10.22:80',
    'https': 'http://你的用户名:你的密码@192.168.10.22:80'
}
URL = 'https://accesscontrol.windows.net/secret-code'
# 修正参数名错误:原代码参数名为header,正确为headers
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
# 修正拼写错误:原代码为request.post,正确为requests.post
resp = requests.post(URL, headers=headers, proxies=proxies)

安全提示:不要硬编码凭证到代码中,建议通过系统环境变量读取凭证值。


方案2:适配企业NTLM代理认证(适用于域内NTLM认证场景,大部分企业内网代理属于该类)

先安装NTLM认证支持库:
pip install requests_ntlm
修改代码适配NTLM认证:

import requests
from requests_ntlm import HttpNtlmAuth

proxies = {
    'http': 'http://192.168.10.22:80',
    'https': 'http://192.168.10.22:80'
}
URL = 'https://accesscontrol.windows.net/secret-code'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
# 填入域账号、密码,用户名格式为 域名\用户名
resp = requests.post(
    URL, 
    headers=headers, 
    proxies=proxies,
    proxy_auth=HttpNtlmAuth('你的域名\\你的用户名', '你的密码')
)

方案3:系统级配置代理(无需修改代码)

在Linux服务器的环境变量中配置带凭证的代理地址,requests会自动读取系统代理配置:

  1. 编辑/etc/profile(全局生效)或当前用户的~/.bashrc(当前用户生效)文件,添加如下内容:
export http_proxy=http://你的用户名:你的密码@192.168.10.22:80
export https_proxy=http://你的用户名:你的密码@192.168.10.22:80
export no_proxy=localhost,127.0.0.1,企业内网域名后缀
  1. 执行source /etc/profile或source ~/.bashrc使配置生效,直接运行原有代码即可。

方案4:适配Kerberos单点登录认证(适用于域内Kerberos认证场景)

  1. 先在Linux服务器配置Kerberos客户端,加入企业域,执行kinit 你的用户名获取身份票据
  2. 安装Kerberos认证支持库:pip install requests-kerberos
  3. 修改代码适配:
import requests
from requests_kerberos import HTTPKerberosAuth, REQUIRED

proxies = {
    'http': 'http://192.168.10.22:80',
    'https': 'http://192.168.10.22:80'
}
URL = 'https://accesscontrol.windows.net/secret-code'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
resp = requests.post(
    URL, 
    headers=headers, 
    proxies=proxies,
    proxy_auth=HTTPKerberosAuth(mutual_authentication=REQUIRED)
)

内容的提问来源于stack exchange,提问作者Rafiq Shaikh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:45:07