VB script on Cisco Anyconnect VPN - vbscript

I am new to use VB script. I am using the below code to connect my VPN. But the problem is that after entering "select" button in VPN client, the second page display is depending on Network Speed. Sometimes it is loaded within 4 sec, sometimes after 10 sec. Is there any code where i can get the VPN is fully loaded or not (like BUSY command for IE).
set WshShell=Wscript.CreateObject("Wscript.Shell")
WshShell.Run("""C:\\Program Files\Cisco\Anyconnect\vpnui.exe""")
WScript.Sleep 500
WshShell.SendKeys "{ENTER}"
WScript.Sleep 500
WshShell.SendKeys "username"
WshShell.SendKeys "rsa_no"
WshShell.SendKeys "password"
WScript.Sleep 500
WshShell.SendKeys "{ENTER}"

Whilst not vb script, I think this approach should still work.
I have the vpncli directory in my %path%
I have a batch file:
vpncli.exe connect xyz.123.com -s < d:\vpncreds.txt
with the credentials in a separate file (d:\vpncreds.txt):
username
password
y
Note: you need an empty line at the end.
This works fine here, and wonder if you take the credentials out of your VB script and put them in a separate file, it might achieve what you need to.
Also, if your credentials change, you only need to change the one file, and not the potential handful of script files if you access the vpn in multiple scripts.

Try my code below. Note that you may have to adjust sleep times (in milliseconds). To see what's happening in the command prompt, change the 2 in the 9th line to a 1.
Dim host, username, password, pathToClient
host = "yourHostURL"
username = "yourUsername"
password = "yourPassword"
pathToClient = "C:\Program Files {(}x86{)}\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"
Set ws = WScript.CreateObject("WScript.Shell")
ws.run("TASKKILL.exe /F /IM vpnui.exe"), 0, false
ws.run("cmd.exe"), 2, false
ws.AppActivate("Command Prompt")
WScript.Sleep 300
ws.SendKeys """" & pathToClient & """ connect " & host & "~"
WScript.Sleep 1000
ws.SendKeys(username & "~")
WScript.Sleep 50
ws.SendKeys(password & "~")
ws.run("TASKKILL.exe /F /IM cmd.exe"), 0, false

Here is an improved version that doesn't wait for sleep timeouts, i.e. connects as soon as the window becomes visible. This works with the latest version of AnyConnect (4.10 as of writing).
' Script to automatically connect to Cisco AnyConnect.
' This script assumes that you have already set up your connection.
Const Password = "[YOUR PASSWORD]" ' Enter your password here
Const ConnectionUrl = "[YOUR CONNECTION URL]" ' Enter the URL of your endpoint (without HTTP prefix)
' Copy password to clipboard in case something goes wrong (to connect manually)
CopyToClipboard(Password)
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe"""
ActivateWindow("Cisco AnyConnect Secure Mobility Client")
WshShell.SendKeys "{ENTER}"
ActivateWindow("Cisco AnyConnect | " + ConnectionUrl)
WshShell.SendKeys "{TAB}"
WshShell.SendKeys Password
WshShell.SendKeys "{ENTER}"
Function ActivateWindow(title)
Const Step = 100
Const Timeout = 10000
Dim Result
Dim Counter
For Counter = 0 To Timeout Step Step
Result = WshShell.AppActivate(title)
If Result Then Exit For
WScript.Sleep Step
Next
If Result = False Then
MsgBox("Window '" + title + "' not found.")
WScript.Quit
End If
End Function
Function CopyToClipboard(Input)
If IsNull(Input) Then
Set Clipboard = CreateObject("HTMLFile").parentWindow.clipboardData.getData("Text")
If IsNull(Clipboard) Then Clipboard = ""
Else
CreateObject("WScript.Shell").Run _
"mshta.exe javascript:eval(""document.parentWindow.clipboardData.setData('text','" _
& Replace(Replace(Replace(Input, "'", "\\u0027"), """","\\u0022"),Chr(13),"\\r\\n") & "');window.close()"")", _
0,True
End If
End Function

Related

VBScript loops in section of sub that does not contain looping code

Windows 10 Enterprise
Version 20H2
I am writing a VBScript that handles a print to PDF dialogue window.
The goal:
Detect that the printer dialogue window is open (using a loop that continuously checks)
If/when detected, handle the dialogue (send the filename, send the file path, click "print" to finish)
The problem: for some reason, the sub endlessly loops through an If statement. I don't understand why the code is looping through a section containing no loop code.
The code basically sends the same keys in a loop over and over again within the dialogue window, never completing the If statement.
As a small aside, I think the sendKeys command I use to close the dialogue is incorrect, but that should not cause an IF statement to loop.
Code (go to the section indicated by "#"'s to see where I am having issues):
Sub handlePrintDial()
iSeconds = 20
'================================================================================
' Set time variables
'================================================================================
tNow = now()
tFuture = DateAdd("s",iSeconds,tNow)
'================================================================================
' Set other objects
'================================================================================
Set WshShell = CreateObject("WScript.Shell")
sApp = "Save Print Output As"
sFileName = "This is a test-" & Year(now()) & Month(now()) & Day(now()) & Hour(now()) & Minute(now()) & Second(now())
'================================================================================
' Loop until window opens or time elapses
'================================================================================
Do Until Now() > tFuture
ret = WshShell.AppActivate(sApp)
If ret = True Then
Exit Do
End If
Loop
If ret <> True Then
MsgBox "Printer window not found. Please try again."
Exit Sub
End If
'================================================================================
' If printer window detected, handle window
'================================================================================
WScript.Sleep 500
ret = WshShell.AppActivate(sApp)
'########This is the top of the endless loop####################
If ret = True Then
ret = wshShell.AppActivate(sApp)
' Send filename
WScript.Sleep 2000
wshShell.sendKeys sFileName
WScript.Sleep 2000
' Send file path to save to
wshShell.sendKeys "{F4}"
WScript.Sleep 2000
wshShell.sendKeys "{BS}"
WScript.Sleep 2000
wshShell.sendKeys "^A"
WScript.Sleep 2000
wshShell.sendKeys "{del}"
WScript.Sleep 2000
wshShell.sendKeys "C:\Users\Username\Desktop\closeDialogue.vbs"
WScript.Sleep 2000
' "Click" print to complete the dialogue window
wshShell.sendKeys "{enter}"
WScript.Sleep 2000
wshShell.sendKeys "{enter}"
WScript.Sleep 2000
End If
WScript.Sleep 500
'########This is the bottom of the endless loop####################
WScript.Quit
End Sub
Call handlePrintDial()
Here is the window I am trying to handle:
After some experimentation, I discovered that the sendKeys "{enter}" commands were mysteriously causing the script to execute again (two simultaneous instances of the code running at once, per command line). When I removed Enter keys, the code ran normally without kicking off new instances of the script.
Summary: use sendKeys at your own peril. Specifically, it appears {enter} can cause the code to have unusual problems.

VBScript not working when PC is locked

I'm running a VBScript that communicates to an exe file in Windows 7.
The VBScript works great!
The issues I have, is that once the PC has been in locked, goes to sleep or hiberation the VBScript doesn't communicate with the exe application.
The VBScript is running (I have a log that tells me every time a loop is complete, but its not communicating to the exe.
Below is code that is not working when the PC is locked.
Set WSHShell = WScript.CreateObject("WScript.Shell")
' info for exporting data
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim fso, MyFile, FileName, TextLine, cycles
Dim I
I = 0
Dim n
n = .1 'how often the program saves the data (in minutes)
cycles = 2 'how many times it will save
FileName = "C:\Users\Desktop\new.txt" 'location where the log file will save
Dim sl
sl = n * 60000 'change from seconds to ms for the sleep function
Set fso = CreateObject("Scripting.FileSystemObject")
' Open the file for output
Set MyFile = fso.OpenTextFile(FileName, ForAppending, True, TristateTrue)
' Write to the file.
MyFile.WriteLine "Log file for recording data from Yokogawa MX100 (" & cycles
& " cycles)"
WSHShell.Run "MXStandardE.exe"
WScript.Sleep 1000
WSHShell.AppActivate "MXStandardE.exe"
WScript.Sleep 1000
Do while I < cycles
a = Now()
WScript.Sleep 1000
WSHShell.Run "MXStandardE.exe"
WScript.Sleep 1000
WSHShell.AppActivate "MXStandardE.exe"
WScript.Sleep 1000
WSHShell.SendKeys "%A"
WScript.Sleep 1000
WSHShell.SendKeys "{DOWN}"
WScript.Sleep 1000
WSHShell.SendKeys "{ENTER}"
I = I + 1
MyFile.Writeline I & " of " & cycles & " at " & a & " --time of each cycle is
" & n & " minutes"
WScript.Sleep sl 'when sl is used loop time is in minutes
Loop
MyFile.Close
MsgBox ("Script has completed")
As Ansgar already said, it's pretty obvious that nothing will work while the PC sleeps or hibernates. In the case where the PC is locked, techniques that rely on window management or direct input such as SendKeys won't work as expected, because the user's session, along with user-level applications, is essentially shelved to make way for the login screen or another user.
You might want to do some research into the SendMessage/PostMessage API, or you can stop using VBScript and replace it with a Scheduled Task or system service that runs using a local service account, assuming you just want to execute an exe without any UI interaction.
The question is: do you need to go under hibernation or pc suspension? If not, you should simply configure or turn off those settings. By only locking the session, the vbscript should be run and generate an outpout without any trouble. By checking and configuring advanced windows energy settings it might help you solving this.

Set Proxy authentication for ie using Vbscript

I want to auto fill proxy authentication value of username and password for ie using vbscript.
After I added the proxy ip and port to Tools>Internet Option>Connection Tab>LAN Settings. I am prompted with the following dialog
Is there anyways using VBS OR VB to auto fill this ?
So, far i have got the code like so
'begin script
Option Explicit
Dim valUserIn
Dim objShell, RegLocate
Set objShell = WScript.CreateObject("WScript.Shell")
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"0","REG_DWORD"
WScript.Sleep(1000)
valUserIn = Inputbox("Enter the Proxy server you want to use.","Proxy Server Required","proxygate.mydomain.com:8080")
if valUserIn = "" then
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"0","REG_DWORD"
'MsgBox "No proxy mode"
else
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer"
objShell.RegWrite RegLocate,valUserIn,"REG_SZ"
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"1","REG_DWORD"
'MsgBox "Proxy mode: " & valUserIn
end if
WScript.Quit
'end script
But this only set's the proxy ip and port.
Thanks in advance..
You can utilize the Sendkeys shell command which will type in and activate keyboard commands for you once it has allocated the correct screen. However, this is assuming you are running the script while it is open. If you are looking for something that prefills that data before hand. I'm afraid I cannot assist in that realm.
Dim WshShell, Success
Set WshShell = WScript.CreateObject("WScript.Shell")
'Wait for window to popup....
'if this doesn't activate it directly, try clicking on the window.
Do Until Success = True
Success = objShell.AppActivate("Windows Security")
Wscript.Sleep 1000
Loop
WScript.Sleep 500
WshShell.SendKeys "Username"
wscript.sleep 500 'allow program to have time to type it in.
WshShell.SendKeys "{TAB}" 'tab for password field
WshShell.SendKeys "Password"
wscript.sleep 500 'allow program to have time to type it in.
WshShell.SendKeys "%o" 'Alt + O for hitting "OK"
wscript.sleep 500

Scripting MMC with vbscript

I would like to add a snap in via vbscript and I have been having a problem getting the snap in to add to the console. It will be run in a Windows 7 environment. If someone could have a look see and direct me in the right direction I would be most grateful. Thanks.
<code>
'Elevated privileges start
'Start of UAC workaround code
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If WScript.Arguments.length =0 Then
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "wscript.exe", Chr(34) & _
WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else
consoleName = "C:\Burnett.msc"
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(consoleName) Then
Wscript.Echo "console already exists"
Else
On Error Resume Next
Set objMMC = CreateObject("MMC20.Application")
If err.Number <> 0 Then
Wscript.Echo "an error occurred. unable to create mmc console"
Wscript.Quit(0)
End If
objMMC.Show
Set objDoc = objMMC.Document
objDoc.snapins.add("Local Computer\Non-Administrators")
if err then
'Trap the error just after the statement where an error/exception can occur and handle it elegantly
msgbox("Snap-in Not found")
err.clear
end if
objDoc.ActiveView.StatusBarText = "Pane 1|Pane 2|Pane 3"
objMMC.UserControl = 1
objDoc.Name = consoleName
objDoc.Save()
End If
Set fso = Nothing
End If
</code>
"Local Computer\Non-Administrators" is just a system-supplied description for the particular configuration of a snap-in. In this case, the actual snap-in name is "Group Policy Object Editor". Thus to eliminate the error in the code change
objDoc.snapins.add("Local Computer\Non-Administrators")
to
objDoc.snapins.add("Group Policy Object Editor")
Unfortunately, this will only get you as far as MMC putting up a "Select Group Policy Object" dialog. You will then have to manually select the configuration you need using that dialog. As far as I can tell there is no way to supply Snapins.Add with the parameters to select the local non-admin users.
The code below will fully automate the process of setting up the snap-in. However, its reliance on SendKeys makes it extremely brittle. It worked on my system, but there's a good chance you'll need to modify the sequence of key strokes and/or the timing delays to make it work on your system. And once you get it working, there's no guarantee it will continue to do so as local conditions are mutable and can greatly effect the timing.
option explicit
if WScript.Arguments.Named.Exists("elevated") = false then
'Launch the script again with UAC permissions
CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ /elevated", "", "runas", 1
WScript.Quit
end if
Dim mmc : set mmc = WScript.CreateObject("MMC20.Application")
mmc.Show
mmc.UserControl = 1 'to keep MMC open
Dim oShell : set oShell = WScript.CreateObject("Wscript.Shell")
oShell.AppActivate "Console1"
WScript.Sleep 200
oShell.SendKeys "%f"
WScript.Sleep 200
oShell.SendKeys "m"
WScript.Sleep 400
oShell.SendKeys "group{TAB}{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{TAB}{TAB}{RIGHT}{TAB}Non{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{TAB}{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{TAB}{TAB}{TAB}{ENTER}"

Logon to website the Login and password

I try to create a VBS script, what started automatically an website. This part could I solve.
But now I need to put in this script the function login as
And that is the point i stay stucked.
So I hope you can help me.
Here is the script I take to open the website
Dim objExplorer
Set objExplorer = WScript.CreateObject("InternetExplorer.Application")
Do While (objExplorer.Busy)
Wscript.Sleep 250
Loop
objExplorer.TheaterMode = False
objExplorer.AddressBar = True
objExplorer.MenuBar = True
objExplorer.StatusBar = True
objExplorer.ToolBar = False
objExplorer.Resizable = True
objExplorer.Height = 600
objExplorer.Width = 800
objExplorer.Left = 0
objExplorer.Top = 0
' objExplorer.FullScreen = True
objExplorer.Silent = False
objExplorer.Visible = True
objExplorer.Navigate https://mi-xxxxx-xxx-xxxxx.xxx.com/xxxxxxxxxxxxx/login.aspx
objExplorer.Login = User
ObjExplorer.Password = Password
wscript.sleep 6000
Set objShell = CreateObject("Wscript.Shell")
objShell.Run("taskkill /F /IM iexplore.exe /T")
Set objExplorer = nothing
I hope there is a easy way to come to an result.
Many thanks for your Help in this case.
best Regards
Martin
Instead of trying to automate the login via the GUI try inspecting the login process with something like Fiddler. That should give you the actual request that's passing the credentials from the client to the server. With that information you can use an XMLHttpRequest to automate the login:
url = "https://mi-xxxxx-xxx-xxxxx.xxx.com/xxxxxxxxxxxxx/login.asp"
user = "..."
pass = "..."
credentials = "username=" & user & "&password=" & pass
Set req = CreateObject("Msxml2.XMLHttp.6.0")
req.open "POST", url, False
req.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
req.send credentials
If req.status = 200 Then
'login successful
Else
'login failed
End If
You may need to adjust the url and credentials strings according to what Fiddler revealed. You may also need to encode username and/or password with something like this:
Function Encode(ByVal str)
Set re = New RegExp
re.Pattern = "[^a-zA-Z0-9_.~-]"
enc = ""
For i = 1 To Len(str)
c = Mid(str, i, 1)
If re.Test(c) Then c = "%" & Right("0" & Hex(Asc(c)), 2)
enc = enc & c
Next
Encode = enc
End Function
I find an great way to come to need result.
WScript.Sleep 5000
WshShell.SendKeys "******"
WScript.Sleep 3000
WshShell.SendKeys "{TAB}"
WScript.Sleep 3000
WshShell.SendKeys "*********"
WshShell.SendKeys "{TAB}"
WScript.Sleep 3000
WshShell.SendKeys "{ENTER}"
wscript.sleep 10000
So this task is solved.
many thanks for all your commands.
best Regards
martin

Resources