Advertisement
maximillianx

JSON access via Powershell to Spiceworks

Feb 10th, 2015
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <# LoginTo-Spiceworks.ps1
  2.  
  3. .SYNOPSIS
  4.     Logs into Spiceworks and returns a session object to be used in further page or api calls
  5. .PARAMETER $url
  6.     The root of the Spiceworks url without any trailing slashes
  7. .PARAMETER $username
  8.     User login that has permission to login to /login
  9. .PARAMETER $password
  10.     User password to /login
  11. .OUTPUTS
  12.     Microsoft.PowerShell.Commands.WebRequestSession object containing cookies for further page or api calls using Invoke-WebRequest or Invoke-RestMethod
  13. .LINK
  14.     http://community.spiceworks.com/topic/295123-fun-spiceworks-community-project
  15. .LINK
  16.     http://community.spiceworks.com/topic/144808-spiceworks-api-question
  17. .LINK
  18.     http://social.technet.microsoft.com/Forums/windowsserver/en-US/21e834e4-65a9-43df-8177-c4060dd66dc1/having-trouble-trying-to-get-json-info-from-spiceworks-website
  19. .LINK
  20.     http://community.spiceworks.com/scripts/show/311-spiceworks-ticket-rss-atom-feed
  21. .NOTES
  22.     Requires PowerShell 3.0 and .NET Framework 4.0
  23.     Script is commented on sections I found interesting.
  24. .EXAMPLE
  25.     $session = .\LoginTo-Spiceworks.ps1 "https://my.spiceworks.server" "user_login" "user_password"
  26.     $jsonData = ConvertTo-Json(Invoke-RestMethod ($url + "/api/tickets.json") -WebSession $session)
  27. #>
  28.  
  29. [CmdletBinding()]
  30. Param(
  31.     [Parameter()][string] $url,
  32.     [Parameter()][string] $username,
  33.     [Parameter()][string] $password
  34. )
  35.  
  36. add-type @"
  37.    using System.Net;
  38.    using System.Security.Cryptography.X509Certificates;
  39.    public class TrustAllCertsPolicy : ICertificatePolicy {
  40.        public bool CheckValidationResult(
  41.            ServicePoint srvPoint, X509Certificate certificate,
  42.            WebRequest request, int certificateProblem) {
  43.            return true;
  44.        }
  45.    }
  46. "@
  47. [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
  48.  
  49.  
  50. # Constants
  51. $userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36"
  52. $headers = @{"Accept"="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
  53.                 "Accept-Encoding"="gzip,deflate,sdch";
  54.                 "Accept-Language"="en-US,en;q=0.8";}
  55.  
  56. # First call - used to get "spiceworks_session" cookie and "authenticity_token" form entry
  57. # UserAgent and Headers not necessary here, but included to match fiddler capture of browser
  58. $r = Invoke-WebRequest ($url + "/pro_users/login") -SessionVariable session -UserAgent $userAgent -Headers $headers
  59.  
  60. # There are 3 "Set-Cookie" in the response - the 2nd one is blank - fine for browsers, but powershell takes the first one and ignores the 2nd and 3rd - so we fix:
  61. $session.Cookies.SetCookies($url,$r.Headers['Set-Cookie'] -split ',' -match '.' -join ',')
  62.  
  63. # Fill out form fields:
  64. # 1.) Can't use $r.Forms[0].Fields[*] because it returns the "id" on form inputs, but "name" inputs are passed to POST
  65. # 2.) Can't use a dictionary object as it sends data in incorrect order in the POST
  66. # 3.) Plain string works - pickaxe and both btn inputs are not necessary but there to match fiddler capture of browser
  67. $formFieldsText = "authenticity_token=" + [System.Net.WebUtility]::UrlEncode($r.Forms[0].Fields["authenticity_token"]) + `
  68.                     "&_pickaxe=%E2%B8%95" + ` # Go figure, it's an actual pickaxe in unicode
  69.                     "&pro_user%5Bemail%5D=" + [System.Net.WebUtility]::UrlEncode($username) + `
  70.                     "&pro_user%5Bpassword%5D=" + [System.Net.WebUtility]::UrlEncode($password) + `
  71.                     "&btn=login&btn=login"
  72.  
  73. # Redirection not necessary - cookies get messed up between posts unless you manually fix, so we don't follow redirections
  74. $session.MaximumRedirection = 0
  75.  
  76. # Second call - post login data, authenticity_token, and spiceworks_session cookie - Ignore Error output as we'll go over the MaximumRedirection setting here
  77. # This call returns a different spiceworks_cookie and 2 other cookies needed for all future calls (portal_user_email and user_id)
  78. # Have not tested excluding these other cookies to see if other url's work without them, easier to just include them all)
  79. # UserAgent and Headers not necessary here, but included to match fiddler capture of browser
  80. $r = Invoke-WebRequest ($url + "/login") -WebSession $session -Method POST -Body $formFieldsText -UserAgent $userAgent -Headers $headers -ErrorAction SilentlyContinue
  81.  
  82. # Fix blank set-cookie header again
  83. $session.Cookies.SetCookies($url,$r.Headers['Set-Cookie'] -split ',' -match '.' -join ',')
  84.  
  85. # Return the session object for future calls
  86. $session
  87.  
  88. #An example of returning JSON data using the web session cached above:
  89. $Data = Invoke-WebRequest -uri "$url/api/devices.json" -WebSession $session -ContentType "application/x-www-form-urlencoded" | ConvertFrom-Json
  90.  
  91. $Data
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement