使用Invoke-WebRequest通过PowerShell登录网站返回403错误求助
解决PowerShell登录网站返回403禁止访问的问题
问题描述
尝试使用PowerShell登录网站https://xxxx.netstock.co/session/new时,始终返回403错误。执行代码如下:
$LoginUri = "https://xxxx.netstock.co/session/new" $LoginResp = Invoke-WebRequest -Uri $LoginUri -SessionVariable "Session" $LoginBody = @{ authenticity_token = $LoginResponse.InputFields[1].value login = "hereisthelogin" password = "hereisthepassword" submit = "Log in" } $LoginResp = Invoke-WebRequest -Uri $LoginUri -WebSession $Session -Body $LoginBody -Method "POST"
返回错误:Invoke-WebRequest : 远程服务器返回错误: (403) 禁止访问。
可能原因及解决方法
1. 变量名拼写错误
代码中第一次请求的响应变量是$LoginResp,但获取authenticity_token时误用了$LoginResponse,变量名不匹配会导致token为空,服务器验证失败返回403。修正变量名即可:
$LoginUri = "https://xxxx.netstock.co/session/new" $LoginResp = Invoke-WebRequest -Uri $LoginUri -SessionVariable "Session" $LoginBody = @{ authenticity_token = $LoginResp.InputFields[1].value # 修正变量名为$LoginResp login = "hereisthelogin" password = "hereisthepassword" submit = "Log in" } $LoginResp = Invoke-WebRequest -Uri $LoginUri -WebSession $Session -Body $LoginBody -Method "POST"
2. 缺失必要请求头
多数网站会验证User-Agent、Referer等请求头,PowerShell默认的请求标识可能被服务器判定为非合法浏览器请求而拦截。添加模拟浏览器的请求头:
$headers = @{ "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" "Referer" = $LoginUri } # 首次请求携带请求头 $LoginResp = Invoke-WebRequest -Uri $LoginUri -SessionVariable "Session" -Headers $headers # POST请求同样携带 $LoginResp = Invoke-WebRequest -Uri $LoginUri -WebSession $Session -Body $LoginBody -Method "POST" -Headers $headers
3. 真实性令牌定位错误
用InputFields[1]通过索引定位令牌存在风险,页面元素顺序变化会导致获取错误。建议通过name属性精准匹配:
# 替换原令牌获取逻辑 $authenticity_token = $LoginResp.InputFields | Where-Object { $_.name -eq 'authenticity_token' } | Select-Object -ExpandProperty value $LoginBody = @{ authenticity_token = $authenticity_token login = "hereisthelogin" password = "hereisthepassword" submit = "Log in" }
4. 网站反爬机制限制
该网站可能存在更严格的反爬设置,比如需要验证额外Cookie字段、JS生成的动态参数,或需要提前加载前置资源建立合法会话。可以用浏览器F12抓包,对比浏览器登录时的请求参数、Cookie、请求头,确保PowerShell请求与浏览器请求完全一致。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

