Solved

Need a vbScript to change HOSTS file  when vpngui.exe is running and delete the line when vpngui.exe is stopped.

Posted on 2008-10-09
15
1,404 Views
Last Modified: 2012-05-05
Im a total new to vbscript.!

Need to delete line in HOSTS file when vpngui.exe is stopped.
I have made the vbscript so far, just can't get it to delete the line when vpngui.exe is stopped.!






Const ForReading = 1 ' Open file read only

Const ForWriting = 2 ' Open file read write

 

Dim objFso, objFile, strFileName, strText, strNewText

 

' It might be nice at some point to get this via the environment variables

strFileName = "C:\windows\system32\drivers\etc\hosts" 

 

Set objFso = CreateObject("Scripting.FileSystemObject")

 

' Open the File and read into string

Set objFile = objFso.OpenTextFile(strFileName, ForReading) 

strText = objFile.ReadAll 

objFile.Close ' close the file

 

' Create a regular expression

Dim re

Set re = New RegExp 

re.Pattern = ".*srv01\.office\.local.*\n" 

re.IgnoreCase = True

re.Global = True

 

' Add the entry 

strNewText = re.Replace(strText, "") 

 strNewText = strNewText + "192.168.30.10    srv01.office.local" 

 

' Write out file (deletes old file)

Set ObjFile = objFSO.OpenTextFile(strFileName, ForWriting) 

objFile.WriteLine strNewText ' Write out the string contents

objFile.Close

 

' Flush the DNS Cache so change will take effect

Set WshShell = CreateObject("WScript.Shell") 

WshShell.Run "ipconfig /flushdns"

MsgBox("Starter forbindelse til serveren - Vent venligst")

WshShell.Run "ping -n 16 127.0.0.1 >NUL"

WshShell.Run "C:\WINDOWS\system32\mstsc.exe /v:srv01.office.local /f"

Open in new window

0
Comment
Question by:lk-data
  • 7
  • 5
  • 3
15 Comments
 
LVL 67

Expert Comment

by:sirbounty
ID: 22677890
You would need to monitor the process...something like this from the scripting guys at Microsoft:

You can grab windows folder using:

Dim objShell : Set objShell = CreateObject("Wscript.Shell")
WinDir = objShell.ExpandEnvironmentStrings("%windir%")
strFileName = WinDir & "\system32\drivers\etc\hosts"


strComputer = "."
 

Set objWMIService = GetObject _

    ("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")

 

objWMIService.Create "vpngui.exe", null, null, intProcessID
 

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
 

Set colItems = objWMIService. _

    ExecNotificationQuery("Select * From __InstanceDeletionEvent " _ 

            & "Within 1 Where TargetInstance ISA 'Win32_Process'")

Do 

    Set objProcess = colItems.NextEvent

    If objProcess.TargetInstance.ProcessID = intProcessID Then

        'update HOSTS file

    End If

Loop

Open in new window

0
 
LVL 1

Author Comment

by:lk-data
ID: 22678107
Hi thanks for the fase answer..

I have read and tryed this, but I can't get it to work together with the script I have made in the top..!

can you help me merge those scripts så they work as one script ?

Im total newbie in this, and need this asap.

Thanks in advance..



0
 
LVL 67

Expert Comment

by:sirbounty
ID: 22678147
The code assumes that you're launching vpngui using this script.  If that's not what you're after, let me know.
The reason is that by launching it from the script, it can grab the ID of the running process (which will change each time it's loaded).
Then when a process is terminated, it compares that ID with the stored ID of vpngui.  If they match, then it runs your sub...
Const ForReading = 1 ' Open file read only

Const ForWriting = 2 ' Open file read write

Dim objFso, objFile, strFileName, strText, strNewText

Dim objShell : Set objShell = CreateObject("Wscript.Shell")

WinDir = objShell.ExpandEnvironmentStrings("%windir%")

strFileName = WinDir & "\system32\drivers\etc\hosts" 

Set objShell = Nothing
 

strComputer = "."

 

Set objWMIService = GetObject ("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")

objWMIService.Create "vpngui.exe", null, null, intProcessID

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

 

Set colItems = objWMIService. _

    ExecNotificationQuery("Select * From __InstanceDeletionEvent " _ 

            & "Within 1 Where TargetInstance ISA 'Win32_Process'")

Do 

    Set objProcess = colItems.NextEvent

    If objProcess.TargetInstance.ProcessID = intProcessID Then

        Main()

    End If

Loop
 

Sub Main()

Set objFso = CreateObject("Scripting.FileSystemObject")

 

' Open the File and read into string

Set objFile = objFso.OpenTextFile(strFileName, ForReading) 

strText = objFile.ReadAll 

objFile.Close ' close the file

 

' Create a regular expression

Dim re

Set re = New RegExp 

re.Pattern = ".*srv01\.office\.local.*\n" 

re.IgnoreCase = True

re.Global = True

 

' Add the entry 

strNewText = re.Replace(strText, "") 

 strNewText = strNewText + "192.168.30.10    srv01.office.local" 

 

' Write out file (deletes old file)

Set ObjFile = objFSO.OpenTextFile(strFileName, ForWriting) 

objFile.WriteLine strNewText ' Write out the string contents

objFile.Close

 

' Flush the DNS Cache so change will take effect

Set WshShell = CreateObject("WScript.Shell") 

WshShell.Run "ipconfig /flushdns"

MsgBox("Starter forbindelse til serveren - Vent venligst")

WshShell.Run "ping -n 16 127.0.0.1 >NUL"

WshShell.Run "C:\WINDOWS\system32\mstsc.exe /v:srv01.office.local /f"

End Sub

Open in new window

0
 
LVL 67

Assisted Solution

by:sirbounty
sirbounty earned 500 total points
ID: 22678273
If not, this one should check for 'only' that process and run your sub when it terminates...

Realize that this script does run 'all' the time.  It's real-time monitoring and can be terminated by any user looking hard enough to do so (with the right permissions, of course).
The polling interval is just after the "Within" - where in the script below it's Within 1, you would change that to "Within 5" to change the polling interval to testing every 5 seconds, instead of every 1 (but either way the processor utilization should still be negligible).
Const ForReading = 1 ' Open file read only

Const ForWriting = 2 ' Open file read write

Dim objFso, objFile, strFileName, strText, strNewText

Dim objShell : Set objShell = CreateObject("Wscript.Shell")

WinDir = objShell.ExpandEnvironmentStrings("%windir%")

strFileName = WinDir & "\system32\drivers\etc\hosts" 

Set objShell = Nothing
 

strComputer = "."

strProcess = "vpngui.exe"
 

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

 Set colItems = objWMIService. _

    ExecNotificationQuery("Select * From __InstanceDeletionEvent " _ 

            & "Within 1 Where TargetInstance ISA 'Win32_Process'" _

            & " and TargetInstance.Name = '" & strProcess & "'")

Do 

    Set objProcess = colItems.NextEvent

    Main()

Loop
 

Sub Main()

Set objFso = CreateObject("Scripting.FileSystemObject")

 

' Open the File and read into string

Set objFile = objFso.OpenTextFile(strFileName, ForReading) 

strText = objFile.ReadAll 

objFile.Close ' close the file

 

' Create a regular expression

Dim re

Set re = New RegExp 

re.Pattern = ".*srv01\.office\.local.*\n" 

re.IgnoreCase = True

re.Global = True

 

' Add the entry 

strNewText = re.Replace(strText, "") 

 strNewText = strNewText + "192.168.30.10    srv01.office.local" 

 

' Write out file (deletes old file)

Set ObjFile = objFSO.OpenTextFile(strFileName, ForWriting) 

objFile.WriteLine strNewText ' Write out the string contents

objFile.Close

 

' Flush the DNS Cache so change will take effect

Set WshShell = CreateObject("WScript.Shell") 

WshShell.Run "ipconfig /flushdns"

MsgBox("Starter forbindelse til serveren - Vent venligst")

WshShell.Run "ping -n 16 127.0.0.1 >NUL"

WshShell.Run "C:\WINDOWS\system32\mstsc.exe /v:srv01.office.local /f"

End Sub

Open in new window

0
 
LVL 1

Author Comment

by:lk-data
ID: 22678365
I run this script automatic when starting Cisco VPN Client (vpngui.exe). Then the script must add  this line in The HOSTS file: 192.168.30.10    srv01.office.local

And wait 11 sec and then run : C:\WINDOWS\system32\mstsc.exe /v:srv01.office.local /f

So far so good :-)

When I close the vpngui.exe, I need the script to Delete the line again from the HOSTS file.

Is that possible ?
 
Thanks in advance.
0
 
LVL 67

Expert Comment

by:sirbounty
ID: 22678382
So far so good?  Which script?

Post the full working one you've decided to go with and I'll see what I can come up with (regex is not my specialty though! :^)

And yes, I use Cisco VPN as well...
0
 
LVL 1

Author Comment

by:lk-data
ID: 22678514
This script, the same as in the top.

It adds the line in HOSTS file, but after that I can't get it to do the rest..

(I'll drive from my work to home now, take a look when im home this evening.)

Const ForReading = 1 ' Open file read only

Const ForWriting = 2 ' Open file read write

 

Dim objFso, objFile, strFileName, strText, strNewText

 

' It might be nice at some point to get this via the environment variables

strFileName = "C:\windows\system32\drivers\etc\hosts" 

 

Set objFso = CreateObject("Scripting.FileSystemObject")

 

' Open the File and read into string

Set objFile = objFso.OpenTextFile(strFileName, ForReading) 

strText = objFile.ReadAll 

objFile.Close ' close the file

 

' Create a regular expression

Dim re

Set re = New RegExp 

re.Pattern = ".*srv01\.office\.local.*\n" 

re.IgnoreCase = True

re.Global = True

 

' Add the entry 

strNewText = re.Replace(strText, "") 

 strNewText = strNewText + "192.168.30.10    srv01.office.local" 

 

' Write out file (deletes old file)

Set ObjFile = objFSO.OpenTextFile(strFileName, ForWriting) 

objFile.WriteLine strNewText ' Write out the string contents

objFile.Close

 

' Flush the DNS Cache so change will take effect

Set WshShell = CreateObject("WScript.Shell") 

WshShell.Run "ipconfig /flushdns"

MsgBox("Starter forbindelse til serveren - Vent venligst")

WshShell.Run "ping -n 16 127.0.0.1 >NUL"

WshShell.Run "C:\WINDOWS\system32\mstsc.exe /v:srv01.office.local /f"

Open in new window

0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 67

Expert Comment

by:sirbounty
ID: 22678738
Ok - I have to head back to work myself, so I'll check this again in a little while...
0
 
LVL 21

Expert Comment

by:AmazingTech
ID: 22679594
Why even go through that hassle for hard coding an IP address into the HOSTS file to use MSTSC?

WshShell.Run "C:\WINDOWS\system32\mstsc.exe /v:192.168.30.10 /f"
0
 
LVL 1

Author Comment

by:lk-data
ID: 22684498
Thanks for the answer AmazingTech.

But it's not gonna work alone, because they need that address because they somtimes they stop the  MSTSC and then they can't remember the IP address, but they have learned the DNS name over the years. And they use that address on two other locations where there are LAN 2 LAN VPN, so they can't have the entry in the HOSTS file when not using the Cisco VPN Client.

0
 
LVL 21

Expert Comment

by:AmazingTech
ID: 22684690
So when and how does this script to add the host entry gets run?

Your comment on 10.09.2008 at 06:54AM PDT, ID: 22678365. This script would only run your connection to 192.168.30.10 when running LAN VPN. I would assume you would have an alternate script or shortcut when users are on LAN 2.
0
 
LVL 21

Expert Comment

by:AmazingTech
ID: 22684808
Give them this to run when they want to make the remote connection.
strComputer = "."

Set objWMIService = GetObject("winmgmts:" _

    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
 

Set colProcessList = objWMIService.ExecQuery _

    ("Select * from Win32_Process Where Name = 'VPNGUI.exe'")
 

MSTSCConnect="srv01.office.local"

For Each objProcess in colProcessList

    MSTSCConnect="192.168.30.10"

    EXIT FOR

Next

Set WshShell = CreateObject("WScript.Shell")
 

WshShell.Run "C:\WINDOWS\system32\mstsc.exe /v:" & MSTSCConnect & " /f"

Open in new window

0
 
LVL 1

Author Comment

by:lk-data
ID: 22685080
Thanks again AmazingTech. But I realy need the HOSTS file to get this entry added in it when I run this script, and the entry removed, when I stop vpngui.exe.

That must be possible..

0
 
LVL 1

Author Comment

by:lk-data
ID: 22685264
sirbounty, I'm trying your latest file, I dosn't work right, but I try to work on it for a while, I'll return later to day, if I got it to work or not.!

0
 
LVL 1

Accepted Solution

by:
lk-data earned 0 total points
ID: 22685821
Thansk sirbounty, I got your code to work..  But without your input, I could not get it to work..

Copy of the code that workes.


Const ForReading = 1 ' Open file read only

Const ForWriting = 2 ' Open file read write

Dim objFso, objFile, strFileName, strText, strNewText

Dim objShell : Set objShell = CreateObject("Wscript.Shell")

WinDir = objShell.ExpandEnvironmentStrings("%windir%")

strFileName = WinDir & "\system32\drivers\etc\hosts" 

Set objShell = Nothing

 

strComputer = "."

strProcess = "vpngui.exe"

 

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

 Set colItems = objWMIService. _

    ExecNotificationQuery("Select * From __InstanceDeletionEvent " _ 

            & "Within 1 Where TargetInstance ISA 'Win32_Process'" _

            & " and TargetInstance.Name = '" & strProcess & "'")
 
 
 

Set objFso = CreateObject("Scripting.FileSystemObject")

 

' Open the File and read into string

Set objFile = objFso.OpenTextFile(strFileName, ForReading) 

strText = objFile.ReadAll 

objFile.Close ' close the file

 

' Create a regular expression

Dim re

Set re = New RegExp 

re.Pattern = "[\r\n]+.*srv01\.office\.local.*[\r\n]+" 

re.IgnoreCase = True

re.Global = True
 

 

' Add the entry 

strNewText = re.Replace(strText, "") 

 strNewText = strNewText + "192.168.30.10    srv01.office.local" 

 

' Write out file (deletes old file)

Set ObjFile = objFSO.OpenTextFile(strFileName, ForWriting) 

objFile.WriteLine strNewText ' Write out the string contents

objFile.Close

 

' Flush the DNS Cache so change will take effect

Set WshShell = CreateObject("WScript.Shell") 

WshShell.Run "ipconfig /flushdns"

MsgBox("Starter forbindelse til serveren - Vent venligst")

WScript.Sleep(11000)

WshShell.Run "C:\WINDOWS\system32\mstsc.exe /v:srv01.office.local /f"
 

Do 

    Set objProcess = colItems.NextEvent

    Main()

Loop
 

Sub Main()
 

Set objFso = CreateObject("Scripting.FileSystemObject")

 

' Open the File and read into string

Set objFile = objFso.OpenTextFile(strFileName, ForReading) 

strText = objFile.ReadAll 

objFile.Close ' close the file
 

      ' Remove the entry if found

      strNewText = re.Replace(strText, "") 
 

' Write out file (deletes old file)

Set ObjFile = objFSO.OpenTextFile(strFileName, ForWriting) 

objFile.WriteLine strNewText ' Write out the string contents

objFile.Close

wscript.quit

End Sub

Open in new window

0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Script to copy or move mouse-selected collection of files plus targets referenced by shortcuts (.lnk) The purpose of this article is to help illuminate the real challenges and options available (where they may exist) for utilizing simple scriptin…
Well hello again!  Glad to see you've made it this far without giving up.  In this, the fourth installment of my popular series, I'm going to cover functions and subroutines, what they are, and why they are useful.  Just in case you stumbled onto th…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

743 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

13 Experts available now in Live!

Get 1:1 Help Now