Issue with parsing the powershell variable into JSON array - json

I'm using the following code to change a Pre-shared key for MEraki, however, at the moment I'm only able to do it statically.
I'd like to automate the code so that the PSK is an actual variable.
I've tried using the " or ' however in either scenario i'm unable to recall the variable into the array, and my end goal is to automate this script so that I can just run it and poof, off it goes.
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls11
function Get-RandomCharacters($length, $characters) {
$random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
$private:ofs=""
return [String]$characters[$random]
}
function Scramble-String([string]$inputString){
$characterArray = $inputString.ToCharArray()
$scrambledStringArray = $characterArray | Get-Random -Count $characterArray.Length
$outputString = -join $scrambledStringArray
return $outputString
}
$password = Get-RandomCharacters -length 5 -characters 'abcdefghiklmnoprstuvwxyz'
$password += Get-RandomCharacters -length 1 -characters 'ABCDEFGHKLMNOPRSTUVWXYZ'
$password += Get-RandomCharacters -length 1 -characters '1234567890'
$password = Scramble-String $password
$newDailyPassword = $password
$newDailyPassword
#Meraki API KEY
$api_key = "API_KEY"
#Meraki Network URL
$network_id = "NETWORK_ID"
#Base API URL
$api = #{
"endpoint" = 'https://api.meraki.com/api/v0'
}
#API URL for SSID PSK Change XXX
$api_put = #{
"endpoint" = 'https://nXXX.meraki.com/api/v0'
}
$header_org = #{
"X-Cisco-Meraki-API-Key" = $api_key
"Content-Type" = 'application/json'
}
# PSK = New password
$data = #{
"psk" = $newDailyPassword **#----> I'd like this to be the new daily password variable. Is there a way to do this?**
}
#Convert data to Json format
$jbody = ConvertTo-Json -InputObject $data
#URL Network_ID and SSID number
$api.ssid = "/networks/$network_id/ssids/2"
#Combine base api_put URL and $api.ssid
$Merakiuri = $api_put.endpoint + $api.ssid
Invoke-RestMethod -Method Put -Uri $Merakiuri -Headers $header_org -Body $jbody -Verbose
EDIT1: I've managed to resolve this, by applying the concatination of the variable string, as I was parsing unexpected query via JSON (single string).
I've done the below.
$JsonJoiner = "'"
$passwordx = -join($JsonJoiner,$password, $JSonJoiner)
$newDailyPassword = $passwordx
now, whenever I parse the
$newDailyPassword
the correct value is parsed, and i'm able to generate the PW.

Related

Invoke-WebRequest : Unauthorized - The request requires user authentication

I am hitting this url
https://webadmin.td90.centile-dev.com/restletrouter/v1/service/Login
Then i am getting the session and passing into the url below
https://myistra.td90.centile-dev.com/restleroute/v1/3rdParty/AdmtiveDomain.
Problem
Output
Invoke-WebRequest : Unauthorized
The request requires user authentication
You can get technical details here.
Please continue your visit at our home page.
At C:\Users\administrator\Documents\CDR.ps1:20 char:213
+ ... 'Session' | Invoke-WebRequest -Uri ("https://myistra.td90.centile-
dev ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation:
(System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
thirdParty_SESSIONID=969514241160310577; _ac958=http://10.20.100.190:8078
Here is my code
$user = "SuperGabriel"
$pass = "SuperGabriel#2019"
$pair = "$($user):$($pass)"
$encodedCreds =
$basicAuthValue = "Basic $encodedCreds"
$PartOneHeaders = #{
"Authorization" = $basicAuthValue
"X-Application" = "3rdParty"
}
#test
$Headers =#{
"X-Application" = "3rdParty"
"Cookie"= "thirdParty_SESSIONID=7353595784495763113;"
}
$PartOneWebRequest = Invoke-WebRequest -Uri https://webadmin.td90.centile-
dev.com/restletrouter/v1/service/Login -Headers $PartOneHeaders -
ContentType "application/json" -Method POST -SessionVariable 'Session' |
Invoke-WebRequest -Uri ("https://myistra.td90.centile-
dev.com/restleroute/v1/3rdParty/AdmtiveDomain" ) -Headers $Headers -
Method Get
I have echoed everything out to make sure i am getting the right information and passing it into the right places.
I have tested the call in postman and it works.
Expected results
[
{
"restUri": "v1/3rdParty/AdmtiveDomain/0.",
"alias": "TopLevelAdmtiveDomain",
"rootModel": "AdmtiveDomain",
"domainName": "Top-Level",
"admtiveDomainID": "0."
},
{
"restUri": "v1/3rdParty/AdmtiveDomain/0.106.",
"alias": "AdmtiveDomainSpecific",
"rootModel": "AdmtiveDomain",
"domainName": "acd-00",
"domainType": "Enterprise",
"admtiveDomainID": "0.106."
}
]
[System.Uri]$Uri = "https://webadmin.td90.centile-dev.com/restletrouter/v1/service/Login" # Add the Uri
[System.Uri]$Uri_Get = "https://webadmin.td90.centile-dev.com/restletrouter/v1/3rdParty/AdmtiveDomain"
$ContentType = "application/json" # Add the content type
$Method = 'POST' # Add the method type
$user = "SuperGabriel"
$pass = "SuperGabriel#2019"
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = #{
# Add name and value of headers
"Authorization" = $basicAuthValue
"Cookie" = "thirdParty_SESSIONID=6335513255659796064"
"X-Application" = "3rdParty"
}
$Headers_Get = #{
# Add name and value of headers
"Cookie" = "thirdParty_SESSIONID=4436753218874838616; thirdParty_SESSIONID=6335513255659796064;"
"X-Application" = "3rdParty"
"Host" = "webadmin.td90.centile-dev.com"
"Content-Type"= "$ContentType"
}
$Headers_Get2 = #{
# Add name and value of headers
"Cookie" = "thirdParty_SESSIONID=1312545750448673312"
"X-Application" = "3rdParty"
"Host" = "webadmin.td90.centile-dev.com"
"Content-Type"= "$ContentType"
}
# Splat the parameters
$props = #{
Uri = $Uri
Headers = $Headers
ContentType = $ContentType
Method = $Method
}
$props_Get = #{
Uri = $Uri_Get
Headers = $Headers_Get
ContentType = $ContentType
Method = "GET"
}
try
{
$Result= Invoke-RestMethod #props -SessionVariable sess -OutFile C:\output.json
echo $Result
$Result1= Invoke-RestMethod #props_Get -OutFile C:\"$DateStr".json -WebSession $sess
echo $Result1
}
catch [System.Net.WebException]
{
$res = $_.Exception.Response
echo $res
}
Will work as per your request.
Cheers..

How to set powershell to send email alerts when returned JSON api is empty

i need to write a powershell script to connect to a REST API and to output into a text file stored locally. How do i write it such that if the REST API has issues and timeout without returning a response, the powershell script will trigger an email to send out when the saved text file is empty?
Also, how do i append the date to the saved text file for eg. c:\scripts\response_DDMMYYYY.txt
Below are my current powershell script. Newbie at powershell scripting. Hope someone can enlighten me.
Thanks alot!
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12
add-type #"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"#
[System.Net.ServicePointManager]::CertificatePolicy = New-Object
TrustAllCertsPolicy
$url = "https://someapi.com/get_info"
$token = '12345'
$header = #{Authorization = "Bearer $token" }
$body = #{code = "ABC"}
$result = Invoke-RestMethod -Method POST -Uri $url -ContentType
'application/json' -Body (ConvertTo-Json $body) -Header $header
$result | ConvertTo-Json -depth 100 | Set-Content "c:\scripts\response.txt"
Edited based on kumar's advice:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12
add-type #"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"#
[System.Net.ServicePointManager]::CertificatePolicy = New-Object
TrustAllCertsPolicy
$url = "https://someapi.com/get_info"
$token = '12345'
$header = #{Authorization = "Bearer $token" }
$body = #{code = "ABC"}
try {
$result = Invoke-RestMethod -Method POST -Uri $url -ContentType
'application/json' -Body (ConvertTo-Json $body) -Header $header
$time = (Get-Date).ToString("DD-MM-YYYY")
$result | ConvertTo-Json -depth 100 | Set-Content "c:\scripts\response-
"+$time+".txt"
} catch {
Write-Host "StatusCode: " $_.Exception.Response.StatusCode.value__
Write-Host "StatusDescription:"
$_.Exception.Response.Status.StatusDescription
Send-MailMessage -To "ABC<abc#gmail.com>" -From "server <admin#abc.com>"
-Subject "Error with sync to server"
}
You have a few options to get the response status code of the REST call like so..
try {
Invoke-RestMethod ... your parameters here ...
} catch {
# Dig into the exception to get the Response details.
# Note that value__ is not a typo.
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__
Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}
& Use the Send-MailMessage
Send-MailMessage -To "User01 <user01#example.com>" -From "User02 <user02#example.com>" -Subject "Test mail"
Also, how do i append the date to the saved text file for eg. c:\scripts\response_DDMMYYYY.txt
A simple and nice way is:
$time = (Get-Date).ToString("DD-MM-YYYY")
and simply
("C:\scripts\response-"+$time+".txt")

Curl and powershell json woes

I'm still having issues with getting json working with the curl command in powershell.
even a simple request to POST something into elastic fails miserably with the error
Unexpected character ('D' (code 68)): was expecting double-quote to start field name
I've stripped the script down to the basics just to try and test curl and json and still get failures
$curlExe = "h:\powershell\esb\elastic\curl\curl.exe"
$elasticdata = #{
timereceived = "test"
timesent = "testing"
name = "anon"
status = 0
}
$curldata = $elasticdata | convertto-json -Compress
$elasticoutput = "h:\powershell\esb\elastic\elastic.txt"
$elastichost = "http://localhost:9200/newtest20/filecopy/?pretty"
$elasticheader = "content-type: application/json"
$elamethod = "POST"
$curlargs = $elastichost,
'-X',$elamethod,
'-d',$curldata,
'-H',$elasticheader
& $curlexe #curlargs
If your server is running Powershell 2.0 you will not have Invoke-webRequestbut ConvertTo-Json will also be missing.
I also encountered this issue in the past and I made these functions to workaround that issue
function Invoke-WebRequest([string] $Url, [string] $Method, $BodyObject)
{
$request = [System.Net.WebRequest]::Create($Url)
$request.Method = $Method
$request.ContentType = "application/json"
if ($Method -eq "POST")
{
try
{
$body = ConvertTo-Json20 -InputObject $BodyObject
$requestStream = $request.GetRequestStream()
$streamWriter = New-Object System.IO.StreamWriter($requestStream)
$streamWriter.Write($body)
}
finally
{
if ($null -ne $streamWriter) { $streamWriter.Dispose() }
if ($null -ne $requestStream) { $requestStream.Dispose() }
}
}
$response = $request.GetResponse()
if ($response.StatusCode -ne [System.Net.HttpStatusCode]::OK)
{
throw "ERROR Could not $Method url [$Url]"
}
return $response
}
function ConvertTo-Json20($InputObject){
Add-Type -Assembly System.Web.Extensions
$jsonSerializer = New-Object System.Web.Script.Serialization.JavascriptSerializer
return $jsonSerializer.Serialize($InputObject)
}

failed to insert json from android into mysql

some help pliz.
my android app sends a json like
[{"userName":"fred","userId":"1"},{"userName":"juma","userId":"2"}, {"userName":"drer","userId":"3"},{"userName":"drer","userId":"4"},{"userName":"sdd","userId":"5"}]
to my php 5.3 server. When i use the string in code it works perfect after commenting out json_encode, but when i use file_get_contents it does nothing, when i uncomment json_encode it returns NULL.. what am i doin wrong. my server host is using php 5.3.28. this is my code..
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
include_once './db_functions.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = file_get_contents('php://input');
//$json ='[{"userName":"fred","userId":"1"},{"userName":"juma","userId":"2"},{"userName":"drer","userId":"3"},{"userName":"drer","userId":"4"},{"userName":"sdd","userId":"5"}]';
//$json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t](//).*)#", '', $json);
//$json = json_encode($json);
$data = json_decode($json, true);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storeUser($data[$i]->userId, $data[$i]->userName);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->userId;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->userId;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>
the errors are...
Notice: Uninitialized string offset: 0 in XXXX on line 28
Notice: Trying to get property of non-object in xxxxxx on line 28
Notice: Uninitialized string offset: 0 in xxxxxx on line 28
Notice: Trying to get property of non-object in xxxxxx on line 28
Notice: Uninitialized string offset: 0 in xxxxx on line 32
Notice: Trying to get property of non-object in xxxxx on line 32
[{"id":null,"status":"yes"}]
NB.. line 28 is
$res = $db->storeUser($data[$i]->userId, $data[$i]->userName);
and line 32 is
$b["id"] = $data[$i]->userId;
when i echo $json this is part of my logcat
49-949/com.qnatz.ppolocations I/System.out﹕ [{"userName":"sorry","userId":"1"},{"userName":"wakeup","userId":"2"},{"userName":"sleeping","userId":"3"}]
02-13 12:32:17.110 949-949/com.qnatz.ppolocations W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-13 12:32:18.070 949-949/com.qnatz.ppolocations I/System.out﹕ usersJSON=%5B%7B%22userName%22%3A%22sorry%22%2C%22userId%22%3A%221%22%7D%2C%7B%22userName%22%3A%22wakeup%22%2C%22userId%22%3A%222%22%7D%2C%7B%22userName%22%3A%22sleeping%22%2C%22userId%22%3A%223%22%7D%5D
02-13 12:32:18.100 949-949/com.qnatz.ppolocations W/System.err﹕ org.json.JSONException: Value usersJSON of type java.lang.String cannot be converted to JSONArray
02-13 12:32:18.100 9
SOLVED IT WITH THIS CODE...
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
include_once './db_functions.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
//$json = file_get_contents('php://input');
$json = urldecode(utf8_decode(stripslashes($_REQUEST['usersJSON'])));
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storeUser($data[$i]->userId,$data[$i]->userName);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->userId;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->userId;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>

UPS php api - create order

I am trying to integrate UPS php api to generate online order for sending stuff.
I am able to validate address and get rates for stuff transfer but i am not able to find any solution for generating order and labels for courir, can somebody help me in getting that.
UPS Developer Kit and API is quite a good reference to all API related development, including in PHP. It can be downloaded from here: https://www.ups.com/upsdeveloperkit/downloadresource?loc=en_US
Here is some code example, for the PHP ship accept code (from the API zip):
<?php
//Configuration
$access = " Add License Key Here";
$userid = " Add User Id Here";
$passwd = " Add Password Here";
$accessSchemaFile = " Add AccessRequest Schema File";
$requestSchemaFile = " Add ShipAcceptRequest Schema File";
$responseSchemaFile = "Add ShipAcceptResponse Schema File";
$endpointurl = ' Add URL Here';
$outputFileName = "XOLTResult.xml";
try
{
//create AccessRequest data object
$das = SDO_DAS_XML::create("$accessSchemaFile");
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->AccessLicenseNumber=$access;
$root->UserId=$userid;
$root->Password=$passwd;
$security = $das->saveString($doc);
//create ShipAcceptRequest data oject
$das = SDO_DAS_XML::create("$requestSchemaFile");
$requestDO = $das->createDataObject('','RequestType');
$requestDO->RequestAction='01';
//$requestDO->RequestOption='01';
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->Request = $requestDO;
$root->ShipmentDigest = 'test-Invalid-digest';
$request = $das->saveString($doc);
//create Post request
$form = array
(
'http' => array
(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => "$security$request"
)
);
//print form request
print_r($form);
$request = stream_context_create($form);
$browser = fopen($endpointurl , 'rb' , false , $request);
if(!$browser)
{
throw new Exception("Connection failed.");
}
//get response
$response = stream_get_contents($browser);
fclose($browser);
if($response == false)
{
throw new Exception("Bad data.");
}
else
{
//save request and response to file
$fw = fopen($outputFileName,'w');
fwrite($fw , "Response: \n" . $response . "\n");
fclose($fw);
//get response status
$resp = new SimpleXMLElement($response);
echo $resp->Response->ResponseStatusDescription . "\n";
}
}
catch(SDOException $sdo)
{
echo $sdo;
}
catch(Exception $ex)
{
echo $ex;
}
?>