Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / Windows [игнор отключен] [закрыт для гостей] / Powershell script POST with basic authorization / 3 сообщений из 3, страница 1 из 1
02.09.2014, 02:05
    #38734473
ArtemijT
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Powershell script POST with basic authorization
Все привет!
В powershell-е я совсем не силен, но очень нужно написать скрипт который шлет JSON данные с basic authorization.
Помогите довести его до ума.

Код: powershell
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
param($Credentials = $(Get-Credential), $BaseURI = "http://localhost:2990/jira")
#New-RestItem "$BaseURI/rest/api/2/issue/" -Data @{"JSON" = '{"fields":{"project":{"key":"TES"},"summary":"REST OLOLO","description":"Creating of an issue using project keys and issue type names using the REST API","issuetype":{"name": "Bug"}}}'}
#[CmdletBinding()]
[String]$Url = "$BaseURI/rest/api/2/issue/"
[HashTable]$Data = @{"JSON" = '{"fields":{"project":{"key":"TES"},"summary":"REST OLOLO","description":"Creating of an issue using project keys and issue type names using the REST API","issuetype":{"name": "Bug"}}}'}
[TimeSpan]$Timeout = [System.TimeSpan]::FromMinutes(1)
    
    Add-Type -AssemblyName System.Web
    $formData = [System.Web.HttpUtility]::ParseQueryString("")  
    foreach($key in $Data.Keys){
        $formData.Add($key, $Data[$key])        
    }
    Write-Verbose $formData.ToString()
    $reqBody = [System.Text.Encoding]::Default.GetBytes($formData.ToString())   
    try{
        $req = [System.Net.WebRequest]::Create($Url);
        
        #$b64 = ConvertTo-Base64 "$($Credentials.UserName):$($Credentials.Password)"
        #$creds = "Basic $b64"
        #$req.Headers.Add("Authorization", "Basic $creds")
        #ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
        $credentialCache = New-Object -TypeName System.Net.CredentialCache;
        $urrl = New-Object -TypeName System.Uri $Url;
        $crr = New-Object -TypeName System.Net.NetworkCredential $Credentials.UserName $Credentials.Password;
        $credentialCache.Add($urrl, "Basic", $crr);
        
        $req.Credentials = credentialCache;
        $req.PreAuthenticate = $true
        
        $req.Method = "POST"
        $req.ContentType = "application/x-www-form-urlencoded"      
        $req.Timeout = $Timeout.TotalMilliseconds
        $reqStream = $req.GetRequestStream()        
        $reqStream.Write($reqBody, 0, $reqBody.Length)
        $reqStream.Close()
        $resp = $req.GetResponse()
        Write-Verbose $resp
        Write-Output $resp.StatusCode
    }
    catch [System.Net.WebException]{
        if ($_.Exception -ne $null -and $_.Exception.Response -ne $null) {
            $errorResult = $_.Exception.Response.GetResponseStream()
            $errorText = (New-Object System.IO.StreamReader($errorResult)).ReadToEnd()
            Write-Warning "The remote server response: $errorText"
            Write-Output $_.Exception.Response.StatusCode
        } else {
            throw $_
        }
    }   
function ConvertTo-Base64($string) {
   $bytes  = [System.Text.Encoding]::UTF8.GetBytes($string);
   $encoded = [System.Convert]::ToBase64String($bytes);
 
   return $encoded;
}




Выдает след. ошибку:

Код: powershell
1.
2.
3.
4.
5.
New-Object : A positional parameter cannot be found that accepts argument 'System.Security.SecureString'.
At C:\Users\a_triliser\Desktop\powershell\test.ps1:34 char:26
+         $crr = New-Object <<<<  -TypeName System.Net.NetworkCredential $Credentials.UserName $Credentials.Password;
    + CategoryInfo          : InvalidArgument: (:) [New-Object], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand



Не понимаю что нужно сделать чтоб он заработал. Поможите плиз.
...
Рейтинг: 0 / 0
02.09.2014, 03:01
    #38734481
bazile
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Powershell script POST with basic authorization
ArtemijT, исправь
Код: powershell
1.
$crr = New-Object -TypeName System.Net.NetworkCredential $Credentials.UserName $Credentials.Password;


на
Код: powershell
1.
$crr = New-Object System.Net.NetworkCredential -Args ($Credentials.UserName, $Credentials.Password)


И дальше у тебя опечатка в строке $req.Credentials = credentialCache не хватает $ перед credentialCache.
...
Рейтинг: 0 / 0
03.09.2014, 12:59
    #38736089
ArtemijT
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Powershell script POST with basic authorization
Спасибо! Помогло.
В итоге, правда, все переделал.Может кому понадобится, рабочий вариант выглядит так:

Код: powershell
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
[String] $target = "http://myhost:2990/jira/rest/api/2/issue/";
[String] $username = "admin"
[String] $password = "admin"
[String] $projectKey = "TP";
[String] $issueType = "Task";
[String] $summary = "New task1";
[String] $description = "REST API new task1"
[String] $priority = "2"

[String] $body = '{"fields":{"project":{"key":"'+$projectKey+'"},"issuetype":{"name": "'+$issueType+'"},"summary":"'+$summary+'","description":"'+$description+'", "priority":{"id":"'+$priority+'"}}}';

function ConvertTo-Base64($string) {
$bytes = [System.Text.Encoding]::UTF8.GetBytes($string);
$encoded = [System.Convert]::ToBase64String($bytes);
return $encoded;
}

try {

$b64 = ConvertTo-Base64($username + ":" + $password);
$auth = "Basic " + $b64;

$webRequest = [System.Net.WebRequest]::Create($target)
$webRequest.ContentType = "application/json"
$BodyStr = [System.Text.Encoding]::UTF8.GetBytes($body)
$webrequest.ContentLength = $BodyStr.Length
$webRequest.ServicePoint.Expect100Continue = $false
$webRequest.Headers.Add("Authorization", $auth);
$webRequest.PreAuthenticate = $true
$webRequest.Method = "POST"
$requestStream = $webRequest.GetRequestStream()
$requestStream.Write($BodyStr, 0, $BodyStr.length)
$requestStream.Close()
[System.Net.WebResponse] $resp = $webRequest.GetResponse()

$rs = $resp.GetResponseStream()
[System.IO.StreamReader] $sr = New-Object System.IO.StreamReader -argumentList $rs
[string] $results = $sr.ReadToEnd()
Write-Output $results

}

catch [System.Net.WebException]{
        if ($_.Exception -ne $null -and $_.Exception.Response -ne $null) {
            $errorResult = $_.Exception.Response.GetResponseStream()
            $errorText = (New-Object System.IO.StreamReader($errorResult)).ReadToEnd()
            Write-Warning "The remote server response: $errorText"
            Write-Output $_.Exception.Response.StatusCode
        } else {
            throw $_
        }
    }   
...
Рейтинг: 0 / 0
Форумы / Windows [игнор отключен] [закрыт для гостей] / Powershell script POST with basic authorization / 3 сообщений из 3, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]