如何制作添加网络路由的脚本?

时间:2010-07-20 19:31:05

标签: powershell batch-file vpn routes

写景

SO Windows 7

我需要通过cisco vpn连接到远程主机。有时主机目标网络与本地网络相同。 示例(ipconfig命令的部分输出):

Ethernet adapter Cisco Vpn Adapter:
   IPv4 Address. . . . . . . . . . . : 192.168.100.12
   Subnet Mask . . . . . . . . . . . : 255.255.255.0

Wireless LAN adapter Wireless Network Connection:
   IPv4 Address. . . . . . . . . . . : 192.168.1.74
   Subnet Mask . . . . . . . . . . . : 255.255.255.0

我需要通过Vpn连接到远程网络上的主机192.168.1.11 然后我需要添加新路由(在此配置中,到192.168.1.xxx的所有流量都是到本地网络的路由) 路线打印的输出开始于:

Interface List
 17...00 05 9a 3c 78 00 ......Cisco Systems VPN Adapter
 12...00 16 44 ea 74 58 ......Dell Wireless 1395 WLAN Mini-Card

命令是:
route add 192.168.1.11 mask 255.255.255.255 192.168.100.12 metric 1 if 17

问题:
思科适配器上的IP不是静态的,我无法使用修改器-p(永久)路由添加当被删除并重新连接时,我需要查找NewIp并添加正确的路由:
route add 192.168.1.11 mask 255.255.255.255 «NewIP» metric 1 if 17
对我来说,每次都很容易(但很无聊)编写所有这些命令:

ipconfig  etc
route print etc
route add etc

我需要一个bat或powershell脚本来添加正确的路由。该脚本在Cisco适配器上查找ip并运行命令route add with Ip gateway established。

由于

PD索瑞我可怜的英语

3 个答案:

答案 0 :(得分:8)

我尝试了renegm的答案,而Index属性为我提供了错误的值。这对我有用(Juniper VPN在这里,但同样的问题) - 注意InterfaceIndex而不是Index:

$adapter=Get-WmiObject Win32_NetworkAdapterConfiguration|
    Where-Object { $_.Description -match "Juniper Network Connect Virtual Adapter"}
$Gateway=$adapter.IPaddress[0] 
$if=$adapter.InterfaceIndex

route add 192.168.1.3 mask 255.255.255.255 $Gateway metric 1 $if

答案 1 :(得分:4)

我解决了。 (我是PowerShell的新手,但问题非常简单)

$adapter=Get-WmiObject Win32_NetworkAdapterConfiguration|
    Where-Object { $_.Description -match "Cisco Systems VPN Adapter"}
$GateWay=$adapter.IPaddress[0] 
$if=$adapter.Index
route add 192.168.1.11 mask 255.255.255.255 $Gateway metric 1 if $if

答案 2 :(得分:1)

这是一个非常古老的讨论,但您可以使用以下PowerShell命令在连接到VPN后创建路由:

Add-VpnConnectionRoute -ConnectionName "You VPN Name Here" -DestinationPrefix 10.0.0.0/8

它适用于Windows 10。