简体   繁体   English

IP地址的DNS名称

[英]DNS name from IP address

I need to create a list of IP addresses and DNS names. 我需要创建一个IP地址和DNS名称列表。 I am trying to get DNS names from IP addresses. 我正在尝试从IP地址获取DNS名称。 I have tried two ways: 我尝试了两种方法:

  1. try / catch but it ends afterwards. try / catch但此后结束。
  2. Without and it just outputs DNS names that I can't relate to the IP addresses. 没有它,它只会输出与IP地址无关的DNS名称。

Here's what I have so far: 这是我到目前为止的内容:

#try {
 Get-Content C:\Users\pintose\Documents\IP_Address.txt | ForEach-Object 
{([system.net.dns]::GetHostByAddress($_)).hostname >> C:\Users\user\Documents\hostname.txt}
# }
 # catch {
 if ($_.Exception.Message -like "*The requested name is valid*") {
            Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt }
# }

Try this solution: 试试这个解决方案:

$outFile = "C:\Users\user\Documents\hostname.txt"

Get-Content C:\Users\pintose\Documents\IP_Address.txt | ForEach-Object {
    $hash = @{ IPAddress = $_
        hostname = "n/a"     
    }
    $hash.hostname = ([system.net.dns]::GetHostByAddress($_)).hostname
    $object = New-Object psobject -Property $hash
    Export-CSV -InputObject $object -Path $outFile -Append -NoTypeInformation
}

We create a objects, that have the IPaddress in it and a hostname n/a if it cannot be resolved. 我们创建一个对象,该对象中具有IP地址,如果无法解析则提供主机名n/a Then, the object gets exported into the file. 然后,对象被导出到文件中。 You'll get something like: 您会得到类似的信息:

192.0.0.1; Server1

This uses a workflow so it can do parallel foreach 这使用了工作流程,因此可以并行进行foreach

Workflow Get-DNSNames([string[]]$IPAddresses){
    foreach -parallel ($IP in $IPAddresses){
        try{
            @{$IP = $(([system.net.dns]::GetHostByAddress($IP)).hostname)}
        }catch{
            @{$IP = "N/A"}
        }
    }
}

$List = Get-DNSNames -IPAddresses $(Get-Content "C:\IPAddresses.txt").Split("[\r\n]")
$List | Out-File "C:\IPAddresses_Complete.txt"

You might want to try the other solutions offered here, but here are some things you might want to think about. 您可能想尝试这里提供的其他解决方案,但是这里有一些您可能要考虑的事情。

First, I'd recommend not putting the try{}catch{} around the whole of the first command. 首先,建议不要在整个第一个命令中都使用try{}catch{} If you are looping through data and just one of them causes an exception, you risk not completing the task. 如果您正在遍历数据,而其中只有一个会导致异常,则有可能无法完成任务。 Put the try{}catch{} around just the "risky" line of code: try{}catch{}放在仅“危险”的代码行周围:

Get-Content C:\Users\pintose\Documents\IP_Address.txt | Foreach-Object {
  try {
    ([system.net.dns]::GetHostByAddress($_)).hostname >> C:\Users\user\Documents\hostname.txt
  }
  catch {
    if ($_.Exception.Message -like "*The requested name is valid*") {
      Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt
    }
  }
}

When you catch the exception, you only write to the text file in the case that "the requested name is valid" (do you mean in valid?). 当你捕获异常,你只能写在“请求的名称是有效”的情况下的文本文件(你有效期是什么意思?)。 You never write anything to the file otherwise. 否则,您绝不向文件写入任何内容。 Thus, going back to your original code: 因此,回到原始代码:

  • IF there is an exception caused by ANY of the IP addresses 如果有由任何 IP地址引起的异常
  • AND the exception is NOT "the requested name is valid" (which I think might be a typo?) 并且例外不是 “请求的名称有效”(我认为这可能是拼写错误?)
  • THEN no error gets written to the file and the script ends without necessarily completing all the IP addresses. 然后,不会将任何错误写入文件,并且脚本不必完全完成所有IP地址即可结束。

Other things: 其他事情:

You use two methods to write to the file: >> and Out-File . 您使用两种方法写入文件: >>Out-File Probably better to use the PowerShell cmdlet but with the -Append switch to ensure you append to the end of the file: 使用PowerShell cmdlet可能更好,但是使用-Append开关可以确保将其追加到文件末尾:

([system.net.dns]::GetHostByAddress($_)).hostname | Out-File C:\Users\user\Documents\hostname.txt -Append

Write-Output "UNREACHABLE" | Out-File C:\Users\user\Documents\hostname.txt -Append

@restless1987 has suggested a way to ensure you write both the IP address and the hostname (if determined) to the output file. @ restless1987提出了一种确保将IP地址和主机名(如果确定)都写入输出文件的方法。 I'd have a look at that to work out what is going on. 我将对此进行查看以弄清楚发生了什么。

My final tip would be to be wary of reading in from .txt files with Get-Content . 我的最后一个提示是要小心使用Get-Content.txt文件中读取。 They often have trailing (blank) lines and you might want to try to ignore such blanks. 它们通常带有尾随(空白)行,您可能想尝试忽略此类空格。 Probably not a big issue in this case as it will just mean a failed DNS attempt, but I have seen such things wreak havoc on every mailbox in a (very) large company when used with other commands. 在这种情况下,这可能不是什么大问题,因为这仅意味着DNS尝试失败,但是我已经看到,在与其他命令一起使用时,(很多)大公司中的每个邮箱都会遭受严重破坏。

Another way... 其他方式...

$ip_list = Get-Content ./IP_Address.txt

foreach ($ip in $ip_list) {
    try {
        ([system.net.dns]::GetHostByAddress($ip)).hostname |
            Out-File -FilePath ./hostname.txt -Append
    }
    catch {
        if ($_.Exception.Message -like "*The requested name is valid*") {
            Write-Output "UNREACHABLE" | Out-File -FilePath './hostname.txt' -Append }
    }
}

There are many tools that can accomplish this, but if you need a quick and dirty solution that you can run just about anywhere this will get the job done. 有许多工具可以完成此任务,但是如果您需要一种快速而肮脏的解决方案,那么您可以在几乎任何地方运行它就可以完成工作。

Using the eternally useful ps tools such as psloggedon /accepteula \\\\computername or ip address you can get who is currently logged in to check if this is the correct machine. 使用永恒有用的ps工具(例如psloggedon /accepteula \\\\computername or ip address ,可以获取当前登录的用户,以检查这是否是正确的计算机。 For example: 例如:

c:\pstools>psloggedon /accepteula \\10.0.0.10

loggedon v1.33 - See who's logged on
Copyright ⌐ 2000-2006 Mark Russinovich
Sysinternals - www.sysinternals.com

Users logged on locally:
    Error: could not retrieve logon time
NT AUTHORITY\LOCAL SERVICE
 Error: could not retrieve logon time
NT AUTHORITY\NETWORK SERVICE
 1/12/2015 8:06:51 AM    DOMAIN\user
 Error: could not retrieve logon time
NT AUTHORITY\SYSTEM

Users logged on via resource shares:
 1/17/2015 2:26:43 PM    DOMAIN\user

Now that you have confirmed that this IP address is the correct one for this user. 现在,您已经确认此IP地址对于该用户是正确的。 We just need to lookup the IP address using nslookup. 我们只需要使用nslookup查找IP地址。

C:\>nslookup 10.0.0.10
Server:  server.domain.com
Address:  10.10.0.1

Name:    Workstation07.server.domain.com
Address:  10.0.0.10

Now we know that the computer name for that computer is Workstation07. 现在我们知道该计算机的计算机名称为Workstation07。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM