Solved

Script to add a DNS server on the client NIC card? And map a drive aswell?

Posted on 2004-10-28
1,152 Views
Last Modified: 2012-08-14
I have a server running NT.

Each client machine has 2 DNS servers from our ISP.

I need to remove the primary one and update with another IP address, in a simple script that can be run when the users logs on.

How can this be done?



I would also like to know how I can run a script to map a network drive using an if else statement. First check if there is a drive assigned to "U". If yes, ignore script, If no add in the mapped drive. I know how to map a drive but dont know about if/else strings in these batch files.
0
Question by:georgecooldude
    25 Comments
     
    LVL 70

    Accepted Solution

    by:

    You can change the DNS IP Addresses with the VBScript below. It uses the Windows Managment Instrumentation to send the change request. So you'll need admin access over whatever you're running it on, and you'll need WMI there of course ;)

    It can be altered to run on a group of computers, at present it would slot quite happily into a Logon Script and run from there.

    ' This script replaces the DNS Server Search List in the Network Adapter Configuration.
    ' It will only replace DNS values for Static configuration, and will not run against hosts
    ' configured by DHCP.

    Option Explicit

    ' Variable Declaration

    Dim objWMIService, objNICConfig
    Dim strComputer, strDNSServer
    Dim arrNewDNSServer
    Dim colNICConfigs
    Dim intSetDNSServers

    ' Main Script

    ' For strComputer . refers to the current computer
    ' arrNewDNSServer is an array containing DNS Server Addresses to add

    strComputer = "."
    arrNewDNSServer = Array("192.168.0.1", "192.168.0.2")

    ' Set up interface to WMI and select all Interfaces with IP Enabled

    Set objWMIService = GetObject("winmgmts:" _
     & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

    Set colNicConfigs = objWMIService.ExecQuery _
     ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

    ' For each Interface with IP Enabled set the new DNS Servers
     
    For Each objNICConfig In colNICConfigs
          If objNICConfig.DHCPEnabled = FALSE Then
                intSetDNSServers = _
                objNICConfig.SetDNSServerSearchOrder(arrNewDNSServer)
                If intSetDNSServers = 0 Then
                      WScript.Echo "Replaced DNS server search order list."
                Else
                      WScript.Echo "Unable to replace DNS server search order list."
                End If
          End If
    Next

    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    For the drive mapping you get lots more choice.

    Visual Basic:

    Option Explicit

    Dim strDrive, strSharePath
    Dim bolDrive

    strDrive = "N:"
    strSharePath = "\\server\share"

    Set objNetwork = CreateObject("WScript.Network")
    Set objFileSystem = CreateObject("Scripting.FilesystemObject")

    bolDrive = objFileSystem.DriveExists(strDrive)

    If (bolDrive = FALSE) Then
        objNetwork.MapNetworkDrive strDrive, strSharePath
    End If

    Kixtart:

    If Exist("N:")
       Use "N:" "\\Server\Share"
    EndIf

    DOS:

    @echo off
    If Not Exist N: net use n: \\server\share
    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    Oops... Kix bit above should be:

    If Not Exist("N:")
       Use "N:" "\\Server\Share"
    EndIf
    0
     
    LVL 5

    Expert Comment

    by:map000
    ... or you can use dhcp for clients (dhcp server on the Nt server) and make changes when needed centralized and more flexible (from scope options)
    for exemple you need to have all client computers running when you use scripts (dhcp will provide the setting at system startup)
    also it's a better ideea to use your nt server as the Dns server for your clients (and configure it to forward queries to the ISP dns servers)
    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    He's in the process of upgrading to Windows 2003, so the NT server will soon disapear ;)

    I agree completely about setting up DHCP.
    0
     
    LVL 5

    Author Comment

    by:georgecooldude
    Chris thanks for your suggestions.

    I will try the scripts out. On the DNS script:

    "  WScript.Echo "Unable to replace DNS server search order list.""
    How can I put in a prompt that requires the user to press enter? I would like to say. ...blah blah contact the IT department.

    As you know I am migrating from NT. I thought this would be the best way to upgrade without having to go through every single office in the building updating computers. The upgrade has to be silent with users not knowing its happening.  It also occured I need to change the domain name from <NTdomainName> to <2003NewDomainName> - Can this be done in a script? That would require a reboot aswell. How can I automate the process of renaming the domain with as little input and disruption for the end users who only have the most basic of computer skills
    0
     
    LVL 5

    Author Comment

    by:georgecooldude
    map000, we are upgrading to 2003 so the NT box will soon be a lump of useless metal. (Sure there will be another role for it)

    And I like the DHCP idea alot except I am not allowed to set that up until a later date.
    0
     
    LVL 70

    Expert Comment

    by:Chris Dent
    Before anything else, can you confirm that the users are running Windows 2000 or XP?

    Scripting re-joining a computer to a domain isn't advisable as you'd have to include in the script an account and password that has the permissions to do so.

    For the DNS Script it's pretty flexible, any thoughts on how you want to run it?

    Logon Script is slow but probably quite reliable.
    Centrally is fast and allows greater flexibility in error reporting but might not catch everyone.

    To answer the bit above, this will deal with it:

    If intSetDNSServers = 0 Then
          MsgBox "Replaced DNS server search order list."
    Else
          MsgBox "An error occurred while processing the script." & _
          " Please contact your System Administrator.",,"Error"
    End If

    If you didn't want to include the success message either then this will only print on error:

    If not (intSetDNSServers = 0) Then
          MsgBox "An error occurred while processing the script." & _
          " Please contact your System Administrator.",,"Error"
    End If
    0
     
    LVL 5

    Author Comment

    by:georgecooldude
    We are slowly upgrading our machines to XP Pro.

    I think the following:

    8 XP Pro machines
    2 XP Home
    10 Windows 2000 machines

    And the rest range from:
    Windows NT, 95, 98 and M.E.

    Oh and 1 Apple Mac


    We've 60-70 machines in total so it looks like the majority are running legacy systems. :(

    Is there any way around having to go to each and every machine. I've been told this is something we would do as a very last resort.

    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    Well we can but try... give me a little while.. I'll give you a script that can tell you which machines can and can't be changed automatically.

    The Apple Mac I can't help you with at all though.
    0
     
    LVL 5

    Expert Comment

    by:map000
    Chris-Dent answered your question
    you should give him the points and open a different thread (it's becoming too complex)
    0
     
    LVL 5

    Author Comment

    by:georgecooldude
    Well, I see it as an evoled thread. It has been assigned a max of 500 points because it is an "extremely difficult" question as said on the ask an expert page

    "extremely difficult (500 points)"
    "difficult (250 points)"

    Creating multiply threads makes it hard to keep up with what was said where and you end up asking the same questions over again in.

    Unless Chris would like to split the thread into a new one I'll leave it as it is.
    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    Busy morning...

    Not bothered about opening a new question for it. I already have a network scanner script, just a matter of ripping out some of it's more interesting features...

    I haven't had time to alter it significantly though, but if you feed it a list of computer names (in a file called computers.txt) it'll try and connect to WMI on each  of them and give you a few bits of information in a results.txt file (semi-colon delimited text).

    If you can't connect it'll tell you which, those will be the ones you have to run around changing things on.

    It's written in Perl, so you'll need to download that from:

    www.activestate.com

    Then run it from the command line with perl wmi.pl

    If you want to alter the Input / Output file names just edit them in the script itself.

    #WMI.pl# (don't save the Start and End lines)

    ------------------------------------------Start------------------------------------------

    #!/usr/bin/perl

    # Computer Scanner Version 3.1.0
    #
    # Author: Chris Dent
    # Last Modified: 29/09/2004


    # Included Modules

    use Net::Ping;
    use Win32::OLE qw(in);

    # Syntax Pragma

    use strict;

    # Debugging Options

    # use warnings;
    # use diagnostics;

    # Global Variables

    my $InputFile = "computers.txt";
    my $OutputFile = "results.txt";

    our (@ComputerList, @Input);
    our ($Host, $PingHost);
    our ($WMIUserName, $WMIOSName, $WMIComputerName);

    # Functions and Subroutines

    sub PingHost

    # Pings the host by name and returns True or False

    {
          my $PingObject = Net::Ping->new("icmp");
          if ($PingObject->ping($Host, 2))
          {
                $PingHost = 1;
          }
          else
          {
                $PingHost = 0;
          }
    }

    sub WMIConnect

    # Connect to the Windows Management Instrumentation and try to grab
    # Current User and OS Name

    {
          my $WMIServices = Win32::OLE->GetObject("winmgmts:{impersonationLevel=impersonate,(security)}//$Host");
          my $ComputerSystem = $WMIServices->instancesof("Win32_ComputerSystem");
          foreach my $Data (in($ComputerSystem))
          {
                $WMIUserName = $Data->{UserName};
          }
          my $OperatingSystem = $WMIServices->instancesof("Win32_OperatingSystem");      
          foreach my $Data (in($OperatingSystem))
          {
                my $OSName = $Data->{Name};
                my @OSData = split(/\|/, $OSName);
                $WMIOSName = $OSData[0];
                $WMIComputerName = $Data->{CSName};
          }
    }

    sub CleanData

    # Sub to Sort the Computer List from the original file data
    # Requires extending to deal with multiple formats

    {
          my $Counter = 0;
          
          foreach my $Line (@Input)
          {
                my @ComputerElement = split(/\t/, $Line);
                if ($ComputerElement[0] ne "\n")
                {
                      $ComputerList[$Counter] = $ComputerElement[0];
                      $Counter = ++$Counter;
                }
          }
    }

    sub ByNumber

    # This sorts the elements in the hash (by port number in this case)
    # Just makes the port scan run in numerical order

    {
          if ( $a < $b )
          {
                -1
          }
          elsif ( $a > $b )
          {
                1
          }
          else
          {
                0
          }
    }

    # Main Script begins here

    # Open Input File and Read Contents

    open(INPUTFILE, "$InputFile") or die("Can't open $InputFile: $!");
    @Input = <INPUTFILE>;
    close(INPUTFILE);

    # Open Output File for Writing (>) - a nice character delimited list
    # Locks the file for exclusive access (you can't see it until it's done)

    open(OUTPUTFILE, ">$OutputFile") or die("Can't open $OutputFile: $!");
    flock(OUTPUTFILE, 2);

    # Data cleaning - assumes data is tab delimited (default export from AD)
    # or just a simple list, either way, it's going to chop off everything
    # except the computer name

    CleanData();

    # Skip the first line - default export contains column names - Remove comment to enable (#)

    # shift(@ComputerList);

    # Dig out lots of information

    foreach $Host (@ComputerList)
    {
          chomp($Host);
          print "$Host";
          print OUTPUTFILE "Ping Name: $Host;";
          
          PingHost();
          if ($PingHost == 1)
          {
                print OUTPUTFILE "Ping Succeeded;";
          }
          else
          {
                print OUTPUTFILE "Ping Failed;";
          }
          
          if ($PingHost == 1)
          {
                eval { WMIConnect(); };
                if ($@)
                {
                      print ": WMI could not establish a connection";
                      print OUTPUTFILE ";;;"
                }
                else
                {
                      print OUTPUTFILE "$WMIOSName;";
                      print OUTPUTFILE "WMI Name: $WMIComputerName;";
                      print OUTPUTFILE "$WMIUserName;";
                }
                
          }
          else
          {
                print ": Unable to Ping Host";
          }
          print "\n";
          print OUTPUTFILE "\n";
    }

    close(OUTPUTFILE);

    ------------------------------------------End------------------------------------------
    0
     
    LVL 5

    Author Comment

    by:georgecooldude
    Thanks Chris,

    This is easyier for me to read as I've got some basic php skills. I think perl is similar to php.

    I'll give it a go and let you know how it works.
    0
     
    LVL 5

    Author Comment

    by:georgecooldude
    Do I just need perl installed on the server?


    Oh and is it possible to control another machine from the command line? I found the following in another thread:
    Say I open the command prompt but want to send the command down to a client machine. This is what I would send:

    netdom join {COMPUTERNAME} /domain:{DOMAINNAME} /userd:{ADMINISTRATOR} /passwordd:{PASSWORD}

    ---

    I'm trying to explore all options so I can put it forward to my head of department.
    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    No, just perl installed wherever you run the script from.

    Yes, you can use that command, but as I mentioned earlier you have to add the Administrator password in plain text, which makes it fair game for anyone. I would not recommend that approach.

    At least with the "run around and do it manually" approach you know that it's done ;)
    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    Oh sorry, misread that. No you can't control another machine from the command prompt as far as I know.
    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    Besides, you have way too much variety in Operating Systems to reliably change things using scripts.

    If you do use the DNS Change script I recommend you run it centrally and add logging options so you can see where it's been successful...
    0
     
    LVL 5

    Author Comment

    by:georgecooldude
    Oh yeah I forgot about the plain text password thing with the standard scripts.

    Now I think of it I will also have to do something with the user profiles. For instance on my XP Machine when i log onto my windows 2003 server I've a new profile locally created on my machine. As such things like my outlook.pst aren't there. Nor my desktop icons/settings.

    Now I thinking if I create scripts to move all this aswell its going to get very complicated. I seem to solve 1 problem and up comes another...
    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    You'd be better off visiting the PC...

    Then you can do the DNS Changes, any Domain Name changes, log in as the user (to create a blank profile) and finally copy their own user profile over.

    It might take time, but you'll know that it's working...
    0
     
    LVL 5

    Author Comment

    by:georgecooldude
    Chris this is a good point.

    I have had a talk with a few people.

    We thought we could create a few .bat scripts of somesort that we can run on a floppy on each machine we visit.

    Is there a dos compatiable way i could remove DNS servers and add in a new one?
    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    You can run the vbscript from the command line.

    Just set everything you want to set in the file itself, the use:

    cscript dnsconfig.vbs

    Or use that line in a batch file...

    The script at the top simply overwrites the existing list of servers with a new one. I haven't tested it on Windows 9x though, haven't had one of those installed for quite some time ;)

    The Profile copy is slightly (not very though) tricky since it locks the NTUser.dat file until the PC reboots (and you have to log on once to create the blank profile to start with), you might be able to get away with skipping that file though.
    0
     
    LVL 5

    Author Comment

    by:georgecooldude
    ah ok thanks!

    I was wondering how to run vb scrtip from a batch file
    0
     
    LVL 70

    Expert Comment

    by:Chris Dent

    cscript <script name> for Command Prompt

    wscript <script name> for Windows Shell

    Double Click in windows is associated with wscript.

    ;)
    0
     
    LVL 5

    Author Comment

    by:georgecooldude
    Cool!

    I will right those down for future referrence. :-)
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Free Trending Threat Insights Every Day

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Preface Having the need * to contact many different companies with different infrastructures * do remote maintenance in their network required us to implement a more flexible routing solution. As RAS, PPTP, L2TP and VPN Client connections are no…
    I guess it is not common knowledge to most Wintel engineers/administrators: If you have an SNMP-based monitoring system in your environment (and it's common to have SNMP or Syslog) it's reasonably easy to enable monitoring of the Windows Event logs,…
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    how to add IIS SMTP to handle application/Scanner relays into office 365.

    884 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now