2013-03-29 56 views
3

什麼可能是最好的方式來使用除了解決計算機名的DNS記錄:檢查使用PowerShell 2.0

[System.Net.DNS]::GetHostByName('MachineName').HostName 

我不想導入任何特定的DNS模塊。

+0

好吧,看來的gethostbyname已被標記爲過時的方法 – Rajiv

+0

替代方案:解決()或的gethostname( ) – Rajiv

+0

['Resolve()'](http:// msdn .microsoft.com/en-us/library/system.net.dns.resolve.aspx)也被標記爲廢棄,並且['GetHostName()'](http://msdn.microsoft.com/en-us/ library/system.net.dns.gethostname.aspx)返回本地計算機的主機名,所以它不是'Resolve()'或'GetHostByName()'的替代方法。 ['GetHostEntry()'](http://msdn.microsoft.com/en-us/library/ms143998.aspx)似乎是du jour的方法。你試圖解決的實際問題是什麼? –

回答

5

你可以嘗試GetHostEntry方法:

[Net.DNS]::GetHostEntry("MachineName") 

另一種方法是使用Test-Connection cmdlet來ping到它,see this tip

0

以下2種方式IP的解析DNS地址是唯一的。 這就是你如何使用它。

[Net.DNS]::GetHostEntry("MachineName") 
    [System.Net.DNS]::GetHostByName('MachineName').HostName 

就像我說的,這是你如何使用它們。 我已經寫了一個腳本來做到這一點。

它需要一個IP地址列表並解析那裏的DNS。 在腳本後面它將輸出轉換爲Excel表格,向您顯示結果。 基於過濾器,您可以設置佈局。

現在我知道並不是所有的IP都會用這些方法解決,這就是爲什麼我在腳本中包含一個函數來過濾未解析的IP並將它們放到Excel表格的底部。 (讓每一個IP直接鏈接到who.is/whois/ipadress

這裏的腳本,如果你有興趣。

#Get current date 
$Date = date -format yyyy-MM-dd 
$Company = "Company" 
    $Company2 = "Company2" 
     ######################## 


#Define all Paths. 
$Path = "C:\inetpub\wwwroot\BlockedIP" #This is where your file's will be saved. 
    md "$Path\HTML\$Date" -Force |Out-Null 
    $path2 = "$Path\HTML\$Date" 
$PathWeb = "/ResolvedIp/HTML/$Date" 
######################## 


#Define File's used or created in this script. 
$File = "$Path\IP-$Date.txt" 
    $FileHtml = "$Path2\IP-$Date.htm" 
     $FileXML = "$Path\IP-$Date.xlsx" 
      $FileHTMLWeb = "$PathWeb\IP-$date.htm" 
      ###################################### 


#Define error actions. 
$erroractionpreference = "SilentlyContinue" 
########################################### 

#Since the script used COM objects it will need the following 2 folders: 

#(32Bit) 
MD "C:\Windows\System32\config\systemprofile\Dektop" -force 
    MD "C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Windows\Temporary Internet" -force 
#(64Bit) 
MD "C:\Windows\SysWOW64\config\systemprofile\Desktop" -force 
    MD "C:\Windows\SysWOW64\config\systemprofile\AppData\Local\Microsoft\Windows\Temporary Internet" -force 
#Once successfull the script will run without a problem if scheduled. 

cls 

      (gc $File) | ? {$_.trim() -ne "" } | set-content $File 
      $IPCount = (gc $File) 
      $IPCount = $IPCount.count 

write "$IPCount unique IP addresses detected." 



#Define error actions. 
$erroractionpreference = "SilentlyContinue" 



#Get content from given IP list. 
$colComputers = @(gc $File | sort |Select -unique) 
    $SourceCount = $colComputers.Count 
    write "$SourceCount IP's detected." 

Function Set-KnownIPs{ 
Param([Object]$DNSLookupObject) 
Switch($DNSLookupObject){ 
    {$_.Source -Match "(108.162.254|141.101.(?:104|105)|199.27.128|173.245(?:53|52|51))"}{$_.HostName = "CloudFlare, Inc."} 
    {$_.Source -Match "(64.18.[0-18])"}{$_.HostName = "Google, Inc."} 
    {$_.Source -Match "(192.168|127.0.0)"}{$_.HostName = "Internal Infrastructure"} 
} 
$DNSLookupObject 
} 

#Get DNS Results 
$Progress=1 
$DNSResults = $colComputers | %{ 
Write-Progress -Activity "Creating a usable 'Blocked IP' list ($Progress/$sourcecount)" -PercentComplete ($Progress/$sourceCount*100) -Status "Please stand by" 
try { 
    ($dnsresult = [System.Net.DNS]::GetHostEntry($_)) 
} 
catch { 
    $dnsresult = "Fail" 
} 
Set-KnownIPs -DNSLookupObject ([PSCustomObject][Ordered]@{ 
Source=$_.ToUpper() 
HostName=$(if(!([string]::IsNullOrEmpty($dnsresult.HostName))){$dnsresult.HostName}) 
IPAddress=$(if(!([string]::IsNullOrEmpty($dnsresult.AddressList))){$dnsresult.AddressList[0].ToString()}) 
}) 
$Progress++ 
} 

$Keywords = @("Google","Cloudflare","Cloud","Ping", 
"Easy-Voyage","McAfee","Pingdom","Panopta","Scoot","Uniglobe", 
"Internal") 

$Filter = "($(($Keywords|%{[RegEx]::Escape($_)}) -join "|"))" 


$DNSLookupFailed = $DNSResults | 
?{[string]::IsNullOrEmpty($_.HostName) -and !($_ -match $filter)} 

$DNSWithKeyword = $DNSResults | 
?{$_ -match $Filter} 

$DNSNoKeyword = $DNSResults | 
?{!($_.HostName -match $Filter) -and !([string]::IsNullOrEmpty($_.IPAddress))} 


#$count = ($DNSResults|?{$_ -match $filter}).count 
$count = $SourceCount 
##################### 


#start Excel. 
$a = New-Object -comobject Excel.Application 

# set interactive to false so nothing from excel is shown. 
$a.DisplayAlerts = $False 
$a.ScreenUpdating = $True 
$a.Visible = $True 
$a.UserControl = $True 
$a.Interactive = $True 
########################### 


#Create sheets in Excel. 
$b = $a.Workbooks.Add() 
    $c = $b.Worksheets.Item(1) 
    $c.Activate() | Out-Null 

#Create a Title for the first worksheet and adjust the font 
$c.Cells.Item(1,1)= "Blocked IP's $Date" 
    $c.Cells.Item(1,1).Font.ColorIndex = 55 
    $c.Cells.Item(1,1).Font.Color = 8210719 

$c.Cells.Item((3+$DNSWithKeyword.Count+1),1) = "IP's not in whitelist" 
    $c.Cells.Item((3+$DNSWithKeyword.Count+1),1).Font.ColorIndex = 55 
    $c.Cells.Item((3+$DNSWithKeyword.Count+1),1).Font.Color = 8210719 

$c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+3),1)= "IP's without DNS return" 
    $c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+3),1).Font.ColorIndex = 55 
    $c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+3),1).Font.Color = 8210719 
    ####################################### 


$range = $c.Range("a1","e1") 
$range.Style = 'Title' 
$range.Select() 
$range.MergeCells = $true 
$range.VerticalAlignment = -4108 
################################ 

      $Linkedin = "https://www.linkedin.com/profile/view?id=96981180" #Look me up! :D 
#Define row to be used for linkedin link. 
$CounterRow = $Count+5 
###################### 


#Define subjects. 
$c.Name = "Blocked IP's ($Date)" 
$c.Cells.Item(2,1) = "Given IP" 
$c.Cells.Item(2,2) = "Resolved DNS" 
$c.Cells.Item(2,3) = "Returned IP" 
$c.Cells.Item(2,5) = "$Company" 
$c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+5),1) = "Created by" 
######################################## 


$link = "http://www.$Company" 
    $link2 = "$Linkedin" 

$r = $c.Range("E2") 
    [void]$c.Hyperlinks.Add($r, $link) 

$r = $c.Range("A$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+5)") 
    [void]$c.Hyperlinks.Add($r, $link2) 
    ################################### 

#Define cell formatting from subjects. 
$c.Range("A2:E2").Interior.ColorIndex = 6 
$c.Range("A2:E2").font.size = 13 
$c.Range("A2:E2").Font.ColorIndex = 1 
$c.Range("A2:E2").Font.Bold = $True 
################################### 


#Define the usedrange, excluding header and footer rows 
$KeyRange = $c.Range("A3:c$(3+$DNSWithKeyword.Count)") 
$NoKeyRange = $c.Range("A$(3+$DNSWithKeyword.Count+2):c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+2)") 
$NoDNSRange = $c.Range("A$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+4):c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+4)") 
$SheetRange = $c.Range("A3:e$(4+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+4)") 
$Investigate = $c.Range("c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+4):c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+4)") 
    ################################ 


#Set background color for the IP list. 
$SheetRange.interior.colorindex = 6 
$KeyRange.interior.colorindex = 4 
$NoKeyRange.interior.colorindex = 15 
$NoDNSRange.interior.colorindex = 8 
#################################### 

#Populate data into spreadsheet 
$DNSWithKeyword | Select Source, HostName, IPAddress | Sort HostName -Descending | 
ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | 
Select -Skip 1 | Clip 
$c.Paste($KeyRange,$false) 

$DNSNoKeyword | Select Source, HostName, IPAddress | Sort HostName -Descending | 
ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | 
Select -Skip 1 | Clip 
    $c.Paste($NoKeyRange,$false) 

$DNSLookupFailed | Select Source, HostName, IPAddress | sort Source -Descending| 
ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | 
Select -Skip 1 | Clip 
    $c.Paste($NoDNSRange,$false) 
    ############################ 



ForEach($Cell in $Investigate){ 
If([String]::IsNullOrWhitespace($Cell.value2)){ 
$Cell.Item($_) = "N/A" 
[void]$cell.Hyperlinks.Add($Cell) 
    } 
} 

########################################################################### 


#Define borders here. 
$xlOpenXMLWorkbook = 51 
$xlAutomatic=-4105 
$xlBottom = -4107 
$xlCenter = -4108 
$xlRight = -4152 
$xlContext = -5002 
$xlContinuous=1 
$xlDiagonalDown=5 
$xlDiagonalUp=6 
$xlEdgeBottom=9 
$xlEdgeLeft=7 
$xlEdgeRight=10 
$xlEdgeTop=8 
$xlInsideHorizontal=12 
$xlInsideVertical=11 
$xlNone=-4142 
$xlThin=2 
#########  

$selection = $c.range("A2:C$(1+$DNSResults.Count-9)") 
    $selection.select() |out-null 
    $selection.HorizontalAlignment = $xlRight 
    $selection.VerticalAlignment = $xlBottom 
    $selection.WrapText = $false 
    $selection.Orientation = 0 
    $selection.AddIndent = $false 
    $selection.IndentLevel = 0 
    $selection.ShrinkToFit = $false 
    $selection.ReadingOrder = $xlContext 
    $selection.MergeCells = $false 
    $selection.Borders.Item($xlInsideHorizontal).Weight = $xlThin 
    ############################################################# 


#Define the usedrange for autofitting. 
$d = $c.UsedRange 
################# 

#Make everything fit in it's cell. 
$d.EntireColumn.AutoFit() | Out-Null 
#################################### 

$c.usedrange | Where{$_.Value2 -match "(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)"} | 
ForEach{$IPLink = "http://who.is/whois-ip/ip-address/$($Matches[1])";[void]$c.Hyperlinks.Add($_, $IPLink)} 

#Define html code for Excel save to .htm. 
$xlExcelHTML = 44 
################# 

#Save final result as an .xlsx file. 
$b.SaveAs("$FileXML") 
##################### 

#Save final result as a .htm file 
$b.SaveAs("$FileHTML",$xlExcelHTML) 
################################### 
1

我是在一個情況下,我不得不查詢特定的DNS服務器,這是不可能直接與.NET/PowerShell的所以我結束了使用好老NSLOOKUP:。

$client="10.110.10.10" 
$ns="10.20.1.10" 
(nslookup $client $ns |sls name).toString().split(":")[1].trim()