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

Ubuntu服务器运行Python请求代码出现403 Forbidden错误,Windows本地运行正常的排查求助

Ubuntu服务器运行Python请求代码出现403 Forbidden错误,Windows本地运行正常的排查求助

我现在遇到一个头疼的问题:在Ubuntu服务器上运行一段Python脚本向某个接口发起HTTP请求时,一直返回403 Forbidden错误,但在我的Windows电脑上运行完全相同的脚本却能正常拿到预期响应。

以下是我简化后的脚本代码:

import subprocess
import secrets
import uuid
from datetime import timedelta, datetime, timezone
import jwt
import requests

def generate_jwt_for_request():
    user_id = str(uuid.uuid4())
    secret_key = secrets.token_hex(32)
    issuer = secrets.token_hex(16)
    header = {"alg": "HS256", "typ": "JWT"}
    now = datetime.now(timezone.utc)
    payload = {
        "sub": user_id,
        "iat": now,
        "exp": now + timedelta(hours=1),
        "iss": issuer
    }
    token = jwt.encode(payload, secret_key, algorithm="HS256", headers=header)
    return {
        "jwt_token": token,
        "user_id": user_id,
        "issuer": issuer
    }

def scrape_address(address):
    base_url = "https://example.com/address/"
    url = base_url + address
    request_details = generate_jwt_for_request()
    jwt_token = request_details["jwt_token"]
    curl_command = [
        "curl", "-X", "GET", url,
        "-H", f"Authorization: Bearer {jwt_token}",
        "-H", "Accept: application/json",
        "-H", "User-Agent: PostmanRuntime/7.43.0"
    ]
    result = subprocess.run(curl_command, capture_output=True, text=True)
    return result.stdout

我的观察:

  • 代码使用curl发起请求,已经包含了必要的请求头(比如Authorization、User-Agent)
  • 脚本在Windows机器上运行毫无问题,但在Ubuntu服务器上就返回403 Forbidden错误
  • 我怀疑问题可能和网络配置有关,比如防火墙规则或者服务器端的IP封禁

我已经尝试过的排查步骤:

  • 确认Ubuntu服务器有正常的网络访问能力
  • 用ping命令测试过目标域名是可达的
  • 在请求中添加了额外的请求头(比如Cookie),但问题依旧

我的疑问:

  1. 会不会是Ubuntu和Windows上的curl行为差异导致的问题?
  2. Ubuntu服务器上还有哪些需要配置的设置可能影响请求?
  3. 会不会是API提供商做了IP封禁?如果是,我该怎么验证这一点?

希望各位能给我一些建议或者帮助,非常感谢!

备注:内容来源于stack exchange,提问作者Ali Mirash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 14:24:36