
Broots
Members-
Posts
16 -
Joined
-
Last visited
Profile Information
-
Location
United Kingdom
Broots's Achievements

Seeker (1/7)
0
Reputation
-
I've noticed the same thing when compiling scripts with the newer versions of AutoIT ie. 3.2.10 and the Beta. I didn't change any source code. Memory usage shot up from 6Mb to 9Mb for the main program and the spawned processes went from 3Mb to 5Mb. For the main program, the includes are <GUIConstants.au3,<date.au3>. However, strangely, if the computer goes into standby or hibernate and is then resumed, the memory usage then goes down to 4Mb (previously about 1.6Mb) and the spawned processes go to 1.7Mb (previously 300-600K). Wonder what the standby / hibernate does that reduces the memory usage of the application. I could provide code but I would have 'scrub' it to remove traces of my company's name in it.
-
Breaking out of Process when run a 'sub' program
Broots replied to Broots's topic in AutoIt General Help and Support
Bump ... Is what I am asking an impossibility?? -
Hi, Apologies for the unclear title, but I couldn't figure out how to explain it. I have an app that I wrote in AutoIT that monitors network connections. A new function I am adding to it, allows the execution of a certain program when a specific network connection is detected, eg a VPN connection. Essentially when the condition is met, the program executes a Run(xxx) command. In my case, for testing, the Run Command opens Outlook. Now this all works well, if I start the program as the using Windows Explorer and double clicking it. The program executed using the Run Command uses the credentials of the logged in user. But my problem is the program is started as a service (using the local service account) using XYNTService. So when network condition type is met, the program is executed, but under the context of Local System Account. In this case, Outlook starts but prompts to to create a profile (using System as the default!!). This is my problem. Using Process Explorer, this is the process tree for my application. The program that NetSentry runs when the condition is met falls under the main NetSentry.exe Process. When starting as a service the program runs under the winlogon process. When started manually as the user, it runs under the Windows Explorer Process. Obviously I do not have a way to knowing each user's password, so was wondering if there was a way that I could write the run command in AutoIT to start a program so that starts under the context of the current user or under the Windows Explorer process. All my users have local Administrator rights to their machines, if that helps in any way! Thanks for your valued input. Edited to upload the picture:
-
If you need to update a specific set of keys, it is probably better to update those entries using the RegWrite function of AutoIT. Consult the AutoIT Helpfile on how to use RegWrite Hope this helps
-
Using WMI to poll for events from two seperate queries
Broots replied to Broots's topic in AutoIt General Help and Support
At long last, please find my working code. I was too busy to finish this project. I finally got a prototype I am happy with and that doesn't crash or stall the system and works as planned. Please note:- --------- 1) This is my first app using WMI. Would like to thank ChrisL for the code snippet spawning the processes. I have no other experience of programming. 2) I have run the compiled exe (with resource files) on separate computers and it has worked first time with no problem. The program is only tested with Windows 2000 Service Pack 4 machines. Don't know what results on XP will be like but can't think it could be much different, unless the WMI returns are slightly different! 3) Other Executables: The exes in the resource folder are all Microsoft executables 1.dc.ex_ is Devcon.exe (used to enable / disable devices - THIS FILE IS IMPORTANT!) 2.instsrv.ex_ is Instrv.exe (to install the netsentry.exe as a service) 3.srvany.ex_ is srvany.exe (to install the netsentry.exe as a service) The most damage this software can do is disable all network cards and modems! What it does is monitors network connects / disconnects and takes action as a result thereof. It does not act on soft connects like a VPN connection, etc. All application settings and actions are written to key HKLM\Software\Netsentry. -------------- ----------------- What I would like to do in the future 1) Have a GUI (accessible via admin mode) where all detected NICS and MODEMS and ACTIONS are listed (but I just use the registry for this!) 2) Have the ability to exclude a specific NIC / Modems from the enable / disable process. This is easily achieved by putting a exclude Reg key for the NIC or Modem and having the software use that key as a criteria for it's enable disable/options. I still haven't implemented. 3) Have a way to use less memory. The application spawns two processes that wait for disconnect or connect events. This program when running normally uses about 15Mb of memory! Would appreciate your comments on this and any advice on how to make it better. ------------------ Here is the code. ; ---------------------------------------------------------------------------- ; ; AutoIt Version: 3.1.0 ; Author: M.Hira <secureair@gmail.com> ; ; Script Function: ; Template AutoIt script. ; ; ---------------------------------------------------------------------------- ; Script Start #include <GUIConstants.au3> #include <INet.au3> #Include <date.au3> #NoTrayIcon Opt("WinWaitDelay", 100) Opt("WinTitleMatchMode", 2) Opt("WinDetectHiddenText", 1) Opt("MouseCoordMode", 0) Opt("TrayIconDebug", 0) ;0=no info, 1=debug line info ;Opt("TrayAutoPause", 0) ; Should be 0 in final release Opt("TrayMenuMode", 1) ; Do not show Pause / exit options Opt("OnExitFunc", "F_AutoITExit") Opt("RunErrorsFatal", 0) ; 0= Don't crash script on error ; ============================================================= ; ****** START: Define Global Parameters ****** ; ============================================================= Global $SecureLAN, $SecureLANNotFound Global $proc[3] Global $wp $APP = "Network Sentry" $VER = "0.50" $APPVER = $APP & " (" & $VER & ")" $REG = "HKEY_LOCAL_MACHINE\SOFTWARE\NetSentry" $RES = @ScriptDir & "\Resource\" $wp = "password" ; the password for closing application ; ============================================================= ; Define Protected Networks ; Settings here will ensure that if settings match the network will be ; considered a secure network and all other other network cards will be ; disabled. ; These are the networks we will consider to be secure. If this ; information is not found, network and modem interfaces will be enabled ; if they were previously disables ; Local Network Settings 1 ; LAN 1 parameters ... will be used by GUI in future versions to allow ; changes instead of being hardcoded $DefinedDHCPServer1 = "10.225.200.101" $DefineDNSSuffix1 = "gb.corpnet.net" ; Local Network Setting 2 ; LAN 2 parameters ... will be used by GUI in future versions to allow ; changes instead of being hardcoded $DefinedDHCPServer2 = "10.225.1.101" $DefineDNSSuffix2 = "us.corpnet.net" ; Subsidiary Network Settings ; Will be used by GUI in future versions to allow changes instead of ; being hardcoded $GlobalDNSSuffix1 = "corpnet.net" $GlobalDNSSuffix2 = "corpnet.com" ; ============================================================= ; ****** END: Define Global Parameters ****** ; ============================================================= ; ============================================================= ; ****** START: Defining Functions ****** ; ============================================================= Func F_AutoITExit() ;kill the processes you spawn ;delete the files you create ProcessClose($proc[1]) ProcessClose($proc[2]) FileDelete("Disconnect.au3") FileDelete("Connect.au3") Exit EndFunc ;==>F_AutoITExit ; ============================================================= Func F_TrayTip($TrayMsg, $TrayTime, $TrayIcon) ; This function is used by the application to bring up the traytip ; dialog box when called TrayTip("Clear Previous tray tip", "", 0) TrayTip($APP, $TrayMsg, $TrayMsg, $TrayIcon) EndFunc ;==>F_TrayTip ; ============================================================= Func F_Debug($DebugMsg) ; Used for debugging, just throws up a msgbox with whatever ; we call it with MsgBox(64, $APP & "-Debug Window", $DebugMsg, 4) EndFunc ;==>F_Debug ; ============================================================= Func F_Startup() ; Is used for the general application when it starts up, to ; enable housekeeping to be performed and to ensure that the ; application dependencies are found, etc. ; ***** Define Initialization Steps ***** F_TrayTip("Network Sentry is intializing", 2, 1) TraySetIcon($RES & "mib.ico") ; Delete list of settings since last run so that program can repopulate RegDelete($REG & "\ACTION\", "SecureNetworkOnNICIndex") RegDelete($REG & "\ACTION\", "SecureNetworkDetectedAt") RegDelete($REG & "\ACTION\", "SecureNetworkStatus") RegDelete($REG & "\ACTION\", "SecureNetworkLostAt") ; Delete these scripts, as we will automatically create it again. If FileExists(@ScriptDir & "\connect.au3") Then FileDelete(@ScriptDir & "\connect.au3") If FileExists(@ScriptDir & "\disconnect.au3") Then FileDelete(@ScriptDir & "\disconnect.au3") Sleep(10000) ; Before we begin let's verify if the application's components can be found ; Check to see if you can find Devcon Utility which is used to control hardware ; devices. Vista will make devcon obsolete as we will be able to use WMI to ; to enable/disable devices :-) F_TrayTip("Verifying Application Settings", 2, 1) If FileExists(@SystemDir & "\devcon.exe") Then ; Do nothing! Else ; If you can't find it, try to copy it from Source folder F_TrayTip("Device controller cannot be found. Trying to repair", 2, 2) FileCopy($RES & "dc.ex_", @SystemDir, 1) ;Rename the source file If FileMove(@SystemDir & "\dc.ex_", @SystemDir & "\Devcon.exe", 1) = 1 Then F_TrayTip("Device controller functionality restored", 1, 1) Else F_TrayTip("Device controller cannot be found!", 2, 2) ; Throw up message box as some devices could be in a disabled state ; from the last time the application ran! MsgBox(64, $APP, "There is a problem with device controller." & @CRLF & _ "You may not have full network functionality" & @CRLF & "Please call IT") EndIf EndIf EndFunc ;==>F_Startup ; ============================================================= Func F_ServiceCheck() ; This checks if NetSentry is installed as a service. If not, it will ; automatically install the application as a service If RegRead($REG, "SvcInstalled") = "Yes" Then ; Do nothing, service is installed Else FileCopy($RES & "*.ex_", @SystemDir, 1) FileMove(@SystemDir & "\dc.ex_", @SystemDir & "\Devcon.exe", 1) FileMove(@SystemDir & "\instsrv.ex_", @SystemDir & "\instsrv.exe", 1) FileMove(@SystemDir & "\srvany.ex_", @SystemDir & "\srvany.exe", 1) If MsgBox(68, $APP, "It looks like " & $APP & " is not installed as a service" & @CRLF & "Would you like to install it?") = 6 Then ;Install Application as service $CMD = @SystemDir & "\instsrv.exe" & " NetSentry " & @SystemDir & "\srvany.exe" F_Debug("Command is: " & $CMD) RunWait(@ComSpec & " /c " & $CMD) $REGSVC = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NetSentry" $REGSVC1 = "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\NetSentry" ;Modify Service Parameters RegWrite($REGSVC1 & "\Parameters") RegWrite($REGSVC1 & "\Parameters", "Application", "REG_SZ", @ScriptFullPath) RegWrite($REGSVC1 & "\Parameters", "Application", "REG_SZ", @ScriptFullPath) RegWrite($REGSVC, "Display Name", "REG_SZ", "Network Sentry") RegWrite($REGSVC, "Description", "REG_SZ", "Network Sentry - Monitors Network Connections and controls interfaces") RegWrite($REGSVC, "FailureActions", "REG_BINARY", "00000000000000000000000003000000f8f310000100000060ea00000100000060ea00000000000060ea0000") RegWrite($REGSVC, "Type", "REG_DWORD", "272") RegWrite($REGSVC1, "Display Name", "REG_SZ", "Network Sentry") RegWrite($REGSVC1, "Description", "REG_SZ", "Network Sentry - Monitors Network Connections and controls interfaces") RegWrite($REGSVC1, "FailureActions", "REG_BINARY", "00000000000000000000000003000000f8f310000100000060ea00000100000060ea00000000000060ea0000") RegWrite($REGSVC1, "Type", "REG_DWORD", "272") RegWrite($REG, "SvcInstalled", "REG_SZ", "Yes") Else ; Do Nothing, user said service should not be installed EndIf EndIf EndFunc ;==>F_ServiceCheck ; ============================================================= Func F_GetNetDevices($NicEvent) ; where event = Startup; Connect; Disconnect ; Builds a list of all network adaptors on the local machine ; Depending on what function calls it, it could do slightly different things. ; On application startup,once a Nic is added to a machine and is populated in the ; registry via this script, it does not get deleted. The reason for this is bcos if ; the device is disabled, the WMI script will not pick it up and we will not be able ; to get a PnPID Value it. In the future will try to get around this problem, but ; it is not major.. If $NicEvent = "Startup" Then F_TrayTip("Building list of connectivity adapters", 3, 1) ; If there is a connect/disconnect we clear the secure network settings, as the ; connectivity checks will update the value if a secure or subsidiary network is found If $NicEvent <> "StartUp" Then $SecureLAN = "" RegDelete($REG & "\ACTION\", "SecureNetworkOnNICIndex") RegDelete($REG & "\ACTION\", "SecureNetworkDetectedAt") RegDelete($REG & "\ACTION\", "SecureNetworkStatus") RegDelete($REG & "\ACTION\", "SecureNetworkLostAt") EndIf ; Start the WMI Queries $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colNetAdapter = "" $strComputer = "localhost" $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2") $colNetAdapterConfig = $objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapterConfiguration Where IPEnabled=True", _ "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly) If IsObj($colNetAdapterConfig) Then For $objItem In $colNetAdapterConfig ; Populate NIC Key itself with MAC addresses and name of Network Card RegWrite($REG & "\NIC\", $ObjItem.MacAddress, "REG_SZ", $ObjItem.Description) ; For Each Network Card, create a key and get settings related to it! RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "ServiceName", "REG_SZ", $ObjItem.ServiceName) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "MacAddress", "REG_SZ", $ObjItem.MacAddress) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "Description", "REG_SZ", $ObjItem.Description) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "Index", "REG_SZ", $ObjItem.Index) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "ServiceName", "REG_SZ", $ObjItem.ServiceName) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DHCPServer", "REG_SZ", $ObjItem.DHCPServer) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DNSDomain", "REG_SZ", $ObjItem.DNSDomain) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "IPAddress1", "REG_SZ", $ObjItem.IPAddress (0)) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "IPAddress1Enabled", "REG_SZ", $ObjItem.IPEnabled) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "IPAddress1SNMask", "REG_SZ", $ObjItem.IPSubnet (0)) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "IPAddress1Gateway", "REG_SZ", $ObjItem.DefaultIPGateWay (0)) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "SettingID", "REG_SZ", $ObjItem.SettingID) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "LastUpdated", "REG_SZ", _Now()) ; Find Matching Device in Registry and see what connection is assigned to it $ConnectionNameRead = RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\" & _ "{4D36E972-E325-11CE-BFC1-08002BE10318}\" & $ObjItem.SettingID & "\Connection\", "Name") RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "ConnectionName", "REG_SZ", $ConnectionNameRead) $PnPDeviceIDRead = RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\" & _ "{4D36E972-E325-11CE-BFC1-08002BE10318}\" & $ObjItem.SettingID & "\Connection\", "PnpInstanceID") RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "HardwareID", "REG_SZ", $PnPDeviceIDRead) ; If you find that there is no Network Adapter name in Registry for a NIC, ; delete the section as it is not needed ; The section will be re-added when an IP address is found for it! If RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "ConnectionName") = "" Then RegDelete($REG & "\NIC\" & $ObjItem.MacAddress) EndIf ; Check to see if the Domain Suffix for the local area connections are statically inputted ; If it matches - go and delete them, Do this once - when application is starting up. ; Note: Domain is the statically inputted connection suffix. When DHCP assigns a suffix, it appears in the ; same regtree as DHCPDomain. When querying for DNS suffix via WMI, Domain overides DHCPDomain but if ; no Domain value is listed, WMI will return the DHCPDomain Value when querying for DNSDomain. If $NicEvent = "Startup" Then If RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\" & _ $ObjItem.SettingID & "\", "Domain") = $DefineDNSSuffix1 Or _ RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\" & _ $ObjItem.SettingID & "\", "Domain") = $DefineDNSSuffix2 Then RegDelete("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\" & _ $ObjItem.SettingID & "\", "Domain") EndIf EndIf Next EndIf ; Using Servicename Generated in the original query to get the Hardware ID from another WMI Query $colNetAdapter = $objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapter", "WQL", _ $wbemFlagReturnImmediately + $wbemFlagForwardOnly) If IsObj($colNetAdapter) Then For $objItem In $colNetAdapter If $ObjItem.Index = RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "Index") Then RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "FriendlyName", "REG_SZ", $ObjItem.ProductName) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState", "REG_SZ", $ObjItem.ConfigManagerErrorCode) ; where Errorcode 22=Disabled ; 0=Enabled EndIf ;Clean up this section since the query may write some junk that is not needed! ; If RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "ConnectionName") = "" Then ; RegDelete($REG & "\NIC\" & $ObjItem.MacAddress) ; EndIf Next EndIf ; Get List of Modems in System $colModems = $objWMIService.ExecQuery ("SELECT * FROM Win32_POTSModem", _ "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly) If IsObj($colModems) Then For $objItem In $colModems ; Populate Modem List RegWrite($REG & "\MODEM\", $ObjItem.AttachedTo, "REG_SZ", $ObjItem.Caption) ; For Each Modem, get some more details! RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "FriendlyName", "REG_SZ", $ObjItem.Caption) RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "HardwareID", "REG_SZ", $ObjItem.DeviceID) RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "ModemType", "REG_SZ", $ObjItem.DeviceType) RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState", "REG_SZ", $ObjItem.ConfigManagerErrorCode) RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "LastUpdated", "REG_SZ", _Now()) Next EndIf ;EndIf EndFunc ;==>F_GetNetDevices ; ============================================================= Func F_MonitorNics() $MonDisconnect = 'Opt("TrayIconHide",1)' & @CRLF & _ '$strComputer = "." ' & @CRLF & _ '$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\wmi")' & @CRLF & _ '$colMonitoredEvents = $objWMIService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaDisconnect")' & @CRLF & _ 'While True' & @CRLF & _ '$strLatestEvent = $colMonitoredEvents.NextEvent ' & @CRLF & _ 'Sleep(1500) ' & @CRLF & _ 'ConsoleWrite("Disconnect")' & @CRLF & _ 'Wend' $MonConnect = 'Opt("TrayIconHide",1)' & @CRLF & _ '$strComputer = "." ' & @CRLF & _ '$objWMIService = Objget("winmgmts:\\" & $strComputer & "\root\wmi") ' & @CRLF & _ '$colMonitoredEvents = $objWMIService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaConnect")' & @CRLF & _ 'While True' & @CRLF & _ '$strLatestEvent = $colMonitoredEvents.NextEvent' & @CRLF & _ 'Sleep(1500) ' & @CRLF & _ 'ConsoleWrite("Connect")' & @CRLF & _ 'Wend' FileWrite(@ScriptDir & "\Disconnect.au3", $MonDisconnect) FileWrite(@ScriptDir & "\Connect.au3", $MonConnect) $proc[1] = Run(@AutoItExe & ' /AutoIt3ExecuteScript Disconnect.au3', @ScriptDir, @SW_SHOW, 7) $proc[2] = Run(@AutoItExe & ' /AutoIt3ExecuteScript Connect.au3', @ScriptDir, @SW_SHOW, 7) ;=-=-=- $retestitem = TrayCreateItem("Re-test") TrayCreateItem("") $aboutitem = TrayCreateItem("About") $closeitem = TrayCreateItem("Close") ;=-=-=- TraySetState() While 1 $msg = TrayGetMsg() Select Case $msg = 0 For $i = 1 To UBound($proc) - 1 If @error Then ExitLoop $line = StdoutRead($proc[$i], "", True) If $line <> 0 Then $line = StdoutRead($proc[$i]) ;Pipe The Output of the SubProcesses so that we can use it to perform an action ;based on the subprocess, we are looking for an output of "Connect or "Disconnect" $NicEvent = $line F_VerifyConnection($NicEvent) EndIf Next Sleep(1500) ContinueLoop Case $msg = $retestitem F_VerifyConnection("Retest") Case $msg = $aboutitem MsgBox(64, $APPVER, "Network Sentry" & @CRLF & "Version:" & $VER) Case $msg = $closeitem If InputBox($APPVER, "Enter password to close application", "", "*") = $wp Then ; Correct Password given. Close program MsgBox(64, $APPVER, "Note: Some network interfaces and" & @CRLF & "modems may still be disabled!") ExitLoop Else ;Do Nothing!! MsgBox (48, $APPVER, "Wrong Password!") EndIf EndSelect WEnd EndFunc ;==>F_MonitorNics ; ============================================================= Func F_VerifyConnection($NicEvent) ; Based on whether a Connect/Disconnect Signal has been received, Verify Network Settings ; and disable or enable interfaces as needed TraySetIcon($RES & "mib.ico") $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colNetAdapter = "" $strComputer = "localhost" $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2"); $colNetAdapterConfig = $objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapterConfiguration", _ "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly) $colNetAdapterServices = $objWMIService.ExecQuery ("SELECT * FROM Win32_SystemDriver", _ "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly) $colModems = $objWMIService.ExecQuery ("SELECT * FROM Win32_POTSModem", "WQL", _ $wbemFlagReturnImmediately + $wbemFlagForwardOnly) $colNetAdapter = $objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapter", "WQL", _ $wbemFlagReturnImmediately + $wbemFlagForwardOnly) ; Wait for network info to be collected before you verify connections again. If $NicEvent = "Startup" Then Sleep(15000) If $NicEvent = "Connect" Or $NicEvent = "Disconnect" Then Sleep(10000) If $NicEvent = "Retest" Then F_TrayTip("Re-testing network", 2, 1) TraySetState(4); let the tray icon flash ; Update the list of networks and modems on system ... F_GetNetDevices($NicEvent) ; Only Check for network connections that are connected at the time! ; Look for any interface that is connected to your defined 'secure' network If IsObj($colNetAdapterConfig) Then For $objItem In $colNetAdapterConfig ; We are using the DHCPServer Value as our primary criteria for determining ; if we are on the Local Secure LAN. ; Whether we are on the Local Secure LAN or a Subsidiary Secure LAN, ; the effect will be the same, but if you wanted a slightly different action, ; you could use this to diffrentiate between them. ; Using DHCPServer as parameter to decide if the network is our local internal one! ; Since the DHCPServer info is stored until the interface is connected to ; another network that overwrites it's settings, we ping the $DefindedDHCPServers ; to verify that we are on the network. ; NOTE: When not on a defined network as decided by the Checkpoint Firewall the ; Checkpoint firewall will not allow pings to be made which is fine .. as it is ; another safety check in our favour which means we can allow all interfaces to ; be enabled If $ObjItem.DHCPServer = $DefinedDHCPServer1 Or _ $ObjItem.DHCPServer = $DefinedDHCPServer2 And _ StringInStr($ObjItem.DNSDomain, $DefineDNSSuffix1) >= 1 Or _ StringInStr($ObjItem.DNSDomain, $DefineDNSSuffix2) >= 1 Then If Ping($ObjItem.DHCPServer, 250) = 1 And _ $ObjItem.IPAddress (0) <> "" Then ; ensure interface does have an IP Address! ; Mark this interface as the Local Secure LAN interface $SecureLAN = $ObjItem.Index ;F_TrayTip("Secure Network Detected", 4, 1) ;F_Debug("SecureLocal Network found on:" & $ObjItem.Index & @CRLF & $objItem.IPAddress (0)) RegWrite($REG & "\ACTION\", "SecureNetworkOnNICIndex", "REG_SZ", $SecureLAN) RegWrite($REG & "\ACTION\", "SecureNetworkDetectedAt", "REG_SZ", _Now()) RegWrite($REG & "\ACTION\", "SecureNetworkStatus", "REG_SZ", "LocalSecure") ; Write that the network type is SecureLocal RegDelete($REG & "\ACTION\", "SecureNetworkLostAt") EndIf EndIf ; If the secure network isn't detected we could could be on a subsidiary LAN, ; so we check the DNS Suffix for the connection. If it it matches, still run ; the rule to disable the other interfaces. ; Get the DNSDomain Setting (since it is or will be set by the DHCP Server). ; This will be used to query for a Corpnet Subsidiary network if the primary ; network criterion is not met If $SecureLAN = "" Then ;Check to see if you plugged into a subsidiary network by checking DNS settings If StringInStr($ObjItem.DNSDomain, $GlobalDNSSuffix1) >= 1 Or StringInStr($ObjItem.DNSDomain, $GlobalDNSSuffix2) >= 1 And _ Ping($ObjItem.IPAddress (0), 1000) = 1 Then ; Ensure that Interface has IP Address $SecureLAN = $ObjItem.Index RegWrite($REG & "\ACTION\", "SecureNetworkOnNICIndex", "REG_SZ", $SecureLAN) RegWrite($REG & "\ACTION\", "SecureNetworkDetectedAt", "REG_SZ", _Now()) RegWrite($REG & "\ACTION\", "SecureNetworkStatus", "REG_SZ", "Subsidiary") ; Write that the network type is a subsidiary Lan RegDelete($REG & "\ACTION\", "SecureNetworkLostAt") EndIf EndIf ; If the Local Secure or Subsidiary network is not detected, it means we need ; to enable all the interfaces. ; Try to Ping Secure Network Criterion ; If 0 = then there is no ping response so secure network is not connected ; Enable all cards that you have disabled or are disabled! ; Only run this portion if the local secure/subsidiary is not detected If $SecureLAN <= 0 Then ; Check for response from DHCPServers If Ping($DefinedDHCPServer1, 250) = 0 Or Ping($DefinedDHCPServer2, 250) = 0 Or _ StringInStr($ObjItem.DNSDomain, $GlobalDNSSuffix1) < 1 Or _ StringInStr($ObjItem.DNSDomain, $GlobalDNSSuffix2) < 1 Then ; Or Check to see if an interface has a DNS suffix meeting the criteria ;F_Debug("Secure/Subsidiary Lan Not Detected on " & @CRLF & $ObjItem.Description & "Index:" & $ObjItem.Index) RegWrite($REG & "\ACTION\", "SecureNetworkStatus", "REG_SZ", "NotDetected") RegWrite($REG & "\ACTION\", "SecureNetworkLostAt", "REG_SZ", _Now()) RegDelete($REG & "\ACTION\", "SecureNetworkDetectedAt") RegDelete($REG & "\ACTION\", "SecureNetworkOnNICIndex") EndIf EndIf Next EndIf ; Depending on what you found above, act on it .. If Secure or Subsidiary Network is detected ; enable/disable all other interfaces If RegRead($REG & "\ACTION\", "SecureNetworkOnNICIndex") <> "" Then For $objItem In $colNetAdapter $SecureLAN = RegRead($REG & "\ACTION\", "SecureNetworkOnNICIndex") TraySetIcon($RES & "redlock.ico") TraySetToolTip("PHYSICALLY connected to CorpNet Network" & @CRLF & "Note: Some interfaces have been disabled") If $ObjItem.Index <> $SecureLAN And _ RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "Index") = $ObjItem.Index Then $HardwareID = RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "HardwareID") $DeviceName = RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "FriendlyName") RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled $DeviceState = RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState") $Action = "Disable" ;Send Disable Command If $ObjItem.ConfigManagerErrorCode = 0 Then F_ControlDevice($HardwareID, $DeviceName, $Action) ;Get the device status again after the action has been peformed on it. RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled Sleep(1000) EndIf Next For $objItem In $colModems $HardwareID = RegRead($REG & "\MODEM\" & $ObjItem.Caption, "HardwareID") $DeviceName = RegRead($REG & "\MODEM\" & $ObjItem.Caption, "FriendlyName") RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled $DeviceState = RegRead($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState") $Action = "Disable" ;Send Disable Command If EventCode picked up from WMI = 0 and needs to be 22 If $ObjItem.ConfigManagerErrorCode = 0 Then F_ControlDevice($HardwareID, $DeviceName, $Action) ;Get the device status again after the action has been peformed on it. RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled Next ElseIf RegRead($REG & "\ACTION\", "SecureNetworkStatus") = "NotDetected" Then For $objItem In $colNetAdapter $SecureLAN = RegRead($REG & "\ACTION\", "SecureNetworkOnNICIndex") TraySetIcon($RES & "greenlock.ico") TraySetToolTip("NOT directly connected to CorpNet Network" & @CRLF & "Note: All interfaces are enabled") If $ObjItem.Index <> $SecureLAN And RegRead($REG & "\ACTION\" & _ $ObjItem.Description, "NetSentryLastAction") = "Disable" Then $HardwareID = $ObjItem.PnPDeviceID $DeviceName = $ObjItem.Name RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled $DeviceState = RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState") $Action = "Enable" ;Send Enable Command If $ObjItem.ConfigManagerErrorCode = 22 Then _ F_ControlDevice($HardwareID, $DeviceName, $Action) ;Get the device status again after the action has been peformed on it. RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled Sleep(1000) EndIf Next For $objItem In $colModems $HardwareID = RegRead($REG & "\MODEM\" & $ObjItem.Caption, "HardwareID") $DeviceName = RegRead($REG & "\MODEM\" & $ObjItem.Caption, "FriendlyName") RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled $Action = "Enable" ;Send Enable Command If $ObjItem.ConfigManagerErrorCode = 22 Then _ F_ControlDevice($HardwareID, $DeviceName, $Action) ;Get the device status again after the action has been peformed on it. RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled Next EndIf TraySetState(8); stop the tray icon flashing EndFunc ;==>F_VerifyConnection ; ============================================================= Func F_ControlDevice($HardwareID, $DeviceName, $Action) ; where $Hardware = PnPDeviceID, $DeviceName = Friendly Name, $Action = Enable or Disable ; Enables or disables interfaces based on Function that calls it.. If $Action = "Disable" Then F_TrayTip("Secure Network not detected:-" & @CRLF & "Unsecuring interfaces", 1, 1) ; Generic display box ; If Action = Enable If $Action = "Enable" Then F_TrayTip("Secure Network Detected:-" & @CRLF & "Securing interfaces", 1, 1) F_TrayTip("Network & modem " & @CRLF & "changes are being made", 1, 1) RegWrite($REG & "\ACTION\" & $DeviceName, "NetSentryLastAction", "REG_SZ", $Action) RegWrite($REG & "\ACTION\" & $DeviceName, "ActionTime", "REG_SZ", _Now()) $CMD = @SystemDir & "\devcon.exe -" & $Action & " ""@" & $HardwareID & """" RunWait(@ComSpec & " /c " & $CMD, "", @SW_HIDE) EndFunc ;==>F_ControlDevice ; ============================================================= Func F_Test() EndFunc ;==>F_Test ; ============================================================= ; ****** END: Define Functions ****** ; ============================================================= ; ============================================================= ; ****** START: Application Process ****** ; ============================================================= F_Startup() F_ServiceCheck() F_GetNetDevices("Startup") F_VerifyConnection("Startup") F_MonitorNics() ; ============================================================= ; ****** End: Application Process ****** ; ============================================================= This is the zip file containing the EXEs and the uncompiled code! http://rapidshare.com/files/4651813/NetSentry.zip.html -
What I would do is to use the AutoIT function to get the localhostname which is: EnvGet("ComputerName") Run("psexec \\server -u server\Administrator -p password -i c:\windows\" & EnvGet("ComputerName") & ".exe") That should solve your problem.
-
Using WMI to poll for events from two seperate queries
Broots replied to Broots's topic in AutoIt General Help and Support
Way too complicated for my bird brain ... but I'm getting there ... hopefully I can get it all working by Friday! Thank you once again! -
Using WMI to poll for events from two seperate queries
Broots replied to Broots's topic in AutoIt General Help and Support
You, Sir, are a GENIUS! I'm still trying to understand the method of your absolutely glorius logic! -
Using WMI to poll for events from two seperate queries
Broots replied to Broots's topic in AutoIt General Help and Support
Thanks for the info and pointers. I was sitting on the train on my way to the Arsenal game last night and also wondered that I could miss some events if the app was polling for a disconnect at the time a connect is made. I will test, and hopefully post the code up sometime soon! -
Hi, I am trying to write a little app that disables other network adaptors on the local machine if a 'internally' definded network is detected on any network interface. For the most part the logic seems to work, but I am trying to write function in AutoIT which uses WMI to monitor for two two events: network connection and disconnection. When a connection is detected run Step A and when a disconnect is detected to run step B. Note: Disabling of devices will be done by the devcon utility. This is a portion of the code that I am having trouble with. Func F_TrayTip($TrayMsg, $TrayTime, $TrayIcon) TrayTip("clears previous tray tip", "", 0) TrayTip($APP, $TrayMsg, $TrayMsg, $TrayIcon) EndFunc ;==>F_TrayTip Func F_MonitorNICConnect() $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colItems = "" $strComputer = "localhost" $objNicMonitorService = ObjGet("winmgmts:\\" & $strComputer & "\root\WMI") ; **** QUERY FOR NIC CONNECT EVENTS ***** $colNicConnect = $objNicMonitorService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaConnect") $ColNicDisconnect = $objNicMonitorService.ExecNotificationQuery ("SELECT * FROM MSNdis_StatusMediaDisconnect") While 1 ; Monitor Nics for event change If $colNicConnect.NextEvent Then $Output = "A network connection has been made:" F_TrayTip($Output & @CRLF & "Verifying Network Configuration", 2,1) $NicEvent = "Connect" F_VerifyConnection($NicEvent) ElseIf $ColNicDisconnect.NextEvent Then $Output = "A network connection has been lost:" F_TrayTip($Output & @CRLF & "Verifying Network Configuration", 2,1) $NicEvent = "Disconnect" F_VerifyConnection($NicEvent) EndIf Sleep(5000) WEnd EndFunc ;==>F_MonitorNICConnect When the events are written as different functions, ie, function just for Connect and another for Disconnect, it sort of works as expected if i call them manually. But once the one function is called and it starts polling, I don't know how to break out that function to also monitor for a disconnect state. I tried to amalgamate the two functions as one, which is listed above, but now it doesn't work. Any tips or pointers would really be appreciated on using a WHILE process to monitor for two events via WMI. Once I get this working, I will post the code to forums for peer review and hopefully to help other people like me. Thanks for all your advice in advance! M
-
MHZ ... thanks for your help ... you guidance for this post has helped me answer my query over here
-
*bump ... for other ideas
-
Thanks for the info. Will try to research and resolve. If anybody else has ideas on the Looping two WMI queries, would appreciate it!
-
Hi, My first post, and it's because I can't understand simple logic! I am trying to convert a simple piece of WMI Code to use in AutoIT. However, I just can't seem to work out what I need to change. I've never done programming, and am still trying to get to grips with when to use the Do, For, While commands. What I am trying to do, is to write a small application that detects when a computer has connected or disconnected from a network using any of it's interfaces so that other settings can be effected. From the Microsoft Scripting Guy Column here, there are two scripts that can used. This is for when a disconnect is detected strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\wmi") Set colMonitoredEvents = objWMIService.ExecNotificationQuery _ ("Select * from MSNdis_StatusMediaDisconnect") Do While True Set strLatestEvent = colMonitoredEvents.NextEvent Wscript.Echo "A network connection has been lost:" WScript.Echo strLatestEvent.InstanceName, Now Wscript.Echo Loop This is for detecting when a connection is made strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\wmi") Set colMonitoredEvents = objWMIService.ExecNotificationQuery _ ("Select * from MSNdis_StatusMediaConnect") Do While True Set strLatestEvent = colMonitoredEvents.NextEvent Wscript.Echo "A network connection has been made:" WScript.Echo strLatestEvent.InstanceName, Now Wscript.Echo Loop This is my AutoIT code, which i've tried to write which doesn't work ; Generated by AutoIt Scriptomatic $APP = "NetSentry" $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colItems = "" $strComputer = "localhost" $objNicMonitorService = ObjGet("winmgmts:\\" & $strComputer & "\root\WMI") $colItems = $objNicMonitorService.ExecQuery("SELECT * FROM MSNdis_StatusMediaDisconnect") If IsObj($colItems) Then For $objItem in $colItems While 1 $strLatestEvent = $ColItems.NextEvent $Output = "A network connection has been lost:" & @CRLF $Output = $Output & $strLatestEvent.InstanceName TrayTip($APP,"Disconnect Detected. Updating Networks", 5) WEnd Next Else EndIf My Questions 1) What is the AutoIT equivalent of Do While True ? 2) How can I write a WQL query to poll for both events so that it can run in a loop. I've tried various WMI queries, and it just doesn't work. I don't think WMI can query two differenct 'classes' simulataneously. 3) You guys are great! I'm just not clever enough to transplant the knowledge I've tried to learn while searching the other posts.