RHaslitt

Change DNS of WIFI NIC based on if it can reach Corporate

20 posts in this topic

I am newer to the scripting world.  I need to create a script that will change the "Connected Wireless Network Adapter" DNS settings based on if it can reach my internal DNS servers.  I am struggling with having it read the output txt file to be able to determine the correct adapter and having it change the dns settings using a variable.

 

My Biggest struggle is the then statement to run a netsh command to set the dns based on the information of the text file as the name of the wireless network connection may differ on all pc's.

 

Any help is greatly appreciated.

 

Share this post


Link to post
Share on other sites



Welcome to the forum.

Please show us what you have coded so far.


My UDFs, Abbrevs and Snippets
If you like my post, just click the like button :) 

Share this post


Link to post
Share on other sites

With ipconfig you will get all the info you need, parse that output and you will be able to get Wireless Adapter name.
Then with:

This one for Static IP, Netmask and Gateway:
netsh interface ip set address "Wireless Adapter Name" static 192.168.10.3 255.255.255.0 192.168.10.2

And this one for primary DNS server:
netsh interface ip set dns "Wireless Adapter Name" static 190.6.81.226 primary

Maybe there is a better way to do it, let others say it.

Regards
Alien.

Share this post


Link to post
Share on other sites

Thank you for the responses.

 

I am very new to this so I am a bit lost in everything going on.  I have a few different files i am working with for testing parts of the script.    I probably should have put more detail.  The issue is in Windows 7 the network adapters will put numbers after the name so I need to find the specific one that is connected. i.e.  My pc shows my adapter name as "Wireless Network Adapter 7" the user have the issue shows their's as "Wireless Network Adapter 2"  So far I have it doing a netsh to find the status of each adapter and their names and output that to a file.  I then need to read the file find the line that has Connected and Wireless in it.  Copy the name of the interface and then somehow put that copied name into my cmd command.  I want to write the script for any user's pc regardless of their wireless adapter name.

 

Thanks in advance!

 

 

 

Share this post


Link to post
Share on other sites

Here is what i have so far.  I have just crammed everything into one script for you to review.

#include <Process.au3>
$rc = _RunDOS("netsh int show int > c:\support\network.txt")

Dim $lineCounter
if Not @error Then
    $i= 0
    Do
        ;Location of Network Interfaces File
        $folder = C:\support
        While 1
            If @error Then
            ExitLoop

        $searchfile= FileFindFirstFile($folder & "*.*")
        ;Change dir to c:\support
        FileChangeDir($folder)
            ;Searches all files until it finds 'network.txt' file.
            While 1
                $file = FileFindNextFile
                If @error Then ExitLoop


                if $file= "network.txt" Then
                $foundFile = FileOpen($file,0) ; opens found file
                $lineCounter = 0

                ;Searching all lines for string needed
                While 1
                    $line = FileReadLine($foundFile) ; Reads a line
                    $lineCounter = $lin = 1 ; counts each line
                    if @error = -1 Then ExitLoop
                    If StringInStr($line, "connected & Wirelss*") > 0 Then????


Local $username = "adminaccount"
Local $domain = "@ComputerName"
Local $password = "**********"

#Func CommandRun($cmd)
    ; Ping 10.3.3.3 with a timeout of 10ms to verify the network
    Local $iPing = ping("10.3.3.3",10)

If $iPing Then; If value is greater than 0 the PC is on  Network
    RunAsWait($username,$domain,$password,0, "cmd.exe /c netsh interface ip set dns Wireless Network Connection x 10.3.3.2 index=1")
ElseIf @error Then; If there is a @error the PC is not on  Network
    RunAsWait($username,$domain,$password,0, "cmd.exe /c netsh interface ip set dns Wireless Network Connection x 8.8.8.8 index=1")
EndIf
EndFunc

Share this post


Link to post
Share on other sites

One suggestion, you can do it without writing to a file which is more slow, you can do it on memory.

Like this:
 

#include <Array.au3>
$cPID = Run(@ComSpec & " /c " & "netsh int show int", "", @SW_HIDE, $STDOUT_CHILD + $STDERR_CHILD)
$stdOut = ""
While ProcessExists($cPID)
        $stdError = StderrRead($cPID)
        $stdOut &= StdoutRead($cPID)
WEnd
ConsoleWrite($stdOut&@CRLF)

This also is going to make your script shortest.

Regards
Alien.

Share this post


Link to post
Share on other sites

Ok I have gotten alot further in my script.  Now i am stuck at trying to run a netsh command to change the DNS Server.  Here is what i have now..

 

#include <Process.au3>

#include <file.au3>

$rc = _RunDOS("netsh int show int > c:\support\network.txt")

;#comments-start
Dim $lineCounter
if Not @error Then
    $i = 0
    Do

    ;Location of Network Interfaces File
    $folder = "C:\support\"
    While 1
        If @error Then ExitLoop

        $searchfile= FileFindFirstFile($folder & "*.*")
        ;Change dir to c:\support
        FileChangeDir($folder)
            ;Searches all files until it finds 'network.txt' file.
            While 1
                $file = FileFindNextFile($searchfile)
                If @error Then ExitLoop
                ;;MsgBox(4096,"",$file) ;Used for testing

                If $file = "network.txt" Then
                    $foundFile = FileOpen($file,0) ; opens found file
                    $lineCounter = 0

                    ;Searching all lines for string needed
                    While 1
                        $line = FileReadLine($foundFile) ; Reads a line
                        $lineCounter = $line = 1 ; counts each line
                        If @error = -1 Then ExitLoop
                        If StringInStr($line, "disconnected") <1 and StringInStr($line, "Wireless") >0 Then
                            MsgBox(48,"Line Found",$line)
                            $strLength = StringLen($line)
                            MsgBox(48,"Line Found",$strLength)
                            $getIntFullName = StringMid($Line,47,$strlength)
                            msgbox(48,"Connection Name",$getIntFullName)


                        EndIf
                    Wend
                FileClose($foundFile)
                EndIf
            WEnd
        WEnd
    $i = $i + 1
    Until $i = 1

EndIf

Local $username = "*************"
Local $domain = @ComputerName
Local $password = "********"


CommandRun()

Func CommandRun()
    ; Ping 10.3.3.3 with a timeout of 10ms to verify the network
    $iPing = ping("10.3.3.3",10)

    If $iPing Then; If value is greater than 0 the PC is on  Network
        MsgBox(48,"Ping" ,$iping)
  
    RunAs('$username,$domain,$password,0, CommandRun''netsh interface ip set dns "$getIntFullName" dhcp')
    ElseIf @error Then; If there is a @error the PC is not on Network
    RunAsWait($username,$domain,$password,0, "cmd.exe /c netsh interface ip set dns Wireless Network Connection 7 static 8.8.8.8 primary") & RunAsWait($username,$domain,$password,0, "cmd.exe /c netsh interface ip set dns "**" 8.8.4.4 index=2")
    EndIf


EndFunc

Share this post


Link to post
Share on other sites
On 5/4/2016 at 11:32 AM, jguinch said:

Look at my signature,  the Network UDF should help you

That would be great but I would need to run as an admin..

Share this post


Link to post
Share on other sites

#10 ·  Posted

Ok..  So I am very close.  My issue is the information i am pulling from the text file is not resolving my my command prompt.  If i manually set the name  in my netsh command the script works great.  Here is the latest version of my script.

#include <Process.au3>
#include <file.au3>

$rc = _RunDOS("netsh int show int > c:\support\network.txt")

;#comments-start
Dim $lineCounter
if Not @error Then
    $i = 0
    Do

    ;Location of Network Interfaces File
    $folder = "C:\support\"
    While 1
        If @error Then ExitLoop

        $searchfile= FileFindFirstFile($folder & "*.*")
        ;Change dir to c:\support
        FileChangeDir($folder)
            ;Searches all files until it finds 'network.txt' file.
            While 1
                $file = FileFindNextFile($searchfile)
                If @error Then ExitLoop
                ;;MsgBox(4096,"",$file) ;Used for testing

                If $file = "network.txt" Then
                    $foundFile = FileOpen($file,0) ; opens found file
                    $lineCounter = 0

                    ;Searching all lines for string needed
                    While 1
                        $line = FileReadLine($foundFile) ; Reads a line
                        $lineCounter = $line = 1 ; counts each line
                        If @error = -1 Then ExitLoop
                        If StringInStr($line, "disconnected") <1 and StringInStr($line, "Wireless") >0 Then
                            $strIntLeft = StringMid(StringInStr($line, "Wireless"),1)
                            ;MsgBox(48,"Line Found",$strIntLeft)
                            $strLength = StringLen($line)
                            ;MsgBox(48,"Line Found",$strLength)
                            $getIntFullName = StringMid($Line,$strIntLeft -1,$strlength)
                            ;msgbox(48,"Connection Name",$getIntFullName)

                        EndIf
                    Wend
                FileClose($foundFile)
                EndIf
            WEnd
        WEnd
    $i = $i + 1
    Until $i = 1

EndIf

    Local $username = "*****"
    Local $domain = @ComputerName
    Local $password = "*****"

CommandRun()

Func CommandRun()
    ; Ping 10.3.3.3 with a timeout of 10ms to verify the network
    $iPing = ping("10.3.3.3",10)


    If $iPing Then; If value is greater than 0 the PC is on  Network
        MsgBox(48,"Ping" ,$iping); - Ping Results
        RunAsSet($username,$domain,$password)
        RunWait('cmd /k netsh interface ip set dns name="$getIntFullName" source=dhcp')
        MsgBox(48,"DHCP", "GooD") ;MsgBox(48, $domain, $username) - Gathers PC Name and UserName

    ;#comments-end
        ElseIf @error Then; If there is a @error the PC is not on Network
        MsgBox(48, "Error",@error)
        RunAsSet($username,$domain,$password)
            MsgBox(48, $domain, "Good")
        Run("cmd /k netsh interface ip set dns "$getIntFullName" static 8.8.8.8 primary')
        Run("cmd /k netsh interface ip set dns "$getIntFullName" 8.8.4.4 index=2')
            MsgBox(48,"External","BOOM!")
    ;#comments-end
    EndIf


EndFunc

 

Share this post


Link to post
Share on other sites

#11 ·  Posted (edited)

You need to use string concatenation:
 

Run("cmd /k netsh interface ip set dns " & $getIntFullName & " static 8.8.8.8 primary")

And you can't mix " and ' (double quotation marks and single quotation marks)

Besides I think the best way and the right way to do it is using @ComSpec like this:

Run(@ComSpec & " /k " & "netsh interface ip set dns " & $getIntFullName & " static 8.8.8.8 primary")


Also check my recommendation on post #7 you don't need to write to a file and then read that file.

Regards
Alien.

Edited by alien4u

Share this post


Link to post
Share on other sites

#12 ·  Posted

3 hours ago, RHaslitt said:

That would be great but I would need to run as an admin..

Of course yes, if you need to make some changes in the network configuration, you will need admin rights. It's true for all ways (netsh, registry, wmi...)

With my UDF, you can list all network adapters, check if each one is a wireless adapter or no, and then set the DNS address. I will post you an example on toworrow

 

Share this post


Link to post
Share on other sites

#13 ·  Posted

50 minutes ago, alien4u said:

You need to use string concatenation:
 

Run("cmd /k netsh interface ip set dns " & $getIntFullName & " static 8.8.8.8 primary")

And you can't mix " and ' (double quotation marks and single quotation marks)

Besides I think the best way and the right way to do it is using @ComSpec like this:

Run(@ComSpec & " /k " & "netsh interface ip set dns " & $getIntFullName & " static 8.8.8.8 primary")


Also check my recommendation on post #7 you don't need to write to a file and then read that file.

Regards
Alien.

Thank you very much..  This is what i ended up doing..

 

Local $cmdBegin = "netsh interface ipv4 set dnsservers "
Local $cmdEnd = " dhcp"

Local $cmdAll = $cmdBegin & '"' & $intFullName & '"' & $cmdEnd
    ; used for setting DNS back to DHCP when on internal network

Local $cmdBeginOut = "netsh interface ipv4 set dnsservers "
Local $cmdBeginOut2 = "netsh interface ipv4 add dns "
Local $cmdEndOut1 = " static 8.8.8.8 primary"
Local $cmdEndOut2 = " 8.8.4.4 index=2"

Local $cmdAllOut = $cmdBeginOut & '"' & $intFullName & '"' & $cmdEndout1
Local $cmdAllOut2 = $cmdBeginOut2 & '"' & $intFullName & '"' & $cmdEndout2
    ; Used for setting DNS to public DNS when off Network

    If $iPing Then; If value is greater than 0 the PC is on  Network
            ;MsgBox(48,"Ping" ,$iping); - Ping Results
        RunAsSet($username,$domain,$password)
        RunWait(@ComSpec & " /c " & $cmdAll,@SystemDir)
            ;MsgBox(48,"DHCP", "GooD") ;MsgBox(48, $domain, $username) - Gathers PC Name and UserName

    ;#comments-start
        ElseIf @error Then; If there is a @error the PC is not on  Network
            ;MsgBox(48, "Error",@error)
        RunAsSet($username,$domain,$password)
            MsgBox(48, $domain, "Good")
        Run(@ComSpec & " /c " & $cmdAllOut,@SystemDir)
        Run(@ComSpec & " /c " & $cmdAllOut2,@SystemDir)
            ;MsgBox(48,"External","BOOM!")
    ;#comments-end
    EndIf


EndFunc

 

Share this post


Link to post
Share on other sites

#14 ·  Posted

@RHaslitt

Your welcome I'm glad to help.

Anyways using @jguinch Network UDF will be probably better because it will have more and better errors checks.

And I insist: You don't need to write to a file the output of netsh and then read that file, you can do it without writing to a file like I show you in post #7.

Regards
Alien.

Share this post


Link to post
Share on other sites

#15 ·  Posted

On 04/05/2016 at 5:22 PM, RHaslitt said:

I need to create a script that will change the "Connected Wireless Network Adapter" DNS settings based on if it can reach my internal DNS servers

Is a Ping sufficient to consider that your DNS server is reachable ?

Share this post


Link to post
Share on other sites

#16 ·  Posted

So, here is a script that sets the DNS config for each wireless adapter :

#RequireAdmin
#Include "Network.au3"

Local $IPDNS = "192.168.1.100", $aDNSConfig = [$IPDNS]
Local $aNetAdapterList = _GetNetworkAdapterList()
For $i = 0 To UBound($aNetAdapterList) - 1
    If _IsWirelessAdapter($aNetAdapterList[$i][0]) Then _SetDNSServerSearchOrder($aNetAdapterList[$i][0], $aDNSConfig)
Next

 

Share this post


Link to post
Share on other sites

#17 ·  Posted (edited)

Sorry for jumping in with this somewhat destructive post, BUT:

 

Get your corporate Admin going to set up DHCP properly.

 

Then you don't need this all!

 

 

Regards, Rudi.

Edited by rudi

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post


Link to post
Share on other sites

#18 ·  Posted

1 hour ago, rudi said:

Sorry for jumping in with this somewhat destructive post, BUT:

 

Get your corporate Admin going to set up DHCP properly.

 

Then you don't need this all!

 

 

Regards, Rudi.

@rudi  I understand what you are saying.  The corporate network works fine which is why when it is on corp. it goes to dhcp it is when the user leave the corp network and works from home their home firewall(provided by their isp) that is causing the issue. I am very new at my job(first week) so i am still learning the in's and out's of the network and this script was something i was tasked with.

 

 

Share this post


Link to post
Share on other sites

#19 ·  Posted

7 hours ago, jguinch said:

Is a Ping sufficient to consider that your DNS server is reachable ?

 

6 hours ago, jguinch said:

So, here is a script that sets the DNS config for each wireless adapter :

#RequireAdmin
#Include "Network.au3"

Local $IPDNS = "192.168.1.100", $aDNSConfig = [$IPDNS]
Local $aNetAdapterList = _GetNetworkAdapterList()
For $i = 0 To UBound($aNetAdapterList) - 1
    If _IsWirelessAdapter($aNetAdapterList[$i][0]) Then _SetDNSServerSearchOrder($aNetAdapterList[$i][0], $aDNSConfig)
Next

 

@jguinch  Thank you for the the recommendations.  I will need to do more testing with the user to see if the ping is enough to decide it is on the corp network.  I know I can setup the task to run for the specific users for if it is connected to wireless x then run script.  I am very new to the scripting world with limited exp. using some powershell and vbs over the years for simple items like mapping drives.  I certainly will take some time and explore your suggestion just to understand more when I have some downtime(or maybe need to create another on the fly)

 

Thanks

Rick

Share this post


Link to post
Share on other sites

#20 ·  Posted (edited)

On 6.5.2016 at 3:34 PM, RHaslitt said:

@rudi  I understand what you are saying.  The corporate network works fine which is why when it is on corp. it goes to dhcp it is when the user leave the corp network and works from home their home firewall(provided by their isp) that is causing the issue. I am very new at my job(first week) so i am still learning the in's and out's of the network and this script was something i was tasked with.

 

 

Hi.

 

I assume, that "home firewall" is the internet router? I can only speak for the products common in Germany. All you need here is to set *BOTH* to DHCP: IP-address *AND* DNS settings, and everything is going right. (The default DHCP options each and every Home-Router will provide are sufficent)

Note: you will need to replace "dediziert" to your NLS spelling, I guess "dedicated"

Note2: Run "start as Administrator" (or use #requireadmin)


------ ip2dhcp-all-IF.cmd ----------
for /f "usebackq tokens=3" %%a in (`netsh int sh int^|find /i "dediziert"`) do netsh int ip set addr "%%a" dhcp
------ EOF -----

 


Regards, Rudi.

Edited by rudi

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now