How to get the gateway for a specific route on command line in Windows?

0

Is there a way to print out the gateway for a specific route (not interface) in Windows (in this case Win7)? I'd need to add a route dynamically in an OpenVPN _up script, but since the gateway is dynamically assigned when the connection is formed, I can't script it statically.

There also appears to potentially be some environment variables (route_vpn_gateway?) available for the _up scripts, but I haven't managed to get them to work.

I suppose I gan use awk/grep from GnuWin tools and parse the 'routes' output, but perhaps there is a cleaner/easier way?

Ville

Posted 2013-01-10T01:54:32.977

Reputation: 1 692

This works (using GnuWin32 utilities), but is [really] ugly :D

routes | grep -P "192\.168\.1\.0\s+255\.255\.255\.0\s+(\d+\.\d+\.\d+\.\d+)" | awk "{print $3}"

(The VPN connection in question pushes a route to 192.168.1.0/24 address space.)

Perhaps someone has a more elegant solution to my question.. :)

– Ville – 2013-01-10T02:00:51.747

Using the above grep/awk I came up with this. It works, but like I said, it's awfully ugly and I'm almost certain there's a neater way – probably by accessing data available for the _up script. Anyone? Anyone?

– Ville – 2013-01-10T03:48:26.040

Answers

0

You can easily use powershell:

PS C:\Users\mmoor> $RouteTable = Get-WmiObject Win32_IP4RouteTable
PS C:\Users\mmoor> $RouteTable[0].Mask
0.0.0.0
PS C:\Users\mmoor> $RouteTable[0].Destination
0.0.0.0
PS C:\Users\mmoor> $RouteTable[0].NextHop
<Gateway Address>

Compare this w/ running ROUTE PRINT from a windows command line. Powershell is a verbose scripting language, so you can easily update the openvpn client config script, I'm assuming this is what you're trying to do. It's also object oriented based as well.

I would do something as follows:

1)Grab the routing table from wmi (shown above)

2)Each Routing table entry is one entry in an array (hence the [0] after the variable above)

3)Do a foreach on the array until you find the IP Address you're looking for

4)Get the NextHop member from the RouteTable entry and store it

5)Read in the OpenVPN client config file (using get-content in powershell will create a string array of the file)

6)Iterate through the string array until you find the string you are supposed to replace, then replace the string and save the file.

Hope this points you in the right direction.

MDMoore313

Posted 2013-01-10T01:54:32.977

Reputation: 4 874