Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Get Hostnames and Test Network Ports Using PowerShell

This PowerShell script is useful for system and network administrators who need to resolve hostnames from a list of IPs and test connectivity to specific ports. These tasks are essential for auditing, monitoring, and troubleshooting network environments in Windows-based infrastructures.

This article covers:

  • How to read IPs from a file.
  • How to resolve hostnames using PowerShell and .NET libraries.
  • How to test connectivity on specific ports using Test-NetConnection.

Adjustments for Practical Use:

  • The original script has the ports array commented out. It must be uncommented and defined properly to test port accessibility.
  • Added minor improvements for clarity and completeness.

Examples:

  1. Create a file called ips.txt with IPs (one per line):

    192.168.1.1
    8.8.8.8
    192.168.1.100
  2. Complete PowerShell Script (Get-HostnamesAndPorts.ps1):

    
    # Lista de IPs
    $ips = Get-Content -Path "./ips.txt"

Lista de Portas para testar

$ports = @(80, 443, 21, 25) # Modifique conforme necessário

Função para obter o hostname a partir do IP

function Get-Hostname { param ( [string]$ip ) try { $hostname = [System.Net.Dns]::GetHostEntry($ip).HostName } catch { $hostname = "Hostname não encontrado" } return $hostname }

Obter hostnames

Write-Output "=== RESOLUÇÃO DE HOSTNAMES ===" foreach ($ip in $ips) { $hostname = Get-Hostname -ip $ip Write-Output "$ip : $hostname" }

Testar conectividade nas portas

Write-Output "`n=== TESTE DE PORTAS ===" foreach ($ip in $ips) { foreach ($port in $ports) { $result = Test-NetConnection -ComputerName $ip -Port $port if ($result.TcpTestSucceeded) { Write-Output "$ip está acessível na porta $port." } else { Write-Output "$ip está bloqueado na porta $port." } } }


3. **Executar o Script via PowerShell:**
```powershell
.\Get-HostnamesAndPorts.ps1

This script helps validate DNS resolution and port accessibility across your network, making it easier to identify misconfigurations, offline devices, or firewall issues.

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.