Featured image of post Documenting with PowerShell: Documenting Unifi infrastructure

Documenting with PowerShell: Documenting Unifi infrastructure

This blog is based on an earlier blog by Eliot Munro; Syncing Unifi Sites with IT-Glue by Eliot Munro. I loved the script, but wanted a little bit of extra information, I also didn’t really like the syncing with a Sharepoint list, so I modified the script to use the site name instead.

So, to use this version you’ll have to make some modifications to your Unifi site names. Rename your sites to follow this template: Name (ITGlueID). An example world be “SuperClient (1234)”. I also added a bit more IPSEC VPN information.

This script also has an added feature of documenting the switches for the site, where it lists which ports are in use and which ports are using PoE. A small example screenshot:

As with all my documentation scripts; it creates the flexible asset in IT-Glue for you. You can run this from an Azure runbook, your RMM system, or your personal workstation.

IT-Glue version

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
###############
$ITGkey = "ITGAPIKey"
$ITGbaseURI = "https://api.eu.itglue.com"
$UnifiBaseUri = "https://YourController.com:8443/api"
$UnifiUser = "APIUSER"
$UnifiPassword = "APIPAssword"
$FlexAssetName = "Unifi Controller Autodoc"
$Description = "A network one-page document that displays the unifi status."
##############

$TableStyling = "<th>", "<th style=`"background-color:#4CAF50`">"
#Settings IT-Glue logon information
If (Get-Module -ListAvailable -Name "ITGlueAPI") {
    Import-module ITGlueAPI
}
Else {
    Install-Module ITGlueAPI -Force
    Import-Module ITGlueAPI
}
Add-ITGlueBaseURI -base_uri $ITGbaseURI
Add-ITGlueAPIKey $ITGkey
write-host "Checking if Flexible Asset exists in IT-Glue." -foregroundColor green
$FilterID = (Get-ITGlueFlexibleAssetTypes -filter_name $FlexAssetName).data
if (!$FilterID) {
write-host "Does not exist, creating new." -foregroundColor green
$NewFlexAssetData =
@{
type = 'flexible-asset-types'
attributes = @{
name = $FlexAssetName
icon = 'sitemap'
description = $description
}
relationships = @{
"flexible-asset-fields" = @{
data = @(
@{
type = "flexible_asset_fields"
attributes = @{
order = 1
name = "Site Name"
kind = "Text"
required = $true
"show-in-list" = $true
"use-for-title" = $true
}
},
@{
type = "flexible_asset_fields"
attributes = @{
order = 2
name = "WAN"
kind = "Textbox"
required = $false
"show-in-list" = $false
}
},
@{
type = "flexible_asset_fields"
attributes = @{
order = 3
name = "LAN"
kind = "Textbox"
required = $false
"show-in-list" = $false
}
},
@{
type = "flexible_asset_fields"
attributes = @{
order = 4
name = "VPN"
kind = "Textbox"
required = $false
"show-in-list" = $false
}
},
@{
type = "flexible_asset_fields"
attributes = @{
order = 5
name = "Wi-Fi"
kind = "Textbox"
required = $false
"show-in-list" = $false
}
},
 @{
type = "flexible_asset_fields"
attributes = @{
order = 6
name = "Port Forwards"
kind = "Textbox"
required = $false
"show-in-list" = $false
}
}, @{
type = "flexible_asset_fields"
attributes = @{
order = 7
name = "Switches"
kind = "Textbox"
required = $false
"show-in-list" = $false
}
}
)
}
}
}
New-ITGlueFlexibleAssetTypes -Data $NewFlexAssetData
$FilterID = (Get-ITGlueFlexibleAssetTypes -filter_name $FlexAssetName).data
}

write-host "Start documentation process." -foregroundColor green

$UniFiCredentials = @{
username = $UnifiUser
password = $UnifiPassword
remember = $true
} | ConvertTo-Json

write-host "Logging in to Unifi API." -ForegroundColor Green
try {
Invoke-RestMethod -Uri "$UnifiBaseUri/login" -Method POST -Body $uniFiCredentials -SessionVariable websession
}
catch {
    write-host "Failed to log in on the Unifi API. Error was: $($_.Exception.Message)" -ForegroundColor Red
}
write-host "Collecting sites from Unifi API." -ForegroundColor Green
try {
$sites = (Invoke-RestMethod -Uri "$UnifiBaseUri/self/sites" -WebSession $websession).data
}
catch {
    write-host "Failed to collect the sites. Error was: $($_.Exception.Message)" -ForegroundColor Red
}

foreach ($site in $sites) {
    $ITGlueOrgID = $site.desc.split('()')[1]
    if (!$ITGlueOrgID) {
write-host "Could not get IT-Glue OrgID for site $($site.desc). Moving on to next site." -ForegroundColor Yellow
continue
}
else {
write-host "Documenting $($site.desc), using ITGlue ID: $ITGlueOrgID" -ForegroundColor Green
}

    $unifiDevices = Invoke-RestMethod -Uri "$UnifiBaseUri/s/$($site.name)/stat/device" -WebSession $websession
    $UnifiSwitches = $unifiDevices.data | Where-Object { $_.type -contains "usw" }
    $SwitchPorts = foreach ($unifiswitch in $UnifiSwitches) {
        "<h2>$($unifiswitch.name) - $($unifiswitch.mac)</h2> <table><tr>"
        foreach ($Port in $unifiswitch.port_table) {
            "<th>$($port.port_idx)</th>"
        }
        "</tr><tr>"
        foreach ($Port in $unifiswitch.port_table) {
            $colour = if ($port.up -eq $true) { '02ab26' } else { 'ad2323' }
            $speed = switch ($port.speed) {
                10000 { "10Gb" }
                1000 { "1Gb" }
                100 { "100Mb" }
                10 { "10Mb" }
                0 { "Port off" }
            }
            "<td style='background-color:#$($colour)'>$speed</td>"
        }
        '</tr><tr>'
        foreach ($Port in $unifiswitch.port_table) {
            $poestate = if ($port.poe_enable -eq $true) { 'PoE on'; $colour = '02ab26' } elseif ($port.port_poe -eq $false) { 'No PoE'; $colour = '#696363' } else { "PoE Off"; $colour = 'ad2323' }
            "<td style='background-color:#$($colour)'>$Poestate</td >"
        }
        '</tr></table>'
    }

    $uaps = $unifiDevices.data | Where-Object { $_.type -contains "uap" }

    $Wifinetworks = $uaps.vap_table | Group-Object Essid
    $wifi = foreach ($Wifinetwork in $Wifinetworks) {
        $Wifinetwork | Select-object @{n = "SSID"; e = { $_.Name } }, @{n = "Access Points"; e = { $uaps.name -join "`n" } }, @{n = "Channel"; e = { $_.group.channel -join ", " } }, @{n = "Usage"; e = { $_.group.usage | Sort-Object -Unique } }, @{n = "Enabled"; e = { $_.group.up | sort-object -Unique } }
    }

    $alarms = (Invoke-RestMethod -Uri "$UnifiBaseUri/s/$($site.name)/stat/alarm" -WebSession $websession).data
    $alarms = $alarms | Select-Object @{n = "Universal Time"; e = { [datetime]$_.datetime } }, @{n = "Device Name"; e = { $_.$(($_ | Get-Member | Where-Object { $_.Name -match "_name" }).name) } }, @{n = "Message"; e = { $_.msg } } -First 10

    $portforward = (Invoke-RestMethod -Uri "$UnifiBaseUri/s/$($site.name)/rest/portforward" -WebSession $websession).data
    $portForward = $portforward | Select-Object Name, @{n = "Source"; e = { "$($_.src):$($_.dst_port)" } }, @{n = "Destination"; e = { "$($_.fwd):$($_.fwd_port)" } }, @{n = "Protocol"; e = { $_.proto } }


    $networkConf = (Invoke-RestMethod -Uri "$UnifiBaseUri/s/$($site.name)/rest/networkconf" -WebSession $websession).data

    $NetworkInfo = foreach ($network in $networkConf) {
        [pscustomobject] @{
            'Purpose'                 = $network.purpose
            'Name'                    = $network.name
            'vlan'                    = "$($network.vlan_enabled) $($network.vlan)"
            "LAN IP Subnet"           =	$network.ip_subnet
            "LAN DHCP Relay Enabled"  =	$network.dhcp_relay_enabled
            "LAN DHCP Enabled"        =	$network.dhcpd_enabled
            "LAN Network Group"       =	$network.networkgroup
            "LAN Domain Name"         =	$network.domain_name
            "LAN DHCP Lease Time"     =	$network.dhcpd_leasetime
            "LAN DNS 1"               =	$network.dhcpd_dns_1
            "LAN DNS 2"               =	$network.dhcpd_dns_2
            "LAN DNS 3"               =	$network.dhcpd_dns_3
            "LAN DNS 4"               =	$network.dhcpd_dns_4
            'DHCP Range'              = "$($network.dhcpd_start) - $($network.dhcpd_stop)"
            "WAN IP Type"             = $network.wan_type
            'WAN IP'                  = $network.wan_ip
            "WAN Subnet"              = $network.wan_netmask
            'WAN Gateway'             = $network.wan_gateway
            "WAN DNS 1"               = $network.wan_dns1
            "WAN DNS 2"               = $network.wan_dns2
            "WAN Failover Type"       = $network.wan_load_balance_type
            'VPN Ike Version'         = $network.ipsec_key_exchange
            'VPN Encryption protocol' = $network.ipsec_encryption
            'VPN Hashing protocol'    = $network.ipsec_hash
            'VPN DH Group'            = $network.ipsec_dh_group
            'VPN PFS Enabled'         = $network.ipsec_pfs
            'VPN Dynamic Routing'     = $network.ipsec_dynamic_routing
            'VPN Local IP'            = $network.ipsec_local_ip
            'VPN Peer IP'             = $network.ipsec_peer_ip
            'VPN IPSEC Key'           = $network.x_ipsec_pre_shared_key
        }

    }

    $WANs = ($networkinfo | where-object { $_.Purpose -eq "wan" } | select-object Name, *WAN* | convertto-html -frag | out-string) -replace $tablestyling
    $LANS = ($networkinfo | where-object { $_.Purpose -eq "corporate" } | select-object Name, *LAN* | convertto-html -frag | out-string) -replace $tablestyling
    $VPNs = ($networkinfo | where-object { $_.Purpose -eq "site-vpn" } | select-object Name, *VPN* | convertto-html -frag | out-string) -replace $tablestyling
    $Wifi = ($wifi | convertto-html -frag | out-string) -replace $tablestyling
    $PortForwards = ($Portforward | convertto-html -frag | out-string) -replace $tablestyling

    $FlexAssetBody = @{
        type       = 'flexible-assets'
        attributes = @{
            traits = @{
                'site-name'     = $site.name
                'wan'           = $WANs
                'lan'           = $LANS
                'vpn'           = $VPNs
                'wi-fi'          = $wifi
                'port-forwards' = $PortForwards
                'switches'      = ($SwitchPorts | out-string)
            }
        }
    }
    write-host "Documenting to IT-Glue"  -ForegroundColor Green
    $ExistingFlexAsset = (Get-ITGlueFlexibleAssets -filter_flexible_asset_type_id $($filterID.ID) -filter_organization_id $ITGlueOrgID).data | Where-Object { $_.attributes.traits.'site-name' -eq $site.name }
    #If the Asset does not exist, we edit the body to be in the form of a new asset, if not, we just upload.
    if (!$ExistingFlexAsset) {
        $FlexAssetBody.attributes.add('organization-id', $ITGlueOrgID)
        $FlexAssetBody.attributes.add('flexible-asset-type-id', $($filterID.ID))
        write-host "  Creating Unifi into IT-Glue organisation $ITGlueOrgID" -ForegroundColor Green
        New-ITGlueFlexibleAssets -data $FlexAssetBody
    }
    else {
        write-host "  Editing Unifi into IT-Glue organisation $ITGlueOrgID"  -ForegroundColor Green
        $ExistingFlexAsset = $ExistingFlexAsset[-1]
        Set-ITGlueFlexibleAssets -id $ExistingFlexAsset.id -data $FlexAssetBody
    }

}

Generic HTML Version

So as always, I’ve also included a generic version. You can use this generic version with your own documentation system. Per popular request here’s a screenshot on how that looks.

```powershell ############### $UnifiBaseUri = “https://Controller.com:8443/api" $UnifiUser = “APIUSER” $UnifiPassword = “APIUSER” ##############

$TableStyling = “”, “<th style="background-color:#4CAF50">”

$UniFiCredentials = @{ username = $UnifiUser password = $UnifiPassword remember = $true } | ConvertTo-Json

$UnifiCredentials write-host “Logging in to Unifi API.” -ForegroundColor Green try { Invoke-RestMethod -Uri “$UnifiBaseUri/login” -Method POST -Body $uniFiCredentials -SessionVariable websession } catch { write-host “Failed to log in on the Unifi API. Error was: $($.Exception.Message)” -ForegroundColor Red } write-host “Collecting sites from Unifi API.” -ForegroundColor Green try { $sites = (Invoke-RestMethod -Uri “$UnifiBaseUri/self/sites” -WebSession $websession).data } catch { write-host “Failed to collect the sites. Error was: $($.Exception.Message)” -ForegroundColor Red }

foreach ($site in $sites) {

    write-host "Documenting $($site.desc), using ITGlue ID: $ITGlueOrgID" -ForegroundColor Green


$unifiDevices = Invoke-RestMethod -Uri "$UnifiBaseUri/s/$($site.name)/stat/device" -WebSession $websession
$UnifiSwitches = $unifiDevices.data | Where-Object { $_.type -contains "usw" }
$SwitchPorts = foreach ($unifiswitch in $UnifiSwitches) {
    "<h2>$($unifiswitch.name) - $($unifiswitch.mac)</h2> <table><tr>"
    foreach ($Port in $unifiswitch.port_table) {
        "<th>$($port.port_idx)</th>"
    }
    "</tr><tr>"
    foreach ($Port in $unifiswitch.port_table) {
        $colour = if ($port.up -eq $true) { '02ab26' } else { 'ad2323' }
        $speed = switch ($port.speed) {
            10000 { "10Gb" }
            1000 { "1Gb" }
            100 { "100Mb" }
            10 { "10Mb" }
            0 { "Port off" }
        }
        "<td style='background-color:#$($colour)'>$speed</td>"
    }
    '</tr><tr>'
    foreach ($Port in $unifiswitch.port_table) {
        $poestate = if ($port.poe_enable -eq $true) { 'PoE on'; $colour = '02ab26' } elseif ($port.port_poe -eq $false) { 'No PoE'; $colour = '#696363' } else { "PoE Off"; $colour = 'ad2323' }
        "<td style='background-color:#$($colour)'>$Poestate</td >"
    }
    '</tr></table>'
}

$uaps = $unifiDevices.data | Where-Object { $_.type -contains "uap" }

$Wifinetworks = $uaps.vap_table | Group-Object Essid
$wifi = foreach ($Wifinetwork in $Wifinetworks) {
    $Wifinetwork | Select-object @{n = "SSID"; e = { $_.Name } }, @{n = "Access Points"; e = { $uaps.name -join "`n" } }, @{n = "Channel"; e = { $_.group.channel -join ", " } }, @{n = "Usage"; e = { $_.group.usage | Sort-Object -Unique } }, @{n = "Enabled"; e = { $_.group.up | sort-object -Unique } }
}

$alarms = (Invoke-RestMethod -Uri "$UnifiBaseUri/s/$($site.name)/stat/alarm" -WebSession $websession).data
$alarms = $alarms | Select-Object @{n = "Universal Time"; e = { [datetime]$_.datetime } }, @{n = "Device Name"; e = { $_.$(($_ | Get-Member | Where-Object { $_.Name -match "_name" }).name) } }, @{n = "Message"; e = { $_.msg } } -First 10

$portforward = (Invoke-RestMethod -Uri "$UnifiBaseUri/s/$($site.name)/rest/portforward" -WebSession $websession).data
$portForward = $portforward | Select-Object Name, @{n = "Source"; e = { "$($_.src):$($_.dst_port)" } }, @{n = "Destination"; e = { "$($_.fwd):$($_.fwd_port)" } }, @{n = "Protocol"; e = { $_.proto } }


$networkConf = (Invoke-RestMethod -Uri "$UnifiBaseUri/s/$($site.name)/rest/networkconf" -WebSession $websession).data

$NetworkInfo = foreach ($network in $networkConf) {
    [pscustomobject] @{
        'Purpose'                 = $network.purpose
        'Name'                    = $network.name
        'vlan'                    = "$($network.vlan_enabled) $($network.vlan)"
        "LAN IP Subnet"           =	$network.ip_subnet
        "LAN DHCP Relay Enabled"  =	$network.dhcp_relay_enabled
        "LAN DHCP Enabled"        =	$network.dhcpd_enabled
        "LAN Network Group"       =	$network.networkgroup
        "LAN Domain Name"         =	$network.domain_name
        "LAN DHCP Lease Time"     =	$network.dhcpd_leasetime
        "LAN DNS 1"               =	$network.dhcpd_dns_1
        "LAN DNS 2"               =	$network.dhcpd_dns_2
        "LAN DNS 3"               =	$network.dhcpd_dns_3
        "LAN DNS 4"               =	$network.dhcpd_dns_4
        'DHCP Range'              = "$($network.dhcpd_start) - $($network.dhcpd_stop)"
        "WAN IP Type"             = $network.wan_type
        'WAN IP'                  = $network.wan_ip
        "WAN Subnet"              = $network.wan_netmask
        'WAN Gateway'             = $network.wan_gateway
        "WAN DNS 1"               = $network.wan_dns1
        "WAN DNS 2"               = $network.wan_dns2
        "WAN Failover Type"       = $network.wan_load_balance_type
        'VPN Ike Version'         = $network.ipsec_key_exchange
        'VPN Encryption protocol' = $network.ipsec_encryption
        'VPN Hashing protocol'    = $network.ipsec_hash
        'VPN DH Group'            = $network.ipsec_dh_group
        'VPN PFS Enabled'         = $network.ipsec_pfs
        'VPN Dynamic Routing'     = $network.ipsec_dynamic_routing
        'VPN Local IP'            = $network.ipsec_local_ip
        'VPN Peer IP'             = $network.ipsec_peer_ip
        'VPN IPSEC Key'           = $network.x_ipsec_pre_shared_key
    }

}
$head = @"
<script>
function myFunction() {
    const filter = document.querySelector('#myInput').value.toUpperCase();
    const trs = document.querySelectorAll('table tr:not(.header)');
    trs.forEach(tr => tr.style.display = [...tr.children].find(td => td.innerHTML.toUpperCase().includes(filter)) ? '' : 'none');
  }</script>
<Title>Audit Log Report</Title>
<style>
body { background-color:#E5E4E2;
      font-family:Monospace;
      font-size:10pt; }
td, th { border:0px solid black;
        border-collapse:collapse;
        white-space:pre; }
th { color:white;
    background-color:black; }
table, tr, td, th {
     padding: 2px;
     margin: 0px;
     white-space:pre; }
tr:nth-child(odd) {background-color: lightgray}
table { width:95%;margin-left:5px; margin-bottom:20px; }
h2 {
font-family:Tahoma;
color:#6D7B8D;
}
.footer
{ color:green;
 margin-left:10px;
 font-family:Tahoma;
 font-size:8pt;
 font-style:italic;
}
#myInput {
  background-image: url('https://www.w3schools.com/css/searchicon.png'); /* Add a search icon to input */
  background-position: 10px 12px; /* Position the search icon */
  background-repeat: no-repeat; /* Do not repeat the icon image */
  width: 50%; /* Full-width */
  font-size: 16px; /* Increase font-size */
  padding: 12px 20px 12px 40px; /* Add some padding */
  border: 1px solid #ddd; /* Add a grey border */
  margin-bottom: 12px; /* Add some space below the input */
}
</style>

“@ $WANs = ($networkinfo | where-object { $.Purpose -eq “wan” } | select-object Name, WAN | convertto-html -frag -PreContent “WANS” | out-string) -replace $tablestyling $LANS = ($networkinfo | where-object { $.Purpose -eq “corporate” } | select-object Name, LAN | convertto-html -frag -PreContent “LANs” | out-string) -replace $tablestyling $VPNs = ($networkinfo | where-object { $_.Purpose -eq “site-vpn” } | select-object Name, VPN | convertto-html -frag -PreContent “VPNs” | out-string) -replace $tablestyling $Wifi = ($wifi | convertto-html -frag -PreContent “Wi-Fi” | out-string) -replace $tablestyling $PortForwards = ($Portforward | convertto-html -frag -PreContent “Port Forwards” | out-string) -replace $tablestyling

$head,$WANs,$LANS,$VPNs,$wifi,$PortForwards,$SwitchPorts | out-file “C:\Temp$($site.desc).html” }

1
2

So thats it! as always, Happy PowerShelling!
All blogs are posted under AGPL3.0 unless stated otherwise
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy