【问题标题】:How to make an authenticated web request in Powershell?如何在 Powershell 中发出经过身份验证的 Web 请求?
【发布时间】:2010-10-05 05:54:49
【问题描述】:

在 C# 中,我可能会这样做:

System.Net.WebClient w = new System.Net.WebClient();
w.Credentials = new System.Net.NetworkCredential(username, auth, domain);
string webpage = w.DownloadString(url);

是否有此版本的 Powershell 版本,或者我应该直接拨打 CLR 吗?

【问题讨论】:

  • 在我的企业中,有些人喜欢用 IE 中的“有用”偏好来惹恼其他人。不使用IE是否可以发出http请求?

标签: powershell


【解决方案1】:

PowerShell 几乎完全相同。

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)

【讨论】:

  • 这是否突然停止对其他人工作? (401) 未经授权
  • @meffect 下面的评论帮助了我。 $webclient.Credentials = New-Object System.Management.Automation.PSCredential($username, $password)
  • 请注意,如果您只想使用当前的登录凭据(例如,访问内网上经过身份验证的服务器),您可以使用$webclient.UseDefaultCredentials=$true(如Ralph's answer)。
【解决方案2】:

对于那些需要 Powershell 来返回 Http StatusCode 等附加信息的用户,这里有一个示例。其中包括两种最有可能传递凭据的方式。

这是这个 SO 答案的略微修改版本:
How to obtain numeric HTTP status codes in PowerShell

$req = [system.Net.WebRequest]::Create($url)
# method 1 $req.UseDefaultCredentials = $true
# method 2 $req.Credentials = New-Object System.Net.NetworkCredential($username, $pwd, $domain); 
try
{
    $res = $req.GetResponse()
}
catch [System.Net.WebException]
{
    $res = $_.Exception.Response
}

$int = [int]$res.StatusCode
$status = $res.StatusCode
return "$int $status"

【讨论】:

  • 优秀的附加答案,这实际上正是我想要的。
  • 我可能错了,但我必须将new NetworkCredential 替换为$passwd = ConvertTo-SecureString "nowisthetime4U" -AsPlainText -Force;,然后是$request.Credentials = New-Object System.Management.Automation.PSCredential ("pwatson_at_phs_org", $passwd);
  • 新对象 System.Net.NetworkCredential 而不是新的 NetworkCredential
【解决方案3】:

在某些情况下,如果提供正确的凭据,NTLM 身份验证仍然无法工作。

有一种机制会在 WebClient 中取消 NTLM 身份验证,请参阅此处了解更多信息:System.Net.WebClient doesn't work with Windows Authentication

如果您尝试上述答案但仍然无法正常工作,请按照上面的链接添加注册表以将域列入白名单。

在此处发布以节省其他人的时间;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 2019-03-29
    • 2016-05-01
    • 1970-01-01
    相关资源
    最近更新 更多