#============================================================================= # # File Name : opnsense-dhcp-read-res.ps1 # Author : Jay Pieren # Date : Jan 2024 # Version : V1 # # Description of script functionality # Will export DHCP leases either from ISCdhcp4 or Kea DHCP # # # Files: # - opnsense-dhcp-read-res.ps1 : The main script # # Requirements: # - PowerShell (windows or mac, tested on ProbBook M2) # # Usage: # 1) start up PowerShell # 2) run the following command './opnsense-dhcp-read-res.ps1 [-ISCdhcp] [-simulation] [-verbose] # # Note: with the switch '-Verbose' you can show additional log information # #============================================================================= [CmdletBinding()] param( [switch]$ISCdhcp = $false, #means export from kea [switch]$leases = $false, #means get resevrations [switch]$simulation = $true ) function usage { write-host "" write-host "usage DataCollector-to-SPS.ps1 [-Org] [-Verbose] [-simulation:$true/$false]" write-host " -Verbose show detailed process information" write-host " -ISCdhcp defauklt fals, from KEA dhcp" write-host " -simulation just simulates the file moves, default = true" write-host "" } #======================================================================================================= # Script variables #------------------------------------------------------------------------------------------------------- $error.Clear() $global:Delimiter = "," $globaL:ArrayDelimiter = "|" $scriptName = "opnsensedhcpreader" # define various environment variables $script_path = $(Get-Item $($MyInvocation.MyCommand.Path)).DirectoryName Import-Module Microsoft.PowerShell.SecretManagement Import-Module Microsoft.PowerShell.SecretStore $Environments = @{ 'prod'=@{ 'InputPath' = '/Volumes/Media/network'; 'psglobal' = '/Volumes/Media/psh-global'; 'ArchiveDir' = '/Volumes/Media/network'; 'Site' = 'https://opnsense.pieren.arpa:8443/api'; 'apicmd' = @{ 'kea' = @{ 'getSubent' = @('Dhcpv4','Get'); 'searchSubnet' = @('Dhcpv4','Get'); 'getReservation' = @('Dhcpv4','Get'); 'searchReservation' = @('Dhcpv4','Get'); 'addReservation' = @('Dhcpv4','Post'); 'status' = @('service','Get'); 'search' = @('leases4','Get') } 'acemclient' = @{ 'search' = @('certificates','Get'); } 'dhcpv4' = @{ 'searchLease' = @('leases','Get'); 'status' = @('service','Get'); } } 'LogDir' = '/Volumes/Media/network'; 'AdminUser' = 'hb0J8Ik4Chlnopw1VPs7xd9ULxcJ7Kn2fiT+iqBWMaGItaPrzoh0djQBzYu9gA3qCWlwUXfRXS0NZQM6'; 'adminpwd' = 'xEjrxfmR9aXojkUwDrUotjObkIbsCMQT8QYmX2i35dO5dQG6xvKF0+m5gBk1AI8KVYQfmFrLcalU5Zq7'; }; 'Q'=@{ } } #------------------------------------------------------------------------------------------------------- $Environment='Prod' # check envexists if ([string]::IsNullOrEmpty($Environment)) { #no valid input write-Error "Can not resolve environment, Abort!" exit 0 } # set directories $InputPath = $Environments.Item($Environment).InputPath $PSglobal = $Environments.Item($Environment).psglobal $Site = $Environments.Item($Environment).Site $apicmds = $Environments.Item($Environment).apicmd $LogPath = $Environments.Item($Environment).LogDir $AdminUser = $Environments.Item($Environment).AdminUser $adminpwd = $Environments.Item($Environment).adminpwd $EnvironmentUser = $env:USER $Computername= $(Hostname) . $PSglobal/globalfunctions.ps1 $AdminUserpwdhash = Get-Hash -env $Environment -EnvUser $EnvironmentUser -compi $Computername -id $AdminUser -path $PSglobal $AdminUserpwd = ConvertTo-SecureString $AdminUserpwdhash -ErrorAction SilentlyContinue -ErrorVariable E # $MailFrom = "datacollector@" $MailTo = "jay.pieren@" $MailHost = "smtp.swissport.aero" $FileError1 = "Check locked: file:{0} error on {1} to {2};Error: {3}" $FileError2 = "Archive: file:{0} error on {1} to {2};Error: {3}" $FileError3 = "copy to target: file:{0} error on {1} to {2};Error: {3}" [array]$ArrayError = @() $scriptName = "opnsense-dhcp-read-res" $dt = Get-Date -f "yyyy-MM-dd-hh-mm" $LogFN = "$LogPath\$scriptname-$dt.log" # prepare opnsense connect and chech login if ($ISCdhcp){ $module = 'dhcpv4' $cmd = 'searchLease' } elseif ($leases) { $module = 'kea' $cmd = 'search' } else { $module = 'kea' $cmd = 'searchReservation' } $cmdstruc = $apicmds.$module.$cmd $controller = $cmdstruc[0] $method = $cmdstruc[1] $URI = ("{0}/{1}/{2}/{3}" -f $site, $module, $controller, $cmd) # Build auth header $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $AdminUser, $adminpwd))) # Set proper headers $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo)) $Error.Clear() [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 try { $response = Invoke-RestMethod -Headers $headers -Method $method -Uri $Uri -SessionVariable "ws" } catch { $msg = ("{0}: Can't connect to opnsense. Abort {1}!" -f $dt, $SnowUriBase) $error[0] Logging -Msg $msg -Logfile $LogFN -OutputToScreen -ForegroundColor Red $body = Get-Content $LogFN EmailAlert -Subject $msg -body $($body -join "`n") exit } [array]$requests = $response.rows if ([string]::isNullorEmpty($requests)){ Logging -Msg ("No items to process") -Logfile $LogFN -OutputToScreen -ForegroundColor Red exit } $FN = "$InputPath\kea-$cmd-$dt.csv" $sheet = $response.rows | ConvertTo-csv Out-File -InputObject $sheet -Encoding utf8 -LiteralPath $FN Logging -Msg ("Items to process found:{0}" -f $requests.Count) -Logfile $LogFN -OutputToScreen -ForegroundColor Magenta