Public/Connect-SWAppliance.ps1
function Connect-SWAppliance { <# .SYNOPSIS Connect to a SonicWall appliance. .DESCRIPTION Connects to a SonicWall appliance using the SonicOS REST API. .PARAMETER Server IP or DNS name of the SonicWall appliance. .PARAMETER Credential PSCredential to use for the authentication. .PARAMETER Port Port to connect to the SonicOS API. .PARAMETER Insecure When set Connect-SWAppliance try to make the connection using HTTP instead of HTTPS. .EXAMPLE Connect-SWAppliance -Server 192.168.168.168 Basic use, connects to 192.168.168.168 SonicWall appliance. If there's not a -Credential parameter the function asks for it. .EXAMPLE Connect-SWAppliance -Server 192.168.168.168 -Credential $credential -Port 4433 Connects to 192.168.168.168 SonicWall appliance using a prebuild PSCredential object using port 4433. .EXAMPLE Connect-SWAppliance -Server 192.168.168.168 -Credential $credential -Insecure:$true Insecure mode, only for test purposes. Tries to connect to SonicWall appliance using HTTP. #> [CmdletBinding()] param ( # SonicWall Appliance IP or FQDN [Parameter(Mandatory=$true)] [string]$Server, # Credential object to connect to SonicWall Appliance [Parameter(Mandatory=$true)] [System.Management.Automation.PSCredential]$Credential, # Port to connect to the appliance [int32]$Port, # Connect using HTTP [boolean]$Insecure=$false ) begin { # Declaring resource of the function $Resource = 'auth' # Declaring used rest method $Method = 'post' } process { ### Building the URL # Generate the protocol if (!$Insecure){ $Protocol = 'https' # Disable Ssl verification to bypass autogenerated certicate Disable-SslVerification # Force the use of TLS1.2 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } else { $Protocol = 'http' } # Add custom port to address if necessary if (!$Port) { $Address = $Server } else { $Address = "$($Server):$($Port)" } # Base URL for API calls $BaseApiUrl = '/api/sonicos/' $SWBaseUrl = "$($Protocol)://$($Address)$($BaseApiUrl)" # Generate the credential pair $CredPair = "$($Credential.UserName):$($Credential.GetNetworkCredential().Password)" $EncodedCredPair = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($CredPair)) # Remove variable with plain text password Remove-Variable -Name CredPair # Generate headers for the request $Headers = @{ Authorization = "Basic $EncodedCredPair" } # Connect to the appliance Try { Write-Verbose "Trying to authenticate to $SWBaseUrl." Invoke-RestMethod -Uri "$($SWBaseUrl)$($Resource)" -Headers $Headers -Method $Method | Out-Null # Set an environmental variable with the base URL of the connection to reuse in the rest of the PSSonicWall functions $env:SWConnection = $SWBaseUrl } Catch { Throw $_ } } } |