【问题标题】:validate IP address entered by user验证用户输入的 IP 地址
【发布时间】:2017-04-11 03:48:39
【问题描述】:

我正在编写一个脚本来设置本地主机上的 IP、子网掩码、网关和 DNS 服务器地址。我有一个工作脚本,但我想确保输入的 IP 地址是数字字符,并且每个八位字节的范围在 0-255 之间。 任何帮助将不胜感激。

     $IP = Read-Host -Prompt 'Please enter the Static IP Address.  Format 192.168.x.x'
                $MaskBits = 24 # This means subnet mask = 255.255.255.0
                $Gateway = Read-Host -Prompt 'Please enter the defaut gateway IP Address.  Format 192.168.x.x'
                $Dns = Read-Host -Prompt 'Please enter the DNS IP Address.  Format 192.168.x.x'
                $IPType = "IPv4"

            # Retrieve the network adapter that you want to configure
               $adapter = Get-NetAdapter | ? {$_.Status -eq "up"}

           # Remove any existing IP, gateway from our ipv4 adapter
 If (($adapter | Get-NetIPConfiguration).IPv4Address.IPAddress) {
    $adapter | Remove-NetIPAddress -AddressFamily $IPType -Confirm:$false
}

If (($adapter | Get-NetIPConfiguration).Ipv4DefaultGateway) {
    $adapter | Remove-NetRoute -AddressFamily $IPType -Confirm:$false
}

 # Configure the IP address and default gateway
$adapter | New-NetIPAddress `
    -AddressFamily $IPType `
    -IPAddress $IP `
    -PrefixLength $MaskBits `
    -DefaultGateway $Gateway

# Configure the DNS client server IP addresses
$adapter | Set-DnsClientServerAddress -ServerAddresses $DNS

【问题讨论】:

  • $IP = Read-Host -Prompt 'Please enter the Static IP Address. Format 192.168.x.x'; if($($addr=$null; [ipaddress]::TryParse($IP, [ref]$addr) -and $addr.AddressFamily -eq 'InterNetwork')) { 'Valid IPv4 address' } else { 'Not valid IPv4 address' }

标签: powershell


【解决方案1】:

检查此link。您可以将给定的字符串转换为[ipaddress]

PS C:\Windows\system32> [ipaddress]"192.168.1.1"

以上示例不会产生错误。如果您使用的 IP 地址无效:

PS C:\Windows\system32> [ipaddress]"260.0.0.1"
Cannot convert value "260.0.0.1" to type "System.Net.IPAddress". Error: "An 
invalid IP address was specified."
At line:1 char:1
+ [ipaddress]"260.0.0.1"
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastParseTargetInvocation

您将收到一个可以被捕获的异常。

【讨论】:

  • 请注意,如果您使用[IPAddress] 192.168.1.1 之类的类型转换进行验证,则可能存在转换错误的情况。例如:[IPAddress] 192 将产生 192.0.0.0。但是你可能会认为192 不是一个有效的ip。
【解决方案2】:

这是结合上述两个答案的方法。
对于基本验证,此 oneliner 可以提供帮助

[bool]("text" -as [ipaddress])

但用户可以输入类似"100" 的内容,它会成功验证到IP 地址0.0.0.100
这可能不是您所期望的。
所以我喜欢结合使用正则表达式和类型验证:

function IsValidIPv4Address ($ip) {
    return ($ip -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$" -and [bool]($ip -as [ipaddress]))
}

【讨论】:

    【解决方案3】:

    使用正则表达式

    $ipRegEx="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
    if($ip -notmatch $ipRegEx)
    {
       #error code
    }
    

    您可以在线搜索有关 IP 的正则表达式和示例。请记住,powershell 是基于 .NET 构建的,因此在搜索和阅读正则表达式时,请关注 .NET 或 C# 表达式。例如this

    更新 正如 cmets 后来指出的那样,正则表达式不正确,但它已作为正则表达式验证的示例发布。替代方案可能是((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]?)

    【讨论】:

    • 嗨,333.444.555.666 不是有效的 IP 地址,这个正则表达式有点太简单了。
    • 我知道,但是在线提供了常用值的正则表达式示例。我只是用"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"作为块的例子。
    • 另外,另一种不尝试/捕获的方法是使用 .NET 中许多类型提供的 TryParse 静态函数。 [System.Net.IPAddress]::TryParse()Link 在 MSDN 上
    猜你喜欢
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    相关资源
    最近更新 更多