使用PowerShell获取会话cookie

问题描述 投票:0回答:1

我正在尝试使用PowerShell和InternetExplorer.Application获取会话cookie,但似乎没有任何工作。

没有$ ie.Document.cookie变量。会话cookie不适用于JavaScript(因为它只是http)

# Create an ie com object
$ie = New-Object -ComObject "InternetExplorer.Application" 
$ie.visible = $true; 
$ie.navigate2("https://www.example.com/login");
# Wait for the page to load 
while ($ie.Busy -eq $true) { Start-Sleep -Milliseconds 1000; }
#Add login details 
$ie.Document.getElementById("username").value = "user"; 
$ie.Document.getElementById("password").value = "1234";
$ie.Document.getElementsByName("login_button")[0].Click();
while($ie.Busy -eq $true) { Start-Sleep -Milliseconds 1000; }
$div = $ie.Document.getElementsByTagName('div')[0];
$ie.navigate("javascript: window.location=document.cookie.match(new RegExp('(^| )csrf_token=([^;]+)'))[2]");
while($ie.Busy -eq $true) { Start-Sleep -Milliseconds 1000; }
$csrf = $ie.LocationUrl.Substring(32);
echo $csrf;
#Stop-Process -Name iexplore
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession

$cookie = New-Object System.Net.Cookie     
$cookie.Name = "user_name"
$cookie.Value = "user"
$cookie.Domain = "www.example.com"
$session.Cookies.Add($cookie);

$cookie = New-Object System.Net.Cookie     
$cookie.Name = "user_session_id"
$cookie.Value = "What I need"
$cookie.Domain = "www.example.com"
$session.Cookies.Add($cookie);

Invoke-WebRequest -URI "https://www.example.com/demo/my_file&csrf_token=$csrf" -WebSession $session -OutFile 'finally.zip';
echo 'Done!';

请注意,我发现获取csrf的唯一方法是使用javascript来获取url的值,但是我不能使用user_session_id来执行它,因为它被标记为http_only。

powershell session-cookies
1个回答
0
投票

看看这些选项,将其融入您已有的内容中。

First, get the cookies

$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession

Get-Content .\cookie.txt | 
foreach {
$line = $_ -split '/' | select -First 1

$tokens=$line.Split("`t").TrimEnd()

    $c = @{
        name=$tokens[0]
        value=$tokens[1]
        domain=$tokens[2]
    }

    $cookie = New-Object System.Net.Cookie
    $cookie.Name=$c.name
    $cookie.Value=$c.Value
    $cookie.Domain=$c.domain

    $session.Cookies.Add($cookie)
}

Getting Cookies using PowerShell

以下是在PowerShell中获取网站cookie的两种简单方法。

$url = "https://www.linkedin.com" 
$webrequest = Invoke-WebRequest -Uri $url -SessionVariable websession 
$cookies = $websession.Cookies.GetCookies($url) 


# Here, you can output all of $cookies, or you can go through them one by one. 

foreach ($cookie in $cookies) { 
     # You can get cookie specifics, or just use $cookie 
     # This gets each cookie's name and value 
     Write-Host "$($cookie.name) = $($cookie.value)" 
}
© www.soinside.com 2019 - 2024. All rights reserved.