simple Query phpipam in powershell - python-3.x

I have a code in python and I would like to do the same in powershell.
This code works to make inquiries in the phpipam api.
#!/usr/bin/env python3.6
import requests
import json
import pandas as pd
server = "http://phpipam.local"
appid = "nuevoid"
username = "admin"
password = "password"
baseurl = server + "/api/" + appid
res = requests.post(baseurl + '/user/', auth=(username, password))
token = json.loads(res.content)['data']['token']
res = requests.get(baseurl + '/addresses/search/192.168.10.10', headers={'token': token})
dip = json.loads(res.content)['data']
df = pd.DataFrame(dip)
print(df[['ip','hostname','custom_dns_name','editDate','is_gateway','owner']])
Invoke-WebRequest
$url = "http://phpipam.local/api/nuevoid/addresses/search/192.168.10.10"
$bearer_token = "asdasdasdZZZZZZZZZZZZZZ"
$headers = #{token = "$bearer_token"}
#$response = Invoke-RestMethod -Uri $url -Headers $headers -UseBasicParsing
$headers=#{ Authorization = "Bearer $bearer_token";"Content-Type"="text/xml" }
Invoke-WebRequest -Headers $headers -Uri $url -Method GET
I don't know how I could do the same type of authorization in powershell. In Python Works OK!
The error in the query is: {"code":401,"success":false,"message":"Unauthorized","time":0.002} –

Related

Unable to retrieve token from Azure API

I am trying to get a token to be able to retrieve Groups information in Azure AD
This is my powershell script against the API:
Invoke-RestMethod -Method POST -Uri 'https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token?api-version=1.6'
-Header #{'Content-type' = 'application/x-www-form-urlencoded'}
-Body '{grant_type=client_credentials&client_id=<clientID>&scope=https://graph.microsoft.com/.default&client_secret=<clientSecret> }'
I keep getting this error: {"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID:
Your body ia malformed, just do:
$body = #{
Grant_Type = 'client_credentials'
Scope = 'https://graph.microsoft.com/.default'
Client_Id = $ClientID
Client_Secret = $Secret
}
$con = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token" -Method 'Post' -Body $body
$token = $con.access_token

create branch based on another branch api az devops

I want to know how to create several repos with their respective branches, but the branches created do not respect the hierarchy example:
DEV based on PRD(master)
FTR based on DEV
DEV-based REL
EXCUSE THE ENGLISH, USE A TRANSLATOR
$repository = "ECOMP_CORE_LG"
$newBranch = "REL/ECOMP_CORE_PDF/ECOMP_CORE_PDF-4080-re"
$baseBranch = "DEV/ECOMP_CORE_PDF/ECOMP_CORE_PDF-dev"
$organization = "XXXXXXX"
$project = "XXXXXX"
$pat = "TOKEN"
$base64AuthInfo =
[System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$pat"))
$headers = #{ Authorization = "Basic $base64AuthInfo" }
# Get ID of the base branch
$url = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/refs?
filter=heads/$baseBranch&api-version=5.1"
$baseBranchResponse = Invoke-RestMethod -Uri $url -ContentType "application/json" -headers
$headers -Method GET
# Create a new branch
$url = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/refs?
api-version=5.1"
$body = ConvertTo-Json #(
#{
name = "refs/heads/$newBranch"
newObjectId = $baseBranchResponse.value.objectId
oldObjectId = "0000000000000000000000000000000000000000"
})
$response = Invoke-RestMethod -Uri $url -ContentType "application/json" -Body $body -headers
$headers -Method POST

Invoke-Restmethod powershell in Azure Devops - strange powershell errors

I am using this invoke-restmethod so I can get a token so I can do some sql work. the variables come from Azure Key Vault. I have tried to write the variables as
$($SPNAppid)
$SPNAppid
${$SPNAppid} etc
Here is the code :
$request = Invoke-RestMethod -Method POST -Uri
"https://login.microsoftonline.com/${$TenantId}"/oauth2/token" -Body
#{ resource="https://database.windows.net/";
grant_type="client_credentials"; client_id=${$SPNAppid};
client_secret=${$SPNValue} } -ContentType
"application/x-www-form-urlencoded"
Getting this error below. What is the best way to do this - whatever i do i am getting the errors below.
Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to
delimit the name.
At C:\agent01_2\_work\_temp\b3f54d23-b7b6-4cc3-96ec-8b4b534be571.ps1:20 char:319
+ ... ervicePrincipalKey } -ContentType "application/x-www-form-urlencoded"
+ ~
The string is missing the terminator: ".
The code you posted, has an extra " and given the ambiguity of the long line I would suggest to use splatting like this :
$header = #{
"Content-type" = "application/x-www-form-urlencoded"
"Authorization" = "Bearer $token"
}
$body = #{
resource = "https://database.windows.net/"
grant_type = "client_credentials"
client_id = $SPNAppid
client_secret = $SPNValue
}
$params = #{
Method = 'Post'
Uri = "https://login.microsoftonline.com/$($TenantId)/oauth2/token"
Body = $body
ContentType = $header
}
$request = Invoke-RestMethod #params
I do not think the API call would work this way, usually clientId etc. are part of the URL, you can read more about it here - https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow

Azure REST API list key vault secrets has maxresults limited to 25

I'm trying to get a list of all the secrets in each of my key vaults and I'm using Microsofts documentation at this URL.
https://learn.microsoft.com/en-us/rest/api/keyvault/getsecrets/getsecrets#secretlistresult
It states that if you do not set maxresults it will default to 25. It does however throw this error in my powershell script when i try to set it higher than 25.
{"error":{"code":"BadParameter","message":"invalid maxresults"}}
From the documentation the endpoint does not appear to contain any pagination or way to get more than 25 random secrets. This seems to make the endpoint pretty useless as there are no ways to filter the listings.
The command I'm using to get the list is this.
$uri = ""https://$($Vault).vault.azure.net/secrets?api-version=7.1&maxresults=26""
Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
As Gaurav said in the comment, you need to use nextLink to get the result of next page.
There is my test code with do-until:
$LoginUrl = "https://login.microsoft.com"
$RresourceUrl = "https://vault.azure.net/.default"
$ClientID = ""
$ClientSecret = ""
$TenantName = ""
# Compose REST request.
$Body = #{ grant_type = "client_credentials"; scope = $RresourceUrl; client_id = $ClientID; client_secret = $ClientSecret }
$OAuth = Invoke-RestMethod -Method Post -Uri $LoginUrl/$TenantName/oauth2/v2.0/token -Body $Body
# Check if authentication was successfull.
if ($OAuth.access_token) {
# Format headers.
$HeaderParams = #{
'Content-Type' = "application\json"
'Authorization' = "Bearer $($OAuth.access_token)"
}
# Create an empty array to store the result.
$QueryResults = #()
$Uri = "https://<your-key-vault-name>.vault.azure.net/secrets?api-version=7.1"
# Invoke REST method and fetch data until there are no pages left.
do {
$Results = Invoke-RestMethod -Headers $HeaderParams -Uri $Uri -UseBasicParsing -Method "GET" -ContentType "application/json"
$Results.nextLink
if ($Results.value) {
$QueryResults += $Results.value
}
else {
$QueryResults += $Results
}
$Uri = $Results.nextLink
} until (!($Uri))
# Return the result.
$QueryResults
}
else {
Write-Error "No Access Token"
}

Azure Batch REST API, authorization issue

I've tried to authenticate to Azure Batch using REST API, to do so I wrote following PowerShell code
$Key = 'key'
$region = "region"
$sharedKey = [System.Convert]::FromBase64String($Key)
$date = [System.DateTime]::UtcNow.ToString("R")
$stringToSign = "GET`n`n`n`n`n`n`n`n`n`n`n`nocp-date:$date`n /$batchAccount/jobs`napi-version:2019-08-01.10.0`ntimeout:20"
[byte[]]$dataBytes = ([System.Text.Encoding]::UTF8).GetBytes($stringToSign)
$hmacsha256 = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha256.Key = [Convert]::FromBase64String($key)
$sig = [Convert]::ToBase64String($hmacsha256.ComputeHash($dataBytes))
$authhdr = "SharedKey $BatchAccount`:$sig"
$headers = #{
"ocp-date" = $date;
"Authorization" = "$authhdr";
}
Invoke-restmethod -Headers $headers -Uri 'https://$BatchAccount.$region.batch.azure.com/jobs?api-version=2019-08-01.10.0'
please note that I know that I can
use OAuth2 as alternative authentication mechanism
use Az.Batch powershell modules
I just wanted to do this using REST and SharedKey scheme as described here
https://learn.microsoft.com/en-us/rest/api/batchservice/authenticate-requests-to-the-azure-batch-service
for this API
https://learn.microsoft.com/en-us/rest/api/batchservice/job/list
But for some reason it doesn't work
I get this error but everything seems to be folowing the docs
"message":{
"lang":"en-US",
"value":"Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.\nRequestId:eb5134f2-2821-4244-ac5b-066bf19bec10\nTime:2019-11-24T21:08:20.3223384Z"
},
"values":[
{
"key":"AuthenticationErrorDetail",
"value":"The MAC signature found in the HTTP request 'signature-goes-here' is not the same as any computed signature. Server used following string to sign: 'GET\n\n\n\n\napplication/json; odata=minimalmetadata; charset=utf-8\n\n\n\n\n\n\nocp-date:Sun, 24 Nov 2019 21:08:20 GMT\n/name-goes-here/jobs\napi-version:2019-08-01.10.0'."
}
]
There is something wrong with $stringToSign . Try this :
$Key = "your key"
$region = "your region"
$BatchAccount = "your account name"
$BatchAccountURL = "Https://$BatchAccount.$region.batch.azure.com"
$sharedKey = [System.Convert]::FromBase64String($Key)
$date = [System.DateTime]::UtcNow.ToString("R")
$stringToSign = "GET`n`n`n`n`n`n`n`n`n`n`n`nocp-date:$date`n/$BatchAccount/jobs`napi-version:2019-08-01.10.0"
[byte[]]$dataBytes = ([System.Text.Encoding]::UTF8).GetBytes($stringToSign)
$hmacsha256 = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha256.Key = [Convert]::FromBase64String($key)
$sig = [Convert]::ToBase64String($hmacsha256.ComputeHash($dataBytes))
$authhdr = "SharedKey $BatchAccount`:$sig"
$headers = #{
"ocp-date" = $date;
"Authorization" = "$authhdr";
}
Invoke-restmethod -Headers $headers -Uri "$BatchAccountURL/jobs?api-version=2019-08-01.10.0"
Result :

Resources