Skip to main content

Script to collect LLDP Information of all the hosts connected to vCenter

 

Challenge: To have a clean inventory of host to switch mapping, we had to gather the lldp information of all the ESXi hosts. It would be easier if the hosts are a few/ in a single digit. 

We had to find an easy and automated script which can generate the output.

 Pre-requisites:

1) Requires power-cli to be installed.

2) Install-Module -Name VMware.PowerCLI -Scope CurrentUser 

Powershell script:

 1) To ignore ssl certificate error

Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$true

 2) Script to connect to vCenter and provide valid credentials, and the script will provide the output in a csv format to the provided location, which can be customized.

 # Array of vCenter Server names or IP addresses
$vCenterServers = @("192.168.1.62") # Add all your vCenter Servers here

# Output file path
$OutputPath = "C:\Users\asyed\Documents\ESXi_LLDP_Report1.csv" # Change this to your desired output path

# --- Script Start ---

Write-Host "Connecting to vCenter Server(s)..." -ForegroundColor Green

# Connect to all specified vCenter Servers
# Using -Force to bypass certificate warnings for lab/test environments.
# In production, ensure proper certificate handling.
try {
    Connect-VIServer -Server $vCenterServers -WarningAction SilentlyContinue -ErrorAction Stop
    Write-Host "Successfully connected to vCenter Server(s)." -ForegroundColor Green
}
catch {
    Write-Error "Failed to connect to vCenter Server(s). Error: $($_.Exception.Message)"
    exit
}

$lldpReport = @()

Write-Host "Gathering LLDP information from ESXi hosts..." -ForegroundColor Green

# Get all ESXi hosts
$allEsxiHosts = Get-VMHost # Renamed the collection variable for clarity

if ($allEsxiHosts.Count -eq 0) {
    Write-Warning "No ESXi hosts found in the connected vCenter Server(s)."
}
else {
    # CHANGE THIS LINE: Use a different variable name for the loop, e.g., $esxiHost
    foreach ($esxiHost in $allEsxiHosts) {
        Write-Host "Processing host: $($esxiHost.Name)..." -ForegroundColor Cyan

        try {
            # Get the NetworkSystem view for the host
            $networkSystem = Get-View $esxiHost.ExtensionData.ConfigManager.NetworkSystem

            # Get physical NICs
            $physicalNics = $esxiHost.ExtensionData.Config.Network.Pnic

            if ($physicalNics.Count -eq 0) {
                Write-Warning "No physical NICs found for host $($esxiHost.Name)."
                continue
            }

            foreach ($pnic in $physicalNics) {
                $pnicDevice = $pnic.Device
                $networkHint = $null

                try {
                    $networkHint = $networkSystem.QueryNetworkHint($pnicDevice)
                }
                catch {
                    Write-Warning "Could not retrieve network hint for $($esxiHost.Name) - $($pnicDevice). Error: $($_.Exception.Message)"
                    continue
                }

                if ($networkHint) {
                    foreach ($hint in $networkHint) {
                        if ($hint.LldpInfo) {
                            $lldpInfo = $hint.LldpInfo
                            $managementAddress = ($lldpInfo.Parameter | Where-Object {$_.Key -eq "Management Address"}).Value
                            $systemName = ($lldpInfo.Parameter | Where-Object {$_.Key -eq "System Name"}).Value
                            $systemDescription = ($lldpInfo.Parameter | Where-Object {$_.Key -eq "System Description"}).Value
                            $portDescription = ($lldpInfo.Parameter | Where-Object {$_.Key -eq "Port Description"}).Value
                            $chassisId = $lldpInfo.ChassisId
                            $portId = $lldpInfo.PortId

                            $lldpEntry = [PSCustomObject]@{
                                VMHostName          = $esxiHost.Name
                                VMHostIP            = (Get-VMHostNetworkAdapter -VMHost $esxiHost | Where-Object {$_.ManagementTrafficEnabled -eq $true}).IP # Get management IP
                                PhysicalNic         = $pnicDevice
                                LLDP_ChassisID      = $chassisId
                                LLDP_PortID         = $portId
                                LLDP_PortDescription= $portDescription
                                LLDP_SystemName     = $systemName
                                LLDP_SystemDescription = $systemDescription
                                LLDP_ManagementAddress = $managementAddress
                            }
                            $lldpReport += $lldpEntry
                        }
                        elseif ($hint.ConnectedSwitchPort) {
                            Write-Verbose "CDP information found for $($esxiHost.Name) - $($pnicDevice). LLDP not present."
                        }
                        else {
                            Write-Verbose "No LLDP or CDP information found for $($esxiHost.Name) - $($pnicDevice)."
                        }
                    }
                }
            }
        }
        catch {
            Write-Error "An error occurred while processing host $($esxiHost.Name). Error: $($_.Exception.Message)"
        }
    }
}

Write-Host "Exporting LLDP information to CSV: $($OutputPath)..." -ForegroundColor Green

if ($lldpReport.Count -gt 0) {
    $lldpReport | Export-Csv -Path $OutputPath -NoTypeInformation -UseCulture
    Write-Host "LLDP report generated successfully at: $($OutputPath)" -ForegroundColor Green
}
else {
    Write-Warning "No LLDP information was collected to export."
}

Write-Host "Disconnecting from vCenter Server(s)..." -ForegroundColor Green
Disconnect-VIServer -Confirm:$false

Write-Host "Script finished." -ForegroundColor Green 

# --- Script End --- 

 

3) Once you get the output, return the invalid certificate action to false by running below command. 

Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false 

Comments

Popular posts from this blog

How to find the physical switch port details from esxcli?

 This article will help you to get the details of the physical switch port details of  ESXi uplinks. Step 1: Login to the ESXi host using root user/ SSO User. Step 2: Enter the below command into the terminal.   vim-cmd hostsvc/net/query_networkhint | grep 'portId\|devId\|vmnic' Output will show the details of the associated physical switch. Note: CDP, LLDP has to be enabled on physical switch. This information is needed when you end up in a troubleshooting session with network team for physical uplinks down/inconsistency of traffic.

JobQueue is full in iDRAC and unable to upgrade firmware??

  Hello There, I was working recently on upgrading the firmware for Dell Power Edge servers due a requirement. As usual, I did the download of the necessary firmware update file and uploaded it in the iDRAC and started the upgrade. Waited for couple of minutes, If I can say, it was almost 15 minutes without any progress. I tried to check the log/job queue in the iDRAC and found it was full of old entries and I tried clearing it but found no option. Later after findings, I managed to find a command which clears the jobqueue, and below is the command I used after logging into iDRAC via SSH. racadm jobqueue delete -i JID_CLEARALL_FORCE Once the above command was executed, I tried to login to iDRAC and check the job queue and found everything was cleared. Whats next?? Tried uploading the file again and then managed to successfully update the firmware.

Renew SSL Certificate for vCloud Director 10.4

Hello There, I would like to give credit for this article to my colleague Muhannad S. Aljaghthami who worked on this task and gave us full insight on how to do. Now lets talk about replacing an expired/ about to expire SSL certificate for the vCloud Director application which is hosted on internet. Prerequisites: Digicert Certificate utility for windows.  Putty/Mobaxterm application for SSH to vCD cells. Winscp to transfer the files to vCD cells. SSH access should be validated on vCD Cells Backup tool to take a backup of vCD cells. Versions & products used while writing this article: vCloud Director 10.4 NSX AVI 22.1.1 Step by step procedure: Initiated a CSR request using Digicert utility for windows and shared the CSR with the team who manages the SSL certificates.  Post submission of CSR,we received the root & SSL certificate for our vCloud Director URL. Using the Digicert utility, we have extracted the pfx file and key file, sample screenshot below.     No...