windows 动态获取IP

windows get IP dynamically

我想实现以下逻辑。是否可以使用 batch 或 power shell 来实现这样的实现?请与我分享脚本。

假设我有一个包含以下内容的配置文件 "config.propertis":

BOOTPRORO=statis or dhcp
IPADDR=192.168.10.10
NETMASK=255.255.255.0
GATEWAY=192.168.10.1
DNS=8.8.8.8

我希望系统在启动时检查该文件并相应地配置网络:

  1. OS: Windows
  2. 如果在 BOOTPROTO=dhcp 中,当在网络配置中使用 DHCP 并忽略配置文件中的所有其他内容时,除了 DNS
  3. 如果在 BOOTPROTO=static 中,则使用配置文件中的所有变量将 IP 配置为静态。

所以,我在Linus下有这样的逻辑,用shell。该脚本在 rc.d 中配置并在网络服务之前执行。是否可以在 Windows 上实现这样的功能?伙计们,请分享脚本!

在 Windows 中我们可以通过批处理文件或 powershell 脚本设置 ip 地址但是当你使用 dhcp 地址时你的 ip 是动态的而不是静态的我强加你想要静态 ip 地址 批处理文件

netsh interface ip set address name=”Local Area Connection” static 192.168.10.10 255.255.255.0 192.168.10.1
netsh interface ip set dns name=”Local Area Connection” static 8.8.8.8

如果你想成为 dhcp 你应该设置

netsh interface ip set address name=”Local Area Connection” source=dhcp

注意我强加你的网卡名称是本地连接

在powershell V3.0及以后我们使用

New-NetIPAddress –InterfaceAlias “Local Area Connection ” –IPv4Address “192.168.10.10” –PrefixLength 24 -DefaultGateway 192.168.10.1
Set-DnsClientServerAddress -InterfaceAlias “Local Area Connection” -ServerAddresses 8.8.8.8

对于启动,您可以将脚本 .bat 和 .ps1 放入启动 windows 但注意您应该 Set-ExecutionPolicy bypass 在 U 运行 任何 powershell[= 脚本之前25=] 要启动任何脚本,请参阅 link

我们绝对可以做到。

首先,因为许多系统有多个网络接口,您需要确定我们要更改的适配器的 ifIndex 是什么。通过 运行ning Get-NetIPInterface 做到这一点。您应该会看到如下结果:

在我的示例中以及以后,我将使用这个索引 41。您应该更改它以匹配您在自己的计算机上找到的内容

好的,现在从文本文件中读取。由于您以键=值对格式(通常称为哈希表)提供了数据,我们可以使用 ConvertFrom-Stringdata 轻松地从那里获取数据。这将为我们提供一个 PowerShell 哈希表,我们可以像这样拉出所需的行。

$values = get-content T:\config.properties | ConvertFrom-StringData
$values.BootProro
>statis

我们可以使用它来将PC设置为动态IP模式,或者设置静态地址。现在,要在您的环境中使用它,您需要找到 ifIndex,正如我之前提到的。将我的索引 41 替换为您自己的索引,然后试一试。我已将 -WhatIf 添加到每一行,因此您将看到 当您 运行 时会发生什么 。如果您对它所做的更改感到满意,请删除 -Whatif 以使脚本实际更改设置。

$values = gc T:\config.properties | ConvertFrom-StringData
if ($values.BOOTPRORO -eq "dhcp"){
  Write-Output "---DHCP mode detected in 'config.properties' file"
  Write-Output "---Setting Set-NetAdapter -DHCP Enabled"
  Set-NetIPInterface –InterfaceIndex 41 –Dhcp Enabled -WhatIf
  }
else{
  Write-outPut "---static mode detected in 'config.properties' file"
  Write-Output "---Removing network configuration"
  Remove-NetIPAddress -InterfaceIndex 41 -whatif

  Write-Output "---Setting new network configuration equal to"
  $values

  New-NetIPAddress -DefaultGateway $values.GATEWAY -IPAddress $values.IPADDR -PrefixLength 24 -InterfaceIndex 41 -WhatIf
Set-DnsClientServerAddress -ServerAddresses $values.DNS -InterfaceIndex 41 -WhatIf
 }

输出如下所示: