Powershell websession

j8yoct9x  于 2023-10-18  发布在  Shell
关注(0)|答案(2)|浏览(123)

我的问题是,我正在使用invoke web-request登录一个网站。我可以成功地登录到网站。我的问题是,当我去一个网址,它认为我没有登录。我使用相同的会话变量登录并转到特定页面。
这是显示我登录的截图,但我不能去网站的一部分上传一些文件。
https://drive.google.com/open?id=18tr4aBxTkroQKl1E1SOAEyeJ70LH2LC0

$Global:organization = Read-Host "`tEnter the organization"
$username = Read-Host "`tEnter the username"
$password = Read-Host "`tEnter the password"

$form.fields["organization"] = $organization
$form.fields["Username"] = $username
$form.fields["Password"] = $password

$Global:loginResponse = Invoke-WebRequest -uri ("https://dealer.md-bmc.rpdss.com/" + $form.Action) -WebSession $login -Method post -Body $form.Fields

if ($loginResponse.ParsedHtml.title -eq "RAPID Dealer Reporting Site") {
    Write-Host "`tLog in failed, please try again! `n" -ForegroundColor Red
}

else {
$info = $loginResponse.AllElements | where {$_.tagName -contains "span"}
$account = ($info.innerhtml | Select-Object -First 3).ToUpper()
Write-Host "`tLogged in as" $account "`n" -ForegroundColor Green
$upload = $loginResponse.AllElements.InnerHtml | Where-Object {$_ -match 'url="(administration/uploadprofileselector.aspx\?.*?)"'} |ForEach-Object {$matches[1]} | Select-Object -First 1

$uid = ($upload -replace '\D').Substring(0,4)
$oid = ($upload -replace '\D').Substring(4,6)

#this is where it "forgets" that it's already logged in.

$fileUploadurl = "https://dealer.md-bmc.rpdss.com/bwident/pawnshop/administration/uploadprofileselector.aspx?l=English&uid=$uid&oid=$oid"
$fileUploadPage = Invoke-WebRequest -Uri $fileUploadurl -WebSession $login

#this should be showing me a selection menu, but it's asking me to login again.  Please see screenshot.
$fileUploadPage.ParsedHtml.body.innerText
}
mlnl4t2r

mlnl4t2r1#

在第一次调用Invoke-WebRequest时,您使用-SessionVariable参数设置一个会话变量:

$Global:loginResponse = Invoke-WebRequest -uri ("https://dealer.md-bmc.rpdss.com/" + $form.Action) -SessionVariable login -Method post -Body $form.Fields

(as你可以看到,变量名没有前缀$。您甚至可以像'login'一样引用它,以使其更清楚,它只是一个变量(字符串)的名称)
在随后对Invoke-WebRequest的调用中,您将使用带有-WebSession参数的会话变量:

$fileUploadPage = Invoke-WebRequest -Uri $fileUploadurl -WebSession $login

正如我之前的评论中所说,你还必须修复代码中的($upload -replace '\D'),因为你现在试图用($upload -replace '\D')替换所有不是数字的字符。???

xzv2uavs

xzv2uavs2#

对我来说,Powershell版本5总是删除我的Cookie,如果我添加它的任何其他方式比这。解决我的问题的方法是:从登录请求中获取cookie:

$webrequest = Invoke-WebRequest -Uri $loginUrl -SessionVariable 'session' -Headers $headers -Method Post -Body $loginBody
$cookies = $session.Cookies.GetCookies($loginUrl)

然后手动构建一个新的会话与cookie从登录,添加任何所需的头等。

$url = [System.Uri]"https://someURl.com"
$Cookie_final = New-Object System.Net.Cookie($cookies[0].Name, $cookies[0].Value, '/')
$newSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$newSession.Cookies.Add($url, $Cookie_final)
$newSession.Headers.Add("Accept", "*/*")

最后发送具有所构造的会话的实际请求:

$response = Invoke-WebRequest -Uri $url -Method Post -Body ($body | ConvertTo-Json) -WebSession $newSession

相关问题