【问题标题】:Powerhsell - Need to resolve IPsPowershell - 需要解析IP
【发布时间】:2020-04-15 17:55:37
【问题描述】:

我可以将包含原始数据的文件导出为 json、xml 或 csv。我选择了 JSON。

JSON 输出如下所示。

{
"entry":[{
"@name":"31.170.162.203",
"ip-netmask":
"31.170.162.203",
"description":
"test1"}
,
{
"@name":"37.193.217.222",
"ip-netmask":
"37.193.217.222",
"description":
"test2"}
,
{
"@name":"46.17.63.169",
"ip-netmask":
"46.17.63.169",
"description":
"test3"}
,
]
}

$input = Get-Content 'C:\Users\e\Desktop' -raw | ConvertFrom-Json

$iplist = $input.entry.'ip-netmask'


foreach ($ip in $iplist)   #for each line in the file...

{
    $hostnames = $null

    try {

        $hostnames = [System.Net.Dns]::GetHostByAddress("$ip").Hostname   #...resolve the ip

    }
     catch [System.Management.Automation.MethodInvocationException] {

          $hostnames = "Server IP cannot resolve."
    }

    catch {

        $hostnames = "unknown error."

    }

    if ($hostnames -ne "Server IP cannot resolve.") {

        $ip -replace $ip, $hostnames

    } else {

        Write-Host $ip
    }
}

输出:

31.170.165.68
31.170.162.203
l37-193-217-222.novotelecom.ru

这告诉我它正在替换已解析的 IP,并保留所有未解析的原始 IP。这正是我想要的

我最终通过进一步的研究、试验和错误找出了如何解决这些问题。

【问题讨论】:

  • DNS 名称是否配置了反向查找记录?如果你做一个ping -a <ip>nslookup <ip> 你会在那里找到名字吗?
  • 是的,他们中的一些人这样做

标签: json powershell dns ip fqdn


【解决方案1】:

事情 1- 发布的 json 格式不正确。

事情 2 -

读取 json 字符串、csv、xml 文件数据并将 IPA 传递给 .Net 类或 DNS cmdlet 以解析它们

一个例子(因为还有其他方法)...

(@'
{
"entry":[{
"@name":"31.170.162.203",
"ip-netmask":"31.170.162.203",
"description":"test1"}
,
{
"@name":"37.193.217.222",
"ip-netmask":"37.193.217.222",
"description":"test2"}
,
{
"@name":"46.17.63.169",
"ip-netmask":"46.17.63.169",
"description":"test3"}
]
}
'@ | 
ConvertFrom-Json | 
Select-Object -ExpandProperty entry).'ip-netmask' | 
ForEach {
    $PSItem
    [System.Net.Dns]::GetHostEntry("$PSItem").HostName
}

#Results
...
37.193.217.222
l37-193-217-222.novotelecom.ru
...

或者这样

(@'
{
"entry":[{
"@name":"31.170.162.203",
"ip-netmask":"31.170.162.203",
"description":"test1"}
,
{
"@name":"37.193.217.222",
"ip-netmask":"37.193.217.222",
"description":"test2"}
,
{
"@name":"46.17.63.169",
"ip-netmask":"46.17.63.169",
"description":"test3"}
]
}
'@ | 
ConvertFrom-Json | 
Select-Object -ExpandProperty entry) | 
ForEach {
    $PSItem.'@name'
    $PSItem.'ip-netmask'
    $PSItem.'description'
    [System.Net.Dns]::GetHostEntry("$($PSItem.'ip-netmask')").HostName
}


# Results
...
37.193.217.222
37.193.217.222
test2
l37-193-217-222.novotelecom.ru
...

【讨论】:

  • 还是不行。使用我的原始 json 文件输入,我得到:使用“1”参数调用“GetHostEntry”的异常:“主机名的大小太长。它不能超过 255 个字符。参数名称:主机名”
猜你喜欢
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 2018-05-15
  • 2015-05-09
  • 1970-01-01
  • 2011-08-15
  • 1970-01-01
  • 2021-06-30
相关资源
最近更新 更多