弱點掃描查伺服器 IP Address 與 Hostname 之間的查詢

2022-07-21

說明如何批次從伺服器 Hostname 取得伺服器的 IP Address,本次示範使用 Python 以及 PowerShell 😁

logo

說明

Python

import socket

datas = {
'web-servernode1': '',
'web-servernode2': '',
'sql-node1': '',
}

for server in datas:
  try:
    ip_address = socket.gethostbyname(server)
  except:
    ip_address = 'unknown'
  print(f"{server}: {ip_address}")
  datas[server] = ip_address

PowerShell

('web-servernode1', 'web-servernode2', 'sql-node1') | 
  % {RESOLVE-DNSNAME $_ } | 
  select name, ipaddress, namehost | 
  clip

從 IP 到 Hostname

PowerShell

# Define the list of IP addresses
$ipList = @(
"192.168.1.100",
"192.168.1.101",
"192.168.1.102"
)

# Create a collection to store results
$results = foreach ($ip in $ipList) {
    try {
        $hostEntry = [System.Net.Dns]::GetHostEntry($ip)
        [PSCustomObject]@{
            IPAddress = $ip
            Hostname  = $hostEntry.HostName
        }
    } catch {
        [PSCustomObject]@{
            IPAddress = $ip
            Hostname  = "Unable to resolve"
        }
    }
}

# Export to CSV
$results | Export-Csv -Path ".\IP_Hostnames.csv" -NoTypeInformation -Encoding UTF8