Thursday, March 8, 2012

Remotely changing the default gateway

Recently I needed to change the default gateway on all the clients residing in a specific subnet. I was able to achieve the  wanted result in two different ways.

For a first bunch of Windows computers I remotely ran the following netsh script:
netsh -r 192.168.1.240 interface ip set address "Local Area Connection" gateway=192.168.1.1 gw=1
For this to work, you have to manually define the IP address of each computer to update. In the example the IP address of the computer is 192.168.1.240. Please note also that the name of your connection could not be "Local Area Connection" but anything else, so please check.

On a second group of hosts I decided to use Powershell, just for fun.

Here's the Powershell script I used:
$DefGateway = "192.168.1.1"
$pc_list = get-content "c:\pclist.txt"
foreach($pc in $pc_list)
    {
    $nics = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $pc -Filter "IPEnabled=TRUE"
    foreach($nic in $nics)
        {
        if($nic.ipaddress -match "192.168.1.") # fetch the right nic based on its IP address
            {
            $nic.SetGateways($DefGateway)
            }
        }
    }
As you can see netsh and powershell are two very powerful tools to administer the IP configuration of your clients. Many more configurations can be done through these tools, so do not hesitate to explore and test to better understand how they work and their extent.

1 comment:

  1. Tried the netsh script, my server ended up with no IP and subnet, though the gateway did get changed. Any idea?

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...