Search the Community
Showing results for tags 'Network'.
-
I needed a function to ping many computers, and get the results of the pings in an array so to manage it easily in a script. Searching in the forum I found some interesting sw with a nice graphical interface, but not a generic function that simply return an array. a very powerful pinger I found is >nPing by Manadar, but it is designed as a command line tool, so I decided to use the entire engine of nPing adapting it a bit, so that it can be used as an udf. This code is a first attempt (beta) and it can be used to: Ping all computers (IP addresses) belonging to the (local) LAN just call the _nPing() without any parameter Ping a predefined list of IP just pass the list of host (IP or hastnames) to the function in an 1D zero based array or in a 2D array indicating the column containing the addresses Ping all computers (IP addresses) of a remote LAN just pass an IP of that lan and his subnet mask Ping range of computers (IP addresses) just pass a string rappresenting the range of IP to ping (as accepted by the nPing program by Manadar), for example: 192.168.0.0-1 will ping these addresses: 192.168.0.0 and 192.168.0.1 192.168.20.* will ping everything in the range from 192.168.20.1 to 192.168.20.255 192.168.0-1.1-254 will ping everything in the range from 192.168.0.1 to 192.168.1.254 I have not done extensive testing on it, so I would be grateful if someone that tries it, can report any error thanks EDIT: After some testing, I have seen that sometime some IP are reported as dead, while are alive instead. This occurs when a device is not so fast to answer to the ping, and so it's marked as dead while instead is only too slow to answer to the ping. I came to the conclusion that for a more accurate result about the not responding devices, is better to use a $timeout parameter of 4000 ms as default value in the _MSPing() function (the same default timeout value as in the standard ping command) So I have "calibrated" the multiping.au3 by modifying the line 349 and incrementing the value of the $Timeout variable from 100 ms to 4000 ms. This should be a better choice for a general purpose utilization that gives more stable and accurate results about the not responding devices. This should not slow down the overall performances, but will only give some more time to respond to the slower devices. MultiPing.au3 #include <iNet.au3> ; #INDEX# ======================================================================================================================= ; Title .........: _nPing ; AutoIt Version : ; Language ......: English ; Description ...: Function to perform multi Ping. ; Author(s) .....: core engine is Manadar's "nping" retrieved at the following post ; http://www.autoitscript.com/forum/topic/108060-nping-console-network-pinger-network-sweeper-network-scanner ; adapted to this UDF by PincoPanco ; =============================================================================================================================== ; #CURRENT# ===================================================================================================================== ; _nPing multi IP pinger ; =============================================================================================================================== ; #INTERNAL_USE ================================================================================================================= ; _LanParameters given IP and mask generate [and display] various lan parameters ; _CIDR_To_Mask transform a CIDR number (1 - 32) to the corresponding 4 digit mask ; _Mask_To_CIDR transform a 4 digit mask to the corresponding CIDR number (1 - 32) ; _GetSubnetMask given the local IP returns the related subnet mask (thanks to dragan) ; _Convert_To_Binary from decimal to binary ; _Bin_To_Dec from binary to decimal ; _FileReadToArray_mod read a file of IP in a 1D array, if is a csv and a separator is passed a 2D array is returned ; _GetIpAddressList Generate the IP list to Ping ; _Make_Range Given an IP and his mask, this function return the full LAN "range" for _nPing ; _GetLanParameters calculate all IP/subnet related parameters ; _isIPaddr check if passed IP is a plausible IP ; _isSNmask check if passed mask is a plausible mask ; _Progress shows a progress bar for the current scan ; =============================================================================================================================== ; #FUNCTION# ==================================================================================================================== ; Name...........: _nPing ; Description ...: returns an array containing: clients responding to ping or clients not responding or both. See $ReturnFlag ; Syntax.........: _nPing([[$IP]|[$IPArray]|[$IPrange]],[[$NetMask]|[$column]], [$ReturnFlag], [$Resolve], [$MyFunction]) ; Parameters ....: [[$IP]|[$IPArray]|[$IPrange]] - An IP address or an 1D or 2D array (0 based) or an IPrange(*) ; $NetMask - An 4 digit Net Mask or a CIDR notation value (numbers of bit from 1 to 32) ; if previous parameter is an 2D array then this parameter contains the ; nr. of the column that contains the addresses to be pinged ; $ReturnFlag - 0|1|2, what to return: 0=all cliensts; 1=responding clients; 2= not responding clients(**) ; $Resolve - O or 1, if IP lookup name resolution must be performed; 1 = yes, 0 = no ; $MyFunction - an User Defined Function to be called each time a PING complete (default is progress bar) ; the called function receives 1 parameter that is an array containing the following 6 parameters: ; [0] nr. of total addresses under process ; [1] nr. of ping already finished ; [2] IP just processed ; [3] resolved Host name or -1 if IP is down ; [4] roundtrip of this ping or -1 if IP is down ; [5] Index of this IP within the caller's passed array ; by default is called the _Progress() function that will display the progress bar ; Return values .: Success - an 2D array containing: ; first row ($array[0][x]) contains: [0][0]= nr. of returned host; [0][1]= total roundtrip ; other rows: [n][0]=Address; [n][1]=lookup name; [n][2]=roundtrip; [n][3]=index in the passed array*** ; Failure - -1, sets @error ; |1 - too many IP, max 16777216 ($MAX_HOSTS) ; |2 - wrong array dimensions or wrong column number ; |3 - wrong IP ; |4 - wrong subnet mask ; |5 - bad "range" or wrong IP error ; |6 - Windows Sockets Error ; |7 - (not used) ; |8 - DLL call error (reading local subnet mask) ; ; (*) IPrange is a string as below ; "192.168.0.0-1" will ping these addresses: 192.168.0.0 and 192.168.0.1 ; "192.168.20.*" will ping everything in the range from 192.168.20.1 to 192.168.20.255 ; "192.168.0-1.1-254" will ping everything in the range from 192.168.0.1 to 192.168.1.254 ; ; (**) returnead 2D array has the following 4 columns: ; first row contains: [0][0]= nr. of returned host; [0][1]= total roundtrip ; following rows contains fields as below ; +-------------------------+-------------------------+ ; | nr of elements in array | total roundtrip | ; +-------------------------+-------------------------+-------------------------+-------------------------+ ; | IP address | [hostname] ( -1) | roundtrip (or -1) | index *** | ; +-------------------------+-------------------------+-------------------------+-------------------------+ ; ; (***) since the returned array has not the same nr. of rows and also has not the same order of the array in input, ; this index is a reference to "bind" both arrays. ; It is more useful if the input array is a 2D array and you have to bind the rows containing results ; with related fields (array elements) in the "source" array ; Author ........: ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........: ; Example .......: ; =============================================================================================================================== Func _nPing($networkRange = "", $MyMask = "", $ReturnFlag = 1, $Resolve = 0, $MyFunction = "_Progress") Static $TCP = TCPStartup() ; this should be used at the beginning of the main program instead of inside the Func() Static $dig = FileExists(".\dig\dig.exe") ; this is for IP to hostname resolution. if dig.exe exists will be used. (faster than _TCPIpToName) Local $MAX_PROCESS = 20 ; A maximum number of processes (25) ; Global $MAX_HOSTS = 16777216 ; A maximum number of hosts to ping due to AutoIt's array limit size Local $_IPup[1][4] ; will contain results of PINGs [IP][roundrip or -1] ; check what has been required from caller If $networkRange = "" Then ; no parameters passed, so scan local network ; ConsoleWrite("debug: no IP/range provided, I will scan the local LAN" & @CRLF) $networkRange = _Make_Range(TCPNameToIP(@ComputerName), _GetSubnetMask(TCPNameToIP(@ComputerName))) ; retrieve local LAN and Subnet Mask values If @error Then Return SetError(@error, @extended, -1) ; ConsoleWrite("debug: network range=" & $networkRange & @CRLF) ElseIf IsArray($networkRange) Then ; ----- is an array -----------------------------+ ; if is an 2D array then $MyMask contains the column else is ignored | If UBound($networkRange) > 16777216 Then Return SetError(1, 0, -1) ; | too many IP > $MAX_HOSTS ; If UBound($networkRange, 0) <> 1 Then Return SetError(2, 0, -1) ; | If UBound($networkRange, 0) > 2 Then Return SetError(2, 0, -1) ; | max 2D array If UBound($networkRange, 0) = 1 Then ; | $aArray = $networkRange ; $aArray = all IP to scan | Else ; ----- it is a 2D array ----- | ; the number of the column with addresses is in $MyMask parameter | If $MyMask > UBound($networkRange, 2) - 1 Then Return SetError(2, 0, -1) ; | wrong column Local $aArray[UBound($networkRange)] ; | For $i = 0 To UBound($networkRange) - 1 ; | $aArray[$i] = $networkRange[$i][$MyMask] ; | Next ; | EndIf ; | ; ------------------------------------------------------------------------------+ ElseIf _isIPaddr($networkRange) Then ; single IP ; ConsoleWrite("debug: single IP value received" & @CRLF) If $MyMask <> "" Then ; is there a subnet? If Not _isSNmask($MyMask) Then ; wrong 4 digit mask If $MyMask > 0 And $MyMask < 33 Then ; is it a CIDR notation number? (nr. of bits of mask (1 to 32)) $MyMask = _CIDR_To_Mask($MyMask) Else Return SetError(4, 0, -1) ; wrong mask provided EndIf EndIf $networkRange = _Make_Range($networkRange, $MyMask) ; generate the "range" of all IP belonging to that subnet mask EndIf EndIf If Not IsArray($networkRange) Then ; ConsoleWrite("debug: Is not an Array" & @CRLF) ; if $networkRange is NOT an array then it is a "range" ; either passed as parameter by caller or generated by above checks $aArray = _GetIpAddressList($networkRange) ; Generate the list of IP to be pinged If @error Then Return SetError(5, 0, -1) ; IP range error EndIf ; ; _ArrayDisplay($aArray,"debug") ; $aArray should contain the IP to be pinged by _nPing ; ; *********************************************************************************************************** ; here start of nping core by Manadar (slightly modified) ; http://www.autoitscript.com/forum/topic/108060-nping-console-network-pinger-network-sweeper-network-scanner ; *********************************************************************************************************** If $ReturnFlag = 0 Then ; make room for all clients ReDim $_IPup[UBound($aArray) + 1][4] ; $_IPup will contain results EndIf Local $aProcess[$MAX_PROCESS] ; An array to keep a reference to spawned processes, in the next loop we fill it with value 0 for reference For $i = 0 To UBound($aProcess) - 1 $aProcess[$i] = 0 Next Local $i = 0 ; which IP are we currently trying to ping ( based on array ) Local $iFinished = 0 ; how many processes have finished pinging Local $iUp = 0 ; Total hosts that are UP Local $iDown = 0 ; Total hosts that are DOWN Local $iTotalRoundTrip = 0 ; Total roundtrip (all the +ms added together) While 1 ; We check all the currently running processes For $n = 0 To UBound($aProcess) - 1 ; Check if we need a spot, and there is an existing spot here If ($i <> UBound($aArray) And $aProcess[$n] == 0) Then $aProcess[$n] = _MSPing($i, $aArray[$i]) ; Start a new Ping process $i += 1 ; Increment $i so we can do the next process the next time around Else ; Check if this process has been spawned and the process is ready If ($aProcess[$n] <> 0 And _MSPingIsReady($aProcess[$n])) Then ; has finished to ping ; results of endings pings. (Get results from the various Pimg commands) $sHostname = _MSPingGetHostname($aProcess[$n]) $sResult = _MSPingGetResult($aProcess[$n]) $sIndex = ___MSPingGetIndex($aProcess[$n]) ; new, added by me (zero based) ; ConsoleWrite("debug: " & $sIndex & " : " & $sHostname & " : " & $sResult & @CRLF) ; -------------------------------------------------------------------------------------------------------------------------------------------------------------- If ($sResult <> -1) Then ; current IP is UP ; ConsoleWrite("debug: " & $sHostname & " has a roundtrip of " & $sResult & " ms" & @CRLF) $iUp += 1 If $ReturnFlag < 2 Then ; if return all(0) or responding only(1) If $ReturnFlag = 1 Then ; 1 = return back only responding IP ReDim $_IPup[$iUp + 1][4] $_IPup[$iUp][3] = $sIndex ; the index of the passed array that contains this IP $sIndex = $iUp Else ; $ReturnFlag = 0 Then keep all clients $sIndex += 1 $_IPup[$sIndex][3] = $sIndex - 1 EndIf $_IPup[$sIndex][0] = $sHostname If $Resolve Then ; ------------ resolve IP to hostname ------------ If _isIPaddr($_IPup[$sIndex][0]) Then ; is it an IP ? (or an hostname) If $dig Then ; resolve with dig if is present (much faster especially on passive devices without a host name) Local $digID = Run(".\dig\dig.exe -x " & $_IPup[$sIndex][0] & " +short", "", @SW_HIDE, 0x2) Do $_IPup[$sIndex][1] &= StdoutRead($digID) ; resolved IP to name (if resolvable else empty) Until @error Else ; _TCPIpToName is very slow to return if the remote IP do not belongs to a windows client (example a printer or a router) $_IPup[$sIndex][1] = _TCPIpToName($_IPup[$sIndex][0]) EndIf Else $_IPup[$sIndex][1] = $_IPup[$sIndex][0] EndIf EndIf ; End of name resolution ------------------------------------- $_IPup[$sIndex][2] = $sResult ; roundtrip of the ping $iTotalRoundTrip += $sResult EndIf Else ; current IP is down ---------------------------------------------------------------------------------------------------------------------------------------- $iDown += 1 If $ReturnFlag = 0 Then ; 0 return back all IP, responding and not responding $sIndex += 1 $_IPup[$sIndex][0] = $sHostname $_IPup[$sIndex][1] = -1 ; loockup name $_IPup[$sIndex][2] = -1 ; roundtrip $_IPup[$sIndex][3] = $sIndex - 1 ; ElseIf $ReturnFlag = 1 Then ; $ReturnFlag = 1 return only responding ; nothing to store ElseIf $ReturnFlag = 2 Then ; $ReturnFlag = 2 return only not responding ReDim $_IPup[$iDown + 1][4] $_IPup[$iDown][0] = $sHostname $_IPup[$iDown][1] = -1 $_IPup[$iDown][2] = -1 $_IPup[$iDown][3] = $sIndex $sIndex = $iDown EndIf EndIf ; *************************************************** ; Free up an empty space for the next address to Ping $aProcess[$n] = 0 ; Increment the total of processes that have finished $iFinished += 1 If ($sResult <> -1 And $ReturnFlag <> 2) Or ($sResult = -1 And $ReturnFlag <> 1) Then ; call an UDF to track and manage what's going on during the scan; ; an array is passed to the called function with the following 6 parameters: ; 0) nr. of total addresses under process ; 1) nr. of ping already finished ; 2) IP just processed ; 3) resolved Host name or -1 if IP is down ; 4) roundtrip of this ping or -1 if IP is down ; 5) Index of this IP within the caller's passed array ; by default is called the _Progress() function that will display the progress bar Local $aPass_Args[6] = [UBound($aArray), $iFinished, $_IPup[$sIndex][0], $_IPup[$sIndex][1], $_IPup[$sIndex][2], $_IPup[$sIndex][3]] Local $aArgs[2] = ["CallArgArray", $aPass_Args] Call($MyFunction, $aArgs) Else Local $aPass_Args[6] = [UBound($aArray), $iFinished, $sHostname, -1, -1, $sIndex] Local $aArgs[2] = ["CallArgArray", $aPass_Args] Call($MyFunction, $aArgs) EndIf ; If the total number of finished processes If ($iFinished == UBound($aArray)) Then ExitLoop 2 ; Exit -----+ EndIf ; | EndIf ; | Next ; | Sleep(50) ; Give existing ping commands some time to process the request | WEnd ; | ; <-------------------+ ; fill record [0] If $ReturnFlag = 0 Then ; return all $_IPup[0][0] = $iUp + $iDown $_IPup[0][1] = $iUp ; $iTotalRoundTrip ; $_IPup[0][2] = $iDown ElseIf $ReturnFlag = 1 Then ; return only up $_IPup[0][0] = $iUp $_IPup[0][1] = $iTotalRoundTrip ; $_IPup[0][2] = $iDown ElseIf $ReturnFlag = 2 Then ; return only down $_IPup[0][0] = $iDown $_IPup[0][1] = -1 ; $_IPup[0][2] = $iUp EndIf Return $_IPup ; - - - The end of scan - - - EndFunc ;==>_nPing Func _GetIpAddressList($ipFormat) ; Generate the IP list to Ping If $ipFormat = "" Then Return SetError(5, 0, -1) ; no IP to ping EndIf $ipFormat = StringReplace($ipFormat, "*", "1-255") ; change * with "1-255" $ipSplit = StringSplit($ipFormat, ".") If $ipSplit[0] <> 4 Then ; if it is not an IP address then check if it is an hostname Static $TCP = TCPStartup() Local $ret[1] = [TCPNameToIP($ipFormat)] ; from hostname to IP If @error Then Return SetError(6, @error, -1) ; windows API WSAGetError Windows Sockets Error in @extended Return $ret ; -----> return EndIf For $i = 1 To 4 ; controls once again If Not StringRegExp($ipSplit[$i], "[0-9\-]*") Then ; are 4 octets numbers Static $TCP = TCPStartup() Local $ret[1] = [TCPNameToIP($ipFormat)] ; if not number try to decode from host to IP If @error Then Return SetError(6, @error, -1) ; windows API WSAGetError. Windows Sockets Error in @extended Return $ret ; -----> return EndIf Next ; $ipFormat is not an hostname Local $ipRange[4][2], $totalPermu = 1 For $i = 0 To 3 If StringInStr($ipSplit[$i + 1], "-") Then ; control the presence of the "-" sign $m = StringSplit($ipSplit[$i + 1], "-") $ipRange[$i][0] = $m[1] $ipRange[$i][1] = $m[2] Else $n = Number($ipSplit[$i + 1]) $ipRange[$i][0] = $n $ipRange[$i][1] = $n EndIf $totalPermu *= $ipRange[$i][1] - $ipRange[$i][0] + 1 ; total number of IP to check If ($ipRange[$i][0] < 0 Or $ipRange[$i][0] > 255) Or ($ipRange[$i][1] < 0 Or $ipRange[$i][1] > 255) Then Return SetError(3, 0, -1) ; wrong IP Next If $totalPermu > 16777216 Then ; > $MAX_HOSTS Return SetError(1, String($totalPermu), -1) ; too many IP EndIf Local $result[$totalPermu], $i = 0 For $a = $ipRange[0][0] To $ipRange[0][1] For $b = $ipRange[1][0] To $ipRange[1][1] For $c = $ipRange[2][0] To $ipRange[2][1] For $d = $ipRange[3][0] To $ipRange[3][1] $result[$i] = $a & "." & $b & "." & $c & "." & $d ; $result contains the IP addresses to ping $i += 1 Next Next Next Next Return $result EndFunc ;==>_GetIpAddressList Func _Exit() Exit EndFunc ;==>_Exit Func _MSPing($Array_ndx, $sHostname, $timeout = 4000) ;$timeout = 50) ; start a new Ping Local $return_struc[5] ; [0] = Result (in ms) ; [1] = The hostname originally used ; [2] = Process handle (for internal use only) ; [3] = Buffer (for internal use only) ; [4] = Index of IP in source array **new** $return_struc[1] = $sHostname $return_struc[2] = Run("ping " & $sHostname & " -n 1 -w " & $timeout, "", @SW_HIDE, 0x2) ; 0x2 -> $STDOUT_CHILD) $return_struc[4] = $Array_ndx Return $return_struc EndFunc ;==>_MSPing Func _MSPingIsReady(ByRef $return_struc) ; check if Ping has finished Return ___MSPingReadOutput($return_struc) EndFunc ;==>_MSPingIsReady Func _MSPingGetResult($return_struc) Return $return_struc[0]; [0] = Result (in ms) EndFunc ;==>_MSPingGetResult Func _MSPingGetHostname($return_struc) ; returns the hostname Return $return_struc[1]; [1] = The hostname originally used EndFunc ;==>_MSPingGetHostname ; Internal use only Func ___MSPingReadOutput(ByRef $return_struc) ; peek result of DOS Ping command $data = StdoutRead($return_struc[2]) ; [2] = Process handle (for internal use only) If (@error) Then ; if ping has finished ___MSPingParseResult($return_struc) ; extract time taken by ping Return 1 ; 1 = finished Else $return_struc[3] &= $data ; [3] = Buffer (for internal use only) ; contains DOS output Return 0 ; 0 = not yet finished EndIf EndFunc ;==>___MSPingReadOutput ; Internal use only Func ___MSPingParseResult(ByRef $return_struc) ; extract from Ping command the millisecond value $result = StringRegExp($return_struc[3], "([0-9]*)ms", 3); [3] = DOS command output is here If @error Then $return_struc[0] = -1 ; [0] = Result (in ms) -1 if error Else $return_struc[0] = $result[0] ; returns the first millisecond value retrieved from Ping EndIf EndFunc ;==>___MSPingParseResult ; Internal use only - new (added by me) Func ___MSPingGetIndex(ByRef $return_struc) ; Index of the current IP in passed array Return $return_struc[4] EndFunc ;==>___MSPingGetIndex ; = = = = = net related functions = = = = = Func _Make_Range($ipLan, $sMask) ; Given an IP and his mask, this function return the full LAN "range" for _nPing Local $aLan = _GetLanParameters($ipLan, $sMask) If @error Then Return SetError(@error, @extended, -1) Return $aLan[7][0] EndFunc ;==>_Make_Range Func _GetLanParameters($theIP1, $sSubNet) ; ------------------------------------------ ; calculate all IP/subnet related parameters ; ------------------------------------------ If Not _isIPaddr($theIP1) Then Return SetError(3, 0, -1) ; wrong IP address ;check on subnet If Not _isSNmask($sSubNet) Then ; it is not a valid 4 digit subnet If $sSubNet > 0 And $sSubNet < 33 Then ; is it a CIDR notation number? nr. of bits 1 to 32 $sSubNet = _CIDR_To_Mask($sSubNet) Else Return SetError(4, 0, -1) ; wrong Mask provided EndIf EndIf Local $aLan[8][5] ; net parameters container Local $sDot[2] = ['', '.'] ; used as IP octets separator Local $aIP = StringSplit($theIP1, '.'), $aSubNet = StringSplit($sSubNet, '.') ; split IP address in single octets and calculate related parameters For $i = 1 To 4 $aLan[0][$i] = $aIP[$i] ; IP $aLan[1][$i] = $aSubNet[$i] ; NetMask $aLan[2][$i] = BitNOT($aLan[1][$i] - 256) ; Wildcard, is the inverse of subnet: BitNot($NetMask - 256) $aLan[3][$i] = BitAND($aLan[0][$i], $aLan[1][$i]) ; LanAddress BitAnd(IP, netmask) $aLan[4][$i] = BitOR($aLan[0][$i], $aLan[2][$i]) ; Broadcast address $aLan[5][$i] = $aLan[3][$i] ; preset First host ; will be $NetAddress + 1 $aLan[6][$i] = $aLan[4][$i] ; preset Last host ; will be $Broadcast -1 Next If $sSubNet <> "255.255.255.255" Then $aLan[5][4] = BitOR($aLan[5][4], 1) ; First host $NetAddress + 1 (Turn last bit ON) $aLan[6][4] = BitAND($aLan[6][4], 254) ; Last host $Broadcast -1 (Turn last bit OFF) EndIf For $i = 1 To 4 $aLan[0][0] &= $aLan[0][$i] & $sDot[$i < 4] ; [0] IP $aLan[1][0] &= $aLan[1][$i] & $sDot[$i < 4] ; [1] NetMask $aLan[2][0] &= $aLan[2][$i] & $sDot[$i < 4] ; [2] Wildcard $aLan[3][0] &= $aLan[3][$i] & $sDot[$i < 4] ; [3] Network $aLan[4][0] &= $aLan[4][$i] & $sDot[$i < 4] ; [4] Broadcast $aLan[5][0] &= $aLan[5][$i] & $sDot[$i < 4] ; [5] First host $aLan[6][0] &= $aLan[6][$i] & $sDot[$i < 4] ; [6] Last host ; [7][0] Range for _nPing If $aLan[5][$i] = $aLan[6][$i] Then $aLan[7][0] &= $aLan[5][$i] & $sDot[$i < 4] Else $aLan[7][0] &= $aLan[5][$i] & "-" & $aLan[6][$i] & $sDot[$i < 4] EndIf Next ; MsgBox(0, "net", "IP address: " & @TAB & $aLan[0][0] & @CRLF & "Subnet: " & @TAB & $aLan[1][0] & @CRLF & "Wildcard: " & @TAB & $aLan[2][0] & @CRLF & "Network: " & @TAB & $aLan[3][0] & @CRLF & "Broadcast: " & @TAB & $aLan[4][0] & @CRLF & "First host: " & @TAB & $aLan[5][0] & @CRLF & "Last host: " & @TAB & $aLan[6][0]) ; _ArrayDisplay($aLan, "IP/subnet related parameters") Return $aLan EndFunc ;==>_GetLanParameters ; #FUNCTION# ==================================================================================================================== ; Name...........: _LanParameters ; Description ...: given an IP and his subnet returns [and displays] the following values in dec and binary format: ; |IP Address ; |Netmask ; |Wildcard ; |Network Address ; |Broadcast Address ; |First host ; |Last host ; Syntax.........: _LanParameters([$IP, $Subnet]) ; Parameters ....: ; ; Return values .: ; Author ........: ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........: ; Example .......: ; =============================================================================================================================== Func _LanParameters($theIP1 = "", $sSubNet = "255.255.255.255", $Msg = 0) Static $TCP = TCPStartup() If $theIP1 = "" Then $theIP1 = TCPNameToIP(@ComputerName) $sSubNet = _GetSubnetMask($theIP1) ElseIf $sSubNet = "" Then $sSubNet = "255.255.255.255" EndIf If Not _isSNmask($sSubNet) Then ; it is not a 4 digit subnet If $sSubNet > 0 And $sSubNet < 33 Then ; is it a CIDR notation number? nr. of bits 1 to 32 $sSubNet = _CIDR_To_Mask($sSubNet) Else Return SetError(4, 0, False) ; wrong mask EndIf EndIf Local $aLan = _GetLanParameters($theIP1, $sSubNet) Local $LanID[7][3] $LanID[0][0] = "IP Address " $LanID[1][0] = "Netmask " $LanID[2][0] = "Wildcard " $LanID[3][0] = "Network Address " $LanID[4][0] = "Broadcast Address" $LanID[5][0] = "First host " $LanID[6][0] = "Last host " For $i = 0 To 6 $LanID[$i][1] = $aLan[$i][0] $LanID[$i][2] = _Convert_To_Binary($aLan[$i][1]) & "." & _Convert_To_Binary($aLan[$i][2]) & "." & _Convert_To_Binary($aLan[$i][3]) & "." & _Convert_To_Binary($aLan[$i][4]) Next If $Msg Then MsgBox(0, "Lan IDs", $LanID[0][0] & @TAB & $LanID[0][2] & @TAB & $LanID[0][1] & @CRLF & _ $LanID[1][0] & "( " & _Mask_To_CIDR($LanID[1][1]) & " ) " & @TAB & $LanID[1][2] & @TAB & $LanID[1][1] & @CRLF & _ $LanID[2][0] & @TAB & $LanID[2][2] & @TAB & $LanID[2][1] & @CRLF & _ $LanID[3][0] & @TAB & $LanID[3][2] & @TAB & $LanID[3][1] & @CRLF & _ $LanID[4][0] & @TAB & $LanID[4][2] & @TAB & $LanID[4][1] & @CRLF & _ $LanID[5][0] & @TAB & $LanID[5][2] & @TAB & $LanID[5][1] & @CRLF & _ $LanID[6][0] & @TAB & $LanID[6][2] & @TAB & $LanID[6][1] & @CRLF) Return $LanID EndFunc ;==>_LanParameters ; #FUNCTION# ==================================================================================================================== ; Name...........: _CIDR_To_Mask ; Description ...: transform a CIDR number (1 - 32) to the corresponding 4 digit mask ; Syntax.........: _CIDR_To_Mask($CIDR) ; Parameters ....: $CIDR a number from 1 to 32 ; Return values .: a 4 bite corresponding subnet mask ; =============================================================================================================================== Func _CIDR_To_Mask($sSubNet) ; From nr. of bit to 4 digit mask $sSubNet = StringLeft(StringLeft("11111111111111111111111111111111", $sSubNet) & "0000000000000000000000000000000", 32) $sSubNet = _Bin_To_Dec(StringLeft($sSubNet, 8)) & "." & _Bin_To_Dec(StringMid($sSubNet, 9, 8)) & "." & _Bin_To_Dec(StringMid($sSubNet, 17, 8)) & "." & _Bin_To_Dec(StringRight($sSubNet, 8)) Return $sSubNet EndFunc ;==>_CIDR_To_Mask ; #FUNCTION# ==================================================================================================================== ; Name...........: _Mask_To_CIDR ; Description ...: transform a 4 digit mask to the corresponding CIDR number (1 - 32) ; Syntax.........: _Mask_To_CIDR($SubnetMask) ; Parameters ....: $SubnetMask a 4 bite subnet mask ; Return values .: the corresponding CIDR ; =============================================================================================================================== Func _Mask_To_CIDR($sSubNet) ; from 4 digit mask to nr. of bits If _isSNmask($sSubNet) Then Local $Digit = StringSplit($sSubNet, ".", 2) Return StringInStr(_Convert_To_Binary($Digit[0]) & _Convert_To_Binary($Digit[1]) & _Convert_To_Binary($Digit[2]) & _Convert_To_Binary($Digit[3]), "1", 0, -1) Else Return SetError(4, 0, False) ; wrong mask EndIf EndFunc ;==>_Mask_To_CIDR ; _GetSubnetMask ; #FUNCTION# ==================================================================================================================== ; Name...........: _GetSubnetMask ; Description ...: given the local IP returns the related subnet mask (thanks to dragan) ; http://www.autoitscript.com/forum/topic/155078-how-to-easily-get-the-subnet-mask/?p=1120929 ; Syntax.........: _GetSubnetMask($LocalIP) ; Parameters ....: $LocalIP IP of the local computer ; Return values .: the corresponding subnet mask ; =============================================================================================================================== Func _GetSubnetMask($theIP) ; given the local IP returns the related subnet mask Local Const $tagIP_ADDRESS_STRING = "char IPAddress[16];" Local Const $tagIP_MASK_STRING = "char IPMask[16];" Local Const $tagIP_ADDR_STRING = "ptr Next;" & $tagIP_ADDRESS_STRING & $tagIP_MASK_STRING & "DWORD Context;" Local Const $tagIP_ADAPTER_INFO = "ptr Next; DWORD ComboIndex; char AdapterName[260];char Description[132]; UINT AddressLength; BYTE Address[8]; dword Index; UINT Type;" & _ " UINT DhcpEnabled; ptr CurrentIpAddress; ptr IpAddressListNext; char IpAddressListADDRESS[16]; char IpAddressListMASK[16]; DWORD IpAddressListContext; " & _ "ptr GatewayListNext; char GatewayListADDRESS[16]; char GatewayListMASK[16]; DWORD GatewayListContext; " & _ "ptr DhcpServerNext; char DhcpServerADDRESS[16]; char DhcpServerMASK[16]; DWORD DhcpServerContext; " & _ "int HaveWins; " & _ "ptr PrimaryWinsServerNext; char PrimaryWinsServerADDRESS[16]; char PrimaryWinsServerMASK[16]; DWORD PrimaryWinsServerContext; " & _ "ptr SecondaryWinsServerNext; char SecondaryWinsServerADDRESS[16]; char SecondaryWinsServerMASK[16]; DWORD SecondaryWinsServerContext; " & _ "DWORD LeaseObtained; DWORD LeaseExpires;" Local $dll = DllOpen("Iphlpapi.dll") If @error Then Return SetError(8, @error, 0); <----------- error 'dll open: Iphlpapi.dll' Local $ret = DllCall($dll, "dword", "GetAdaptersInfo", "ptr", 0, "dword*", 0) If @error Then DllClose($dll) Return SetError(8, @error, 0); <----------- error 'dll call function: GetAdaptersInfo' EndIf Local $adapterBuffer = DllStructCreate("byte[" & $ret[2] & "]") Local $adapterBuffer_pointer = DllStructGetPtr($adapterBuffer) DllCall($dll, "dword", "GetAdaptersInfo", "ptr", $adapterBuffer_pointer, "dword*", $ret[2]) If @error Then $adapterBuffer = "" $adapterBuffer_pointer = "" DllClose($dll) Return SetError(8, @error, 0); <----------- error 'dll call function: GetAdaptersInfo with adapter buffer pointer' EndIf Local $adapter = DllStructCreate($tagIP_ADAPTER_INFO, $adapterBuffer_pointer) Local $IPType = -1 Local $FoundIt = False Local $retVal = "" Do ; -------------------- IP search -------------------- $Ptr = DllStructGetPtr($adapter, "IpAddressListNext") Local $IPStruct, $Index = 0 Local $allArray[1][3] Do ReDim $allArray[$Index + 1][3] $IPStruct = DllStructCreate($tagIP_ADDR_STRING, $Ptr) $allArray[$Index][0] = DllStructGetData($IPStruct, "IPAddress") $allArray[$Index][1] = DllStructGetData($IPStruct, "IPMask") $allArray[$Index][2] = DllStructGetData($IPStruct, "Context") $Ptr = DllStructGetData($IPStruct, "Next") $Index += 1 Until $Ptr = 0 For $i = 0 To UBound($allArray) - 1 If $allArray[$i][0] <> $theIP Then ContinueLoop ; >-+ $retVal = $allArray[$i][1] ; | $IPType = 0 ; | $FoundIt = True ; | ExitLoop ; if found do not search over | Next ; <-------+ If $FoundIt Then ExitLoop ; >---------------------------+ $Ptr = DllStructGetData($adapter, "Next") ; | $adapter = DllStructCreate($tagIP_ADAPTER_INFO, $Ptr); | Until @error ; | ; <---------------------------+ $adapterBuffer = "" $adapterBuffer_pointer = "" DllClose($dll) If Not $FoundIt Then Return SetError(3, 0, 0) ; IP not found <----------- error Return SetError(0, $IPType, $retVal) ; OK Return mask EndFunc ;==>_GetSubnetMask Func _isIPaddr($sIPAddr) ; returns true if argument is a plausible IP address If Not StringRegExp($sIPAddr, "^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$") Then Return SetError(1, 0, False) Return True EndFunc ;==>_isIPaddr Func _isSNmask($sSNmask) ; returns true if argument is a correct 4 digit network mask If Not StringRegExp($sSNmask, "^(((255\.){3}(255|254|252|248|240|224|192|128|0+))|((255\.){2}(255|254|252|248|240|224|192|128|0+)\.0)|((255\.)(255|254|252|248|240|224|192|128|0+)(\.0+){2})|((255|254|252|248|240|224|192|128|0+)(\.0+){3}))$") Then Return SetError(1, 0, False) Return True EndFunc ;==>_isSNmask Func _Progress($aArgs) ; Func _Progress($ToDo, $Done, $Dummy1, $Dummy2, $Dummy3, $Dummy4) ; this will show the progress bar while scanning ; $_Percent = Int($Done / $ToDo * 100) $_Percent = Int($aArgs[1] / $aArgs[0] * 100) Static $_Progress = 0 If Not $_Progress Then ProgressOn("Progress Meter", "Pinged address ", $aArgs[1] & "/" & $aArgs[0] & " ( 0 %)", -1, -1, 16) $_Progress = 1 EndIf ProgressSet($_Percent, $aArgs[1] & "/" & $aArgs[0] & " ( " & $_Percent & " %)", "Pinged address " & $aArgs[2]) If $_Percent = 100 Then ProgressSet(100, "Done", "Complete") Sleep(500) ProgressOff() $_Progress = 0 EndIf EndFunc ;==>_Progress Func _Convert_To_Binary($iNumber) ; from decimal to binary ; http://www.autoitscript.com/forum/topic/90056-decimal-to-binary-number-converter/?p=647505 Local $sBinString = "" While $iNumber $sBinString = BitAND($iNumber, 1) & $sBinString $iNumber = BitShift($iNumber, 1) WEnd ; limit returned value to 8 bit 0 - 255 Return StringRight("00000000" & $sBinString, 8) EndFunc ;==>_Convert_To_Binary Func _Bin_To_Dec($BinNum) ; from binary to decimal Local $dec = 0 For $i = 0 To StringLen($BinNum) - 1 $dec += 2 ^ $i * StringMid($BinNum, StringLen($BinNum) - $i, 1) Next Return $dec EndFunc ;==>_Bin_To_Dec ; #FUNCTION# ==================================================================================================================== ; Name...........: _FileReadToArray_mod ; Description ...: read a file to an array and if is passed a separator and a column number extract only that column (from a csv) ; Syntax.........: _FileReadToArray_mod($sFilePath, $delim = ";") ; Parameters ....: |$sFilePath - path and filename of the file to read ; |$delim - the character separator of the values in the csv ; Remarks .......: if the file is not a csv and contains only one IP per line then $delim is ignored ; Return values .: an 1D array containing the "IP" extracted from the $col column. First column is nr.0 ; =============================================================================================================================== ; Func _FileReadColumnToArray($sFilePath, $delim = ";", $col = 0) Func _FileReadToArray_mod($sFilePath, $delim = ";") ; this function is extracted, adapted and slightly modified from the _FileReadToArray() function in file.au3 Local $aArray Local $hFile = FileOpen($sFilePath, 0); $FO_READ) If $hFile = -1 Then Return SetError(1, 0, 0);; unable to open the file ;; Read the file and remove any trailing white spaces Local $aFile = FileRead($hFile, FileGetSize($sFilePath)) FileClose($hFile) ;~ $aFile = StringStripWS($aFile, 2) ; remove last line separator if any at the end of the file If StringRight($aFile, 1) = @LF Then $aFile = StringTrimRight($aFile, 1) If StringRight($aFile, 1) = @CR Then $aFile = StringTrimRight($aFile, 1) If StringInStr($aFile, @LF) Then $aArray = StringSplit(StringStripCR($aFile), @LF) ElseIf StringInStr($aFile, @CR) Then ;; @LF does not exist so split on the @CR $aArray = StringSplit($aFile, @CR) Else ;; unable to split the file If StringLen($aFile) Then Dim $aArray[2] = [1, $aFile] ; returns the whole file in one element Else Return SetError(2, 0, 0) ; File is empty EndIf EndIf ; now split 1D $aArray to 2D $aColumns according to delimiter Local $aColumns[$aArray[0]][1] ; create a new [2D] array with same nr. of lines of $aArray For $i = 1 To $aArray[0] ; scan all lines of the array $TempRow = StringSplit($aArray[$i], $delim, 2) ; split the line If UBound($TempRow) > UBound($aColumns, 2) Then ReDim $aColumns[$aArray[0]][UBound($TempRow)] For $ii = 0 To UBound($TempRow) - 1 $aColumns[$i - 1][$ii] = $TempRow[$ii] Next Next Return $aColumns EndFunc ;==>_FileReadToArray_mod Func _ExtractColumnFromArray($aArray, $col = 0) If 1 = UBound($aArray, 0) Then If $col = 0 Then Return $aArray ; already a single column array, send it back as is Else Return SetError(2, 0, -1) ; wrong column number EndIf EndIf If $col >= UBound($aArray, 2) Then Return SetError(2, 0, -1) ; wrong column number Local $aColumn[UBound($aArray)] ; create a new [1D] array For $i = 0 To UBound($aArray) - 1 ; scan all lines of the array $aColumn[$i] = $aArray[$i][$col] Next Return $aColumn EndFunc ;==>_ExtractColumnFromArray Basic Example of use: #include 'MultiPing.au3' #include <array.au3> MsgBox(0, "Hello", "The _nPing() function will ping ranges of IP addresses" & @CRLF & @CRLF & _ "if called without arguments, it will try to detect your LAN parameters" & @CRLF & _ "and then will ping all your LAN addresses, returninig a list of responding IP." & @CRLF & @CRLF & _ "First a detection of the LAN is performed and result displayed" & @CRLF & @CRLF & _ "Press OK to detect:") $lan = _LanParameters("", "", 1) ; with the first 2 argument blank, will detect local LAN ; the third parameter 1 means show results MsgBox(0, "Hello", "OK, now the full IP range will be pinged." & @CRLF & "In this example only the addresses of responding devices" & @CRLF & _ "will be returned in the array (default)," & @CRLF & _ "but the function can also return:" & @CRLF & _ " 0 the whole list of IPs" & @CRLF & _ " 1 only responding IPs" & @CRLF & _ " 2 only not responding IPs" & @CRLF & @CRLF & _ "Press OK to ping from IP " & $lan[5][1] & " to IP " & $lan[6][1]) ; simplest way to use: without parameters ; will scan all your local LAN ; and display only responding IP Local $Result = _nPing() If @error Then MsgBox(0, "", "@error " & @error) _ArrayDisplay($Result) MsgBox(0, "", "Another way to use is to read a list of IP from a file (csv or single column)" & @CRLF & _ "into an array and pass the array to the function" & @CRLF & _ "if the array is 1D then is passed as is" & @CRLF & _ "if the array is 2D (because a csv was read) the first column is passed," & @CRLF & _ "but if you want to pass another column of the 2D array then" & @CRLF & _ "just pass the column number (zero based) as second parameter (first column is 0)" & @CRLF & _ "In this example the IP are in column 1" & @CRLF & @CRLF & _ "Press OK to read the file") ; read the file in an array ; use the ";" as fields separator $IPlist = _FileReadToArray_mod(".\IP_List.txt", ";") If Not @error Then _ArrayDisplay($IPlist, "Data read from file") ; show array content $Result = _nPing($IPlist, 1); pass the second column to the function If @error Then MsgBox(0, "", "@error " & @error) _ArrayDisplay($Result) ; display the result of the pings Else MsgBox(0, "", "@error " & @error) EndIf IP_List.txt Google;173.194.36.50 AutoIT;87.106.181.57 YouTube;74.125.228.65 Google.com;74.125.224.72 Gmail.com;74.125.224.181 Bing.com;131.253.13.32 Hotmail.com;65.55.72.135 Yahoo.com;98.139.183.24 Amazon.com;72.21.211.176 Facebook.com;69.171.234.21 Facebook.com;69.63.176.13 Facebook.com;69.63.181.15 Facebook.com;69.63.184.142 Facebook.com;69.63.187.17 Facebook.com;69.63.187.18 Facebook.com;69.63.187.19 Facebook.com;69.63.181.11 Facebook.com;69.63.181.12 Twitter.com;199.59.148.10 Twitter.com;199.59.149.230 LinkedIn.com;216.52.242.86 WordPress.com;76.74.254.126 WordPress.org;72.233.56.138 Tumblr.com;174.121.194.34 Livejournal.com;209.200.154.225 Reddit.com;64.208.126.67 Imgur.com;173.231.140.219 Pinterest.com;23.21.142.179 Instagram.com;23.23.130.59 Stickam.com;67.201.54.151 Blogtv.com;84.22.170.149 Justin.tv;199.9.249.21 ChatRoulette.com;184.173.141.231 Newegg.com;216.52.208.187 ThePirateBay.org;194.71.107.50 Movie2k.com;109.163.226.240 PayPal.com;173.0.84.3 Botcrawl.com;174.132.77.244
-
PDH Performance Counters Measure Process, CPU, Network, Process, Disk (etc) Usage (note that the above dialog appears differently on Vista+) New ObjectBase interface!! *x64 and Localization Issues have been resolved!* *Download and License agreement are at the bottom of this post! About The Project: Performance Counters gather all kind of performance data about the PC and the Network using the standard PDH.DLL module (standard since Windows 2000). Among the performance data you can collect and monitor are: Processor Stats (including total usage)Process (programs) Stats (including CPU usage)Disk Stats (speed/access)TCP, UDP, IP Connection Counts, Speed/Error StatsNetwork Stats..and so onNote that one example is a WIP. 'TaskManager' mockup UDF, I'm looking at you. You can jump right in, download the two AutoIT files (below) and run one of the following to see what the PDH Performance Counters project can get you: TestPDH_PerformanceCounters - this is where you should start! It allows you to visually experiment with most all of the Counters available on your PC and Network. NOTES: - Currently the 'Refresh' rate is set to 1/2 second - this can be changed by altering the Adlib() function frequency - New Counters that come into existence during monitoring will *not* be added to the list (this would be a function I've yet to add) - Counters that become invalid are simply given a prefix of '[Dead Counter Handle]:' TestPDH_ProcessLoop - this basically repeatedly shows an extended Process-information list for all processes. NOTE: You must hit 'ESC' to exit the loop TestPDH_TaskManager - this gathers and displays most everything you'd see in the Process and Performance sections of Task Manager. NOTES: - The screen does NOT update, and the UDF is a MESS. This is due to a number of reasons - the biggest one being laziness on my behalf. Plus I need to figure out how best to manage ListView changes. - TWO fields need Windows XP+ to display correctly (or a version of psapi.dll that supports 'GetPerformanceInfo'): Commit Charge (Peak) and System Cache TestPDH_ProcessGetRelatives - this shows how the PDH Performance Counters can be used to get 'parent' and 'children' process information. There are more practical means of getting this info of course (a few you'll see in my 'Process Functions' module, but hey - its just yet another example of what can be done.TestPDH_ObjectTests - this is more for reading/understanding the code than anything. It is there to show how the new 'ObjectBase' Interface works to make coding Performance Counters *much* easier.Multipile extra 'TestPDH*' examplesAt its most basic, interacting with Performance Counters is as such: The brand new ObjectBase Interface removes some of the difficulty in interacting with Performance Counters, and works like this: Examples of the new ObjectBase interface: % CPU Usage of a Process % CPU Usage of Multiple Instances of a Process (+monitoring and adjustment based on new/dead Instances) Other Examples: Waiting for Hard Disk activity to Idle for 'x' ms % System CPU Usage (by Processor) Network Usage (bytes sent/received) I've put a LOT of work into this project, and all I ask is that you follow my License Agreement when using the code (very easy, see below). Any feedback is welcome. I apologize for the unpolished GUI interfaces (especially the unfinished one), but I will get to that TaskManager GUI one day, hah. Enough chatter -now go on and experience the awesome power of Performance Counters Download the ZIP Here NOTE: Bundled in the ZIP (and included in the License agreement) are other UDF's I wrote that are necessary to run some of the 'Test' programs:_WinAPI_GetSystemInfo.au3, _WinAPI_GetPerformanceInfo.au3, _WinTimeFunctions.au3, and the unnecessary, but provided for those who are interested in the _WinTimeFunctions 'filetime' usage, program: TestWinTimeFunctions.au3. Ascend4nt's AutoIT Code License agreement: While I provide this source code freely, if you do use the code in your projects, all I ask is that: If you provide source, keep the header as I have put it, OR, if you expand it, then at least acknowledge me as the original author, and any other authors I creditIf the program is released, acknowledge me in your credits (it doesn't have to state which functions came from me, though again if the source is provided - see #1)The source on it's own (as opposed to part of a project) can not be posted unless a link to the page(s) where the code were retrieved from is provided and a message stating that the latest updates will be available on the page(s) linked to.Pieces of the code can however be discussed on the threads where Ascend4nt has posted the code without worrying about further linking.Enjoy!Ascend4nt UPDATES:
- 135 replies
-
- performance counters
- monitor
-
(and 8 more)
Tagged with:
-
Hi to all, I was wondering how to do something like this powershell command: Get-NetConnectionProfile -InterfaceAlias "Ethernet" | Set-NetConnectionProfile -NetworkCategory Private -Confirm:$false -PassThru natively, or bypassing powershell, in AutoIt. My goal is to change the state of the current network connection from public to private and viceversa. And looking beyond, to enable/disable network discovery, network crypt properties, sharing options etc....
- 7 replies
-
- network
- networking
-
(and 1 more)
Tagged with:
-
Version 4.0.0-beta
1,059 downloads
Version 2.x.x and 3.x.x has been moved to branch 3.x About Autoit-Socket-IO Autoit-Socket-IO is a event driven TCP/IP wrapper heavily inspired from Socket.IO with focus on user friendliness and long term sustainability. I constantly want to make this UDF faster and better, so if you have any suggestions or questions (beginner and advanced) Do not hesitate to ask them, I will gladly help! Key features Simple API 99% data-type serialization thanks to Autoit-Serialize Can easily be extended with your own functionality thanks to Autoit-Events "Educational" examples Data encryption thanks to _<Crypt.au3> Limitations Speed. This UDF will sacrifice some speed for convenience Read more in the official thread-
- socket-io
- autoit-sockets
-
(and 2 more)
Tagged with:
-
Hello, This is my first post. So Iâve worked on a script for a while and Iâm planning to publish it but the problem is that it connects to an FTP server at some point, and as you probably know FTP credentials are easily captured by a MITM attack or Wireshark (not sure if Wireshark does). So I thought if i can detect data capturing in the userâs network the script would stop. Any idea?. If thereâs another workaround Iâm happy to hear it.
-
Hi guys, It's been a while since I wrote my last message here and a while since I used AutoIt. I'm currently sort of desperate and I'm trying to find some help in regards of getting the network usage per process! I'm not interested in the total network usage of the NIC, but only on a specific PID's network utilization. They idea is to collect the amount of traffic uploaded and downloaded by a list of specific processes. So far Process Hacker and Process Explorer are capable of getting what I need, but I need to use these numbers in another script so they're sort of useless to me. I can't seem to find a way around it. Any idea, help is greatly appreciated. Thanks
-
-
So I having issues with this GUI/Listview. My main GUI works like it needs to but the ListView GUIs don't. The exit buttons do not work on them and om have a hard time getting them to work. And I'm trying to make the listview GUI resizeable. But I'm not sure how to fix either of these issues any thoughts. #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <File.au3> #include <ScreenCapture.au3> #include <MsgBoxConstants.au3> #include <WinAPIFiles.au3> #include <Array.au3> #include <GuiListView.au3> #include <GuiImageList.au3> #include <ListviewConstants.au3> #include 'MultiPing.au3' Opt("GUIOnEventMode", 1) #Region ;Declares ; Reads text file for the base list of IP's Global $aBase_IPlist = _FileReadToArray_mod(".\IP_List.txt") Global $replace2 = "Second" Global $replace3 = "Thrid" ;Global $userdata1 = GUICtrlRead($data1) ;Global $userdata2 = GUICtrlRead($data2) Global $savefolder = "C:\Users\" Global $paths = "\Desktop\PingChecks" Global $1stpaths = "\~~~Store" Global $2ndpaths = "~~~" Global $results = FileExists($savefolder & @UserName & $paths) ;Global $foldercheck = FileExists($savefolder & @UserName & $paths & $1stpaths & $userdata1 & $userdata2 & $2ndpaths) ;Global $savefile = "C:\Users\" & @UserName & "\Desktop\PingChecks\~~~Store" & $userdata1 & $userdata2 & "~~~\" #EndRegion ;Declares #Region ### START Koda GUI section ### Form= $IPMonkey = GUICreate("IP Monkey", 573, 254, -1, -1) GUISetIcon("C:\Users\Dlex\Pictures\monkeyicon.ico", -1) GUISetFont(16, 800, 0, "Arial") GUISetBkColor(0xFFFFFF) GUISetOnEvent($GUI_EVENT_CLOSE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_MINIMIZE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_MAXIMIZE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_RESTORE, "SpecialEvents") $data1 = GUICtrlCreateInput("1", 184, 120, 89, 32, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER)) GUICtrlSetColor(-1, 0x000000) $data2 = GUICtrlCreateInput("23", 280, 120, 89, 32, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER)) GUICtrlSetColor(-1, 0x000000) $GOButton = GUICtrlCreateButton("GO", 80, 192, 75, 25) GUICtrlSetFont(-1, 10, 800, 0, "Arial") GUICtrlSetColor(-1, 0x000000) GUICtrlSetBkColor(-1, 0x00FF00) GUICtrlSetTip(-1, "Runs A Live Continuous Ping" & @CRLF & _ "Until Told Other Wise") GUICtrlSetOnEvent(-1, "GOButtonClick") $quickscan = GUICtrlCreateButton("Quick Scan", 224, 192, 107, 25) GUICtrlSetFont(-1, 12, 800, 0, "Arial") GUICtrlSetColor(-1, 0x000000) GUICtrlSetBkColor(-1, 0xFFFF00) GUICtrlSetOnEvent(-1, "quickscanClick") GUICtrlSetTip(-1, "Quickly Scans, Then Saves" & @CRLF & _ "Results In Your 'PingChecks' " & @CRLF & _ "Folder Under Your Store Number Folder") Global $exitbutton = GUICtrlCreateButton("Exit", 416, 192, 75, 25) GUICtrlSetFont(-1, 12, 800, 0, "Arial") GUICtrlSetColor(-1, 0x000000) GUICtrlSetBkColor(-1, 0xFF0000) GUICtrlSetTip(-1, "What Do You Think This Button Does?") GUICtrlSetOnEvent(-1, "exitbuttonClick") $titlebar = GUICtrlCreateLabel("IP Monkey", 16, 120, 107, 28) GUICtrlSetColor(-1, 0x000000) $Pic1 = GUICtrlCreatePic("C:\Users\Dlex\Pictures\monkeyicon-0.jpg", 16, 16, 100, 100) GUICtrlSetOnEvent(-1, "Pic1Click") $infobutton = GUICtrlCreateButton("?", 536, 8, 27, 25) GUICtrlSetColor(-1, 0x000000) GUICtrlSetBkColor(-1, 0xFF8000) GUICtrlSetTip(-1, "Unsure what to do?" & @CRLF & _ "This will get give you " & @CRLF & _ "the help for IP Monkey") GUICtrlSetOnEvent(-1, "infobuttonClick") $Whatstorelabel = GUICtrlCreateLabel("What Store?", 208, 56, 130, 28) GUICtrlSetColor(-1, 0x000000) GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### #Region ;ping gui ; ------ pinger GUI ------------------- Global $StopPing = 0 Local $Win_X = 1200, $Win_Y = 880 ; dimension of window Global $PingGui = GUICreate("IP Monkey", $Win_X, $Win_Y, -1, -1) GUISetOnEvent($GUI_EVENT_CLOSE, "SpecialEvents") Global $listview = GUICtrlCreateListView("", 10, 10, $Win_X - 20, $Win_Y - 40) GUICtrlSetFont(-1, 8) $button1 = GUICtrlCreateLabel("Hit Exit To Quit", 10, $Win_Y - 25, $Win_X - 20, 20, -1,$ES_CENTER) GUICtrlSetFont(-1, 10, 800) GUICtrlSetTip(-1, "exit") GUICtrlSetOnEvent(-1, 'SpecialEvents') GUICtrlSetStyle($listview, $LVS_ICON) ; + $LVS_NOLABELWRAP) GUISetState(@SW_HIDE) ; hidden at startup ; --------- end of pinger gui ------------- #EndRegion ;ping gui ; Generate colored square images $hImage = _GUIImageList_Create(30, 30) _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0xFFFF00, 30, 30)) ; yellow _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0xFF0000, 30, 30)) ; red _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0x00FF00, 30, 30)) ; green _GUICtrlListView_SetImageList($listview, $hImage, 0) While 1 Sleep(100) WEnd Func exitbuttonClick() MsgBox(0,'0','0') Exit EndFunc ;==>exitbuttonClick Func GOButtonClick() $userdata1 = GUICtrlRead($data1) $userdata2 = GUICtrlRead($data2) ; pass the wanted new octet replace_And_Go($userdata1, $userdata2) ; generate a list of new IP and Go EndFunc ;==>GOButtonClick Func infobuttonClick() EndFunc ;==>infobuttonClick Func Pic1Click() EndFunc ;==>Pic1Click Func quickscanClick() $userdata1 = GUICtrlRead($data1) $userdata2 = GUICtrlRead($data2) replace_And_Go2($userdata1, $userdata2) EndFunc ;==>quickscanClick Func SpecialEvents() Select Case @GUI_CtrlId = $GUI_EVENT_CLOSE _button1() Case @GUI_CtrlId = $GUI_EVENT_MINIMIZE Case @GUI_CtrlId = $GUI_EVENT_RESTORE Case @GUI_CtrlId = $GUI_EVENT_MAXIMIZE EndSelect EndFunc ;==>SpecialEvents #Region ; Main_GO/Replace_and_GO #cs ############################## second script ############################################# ; this is to ping continuously a list of IP addresses, get and display ping result "live" ; it simulates the dos "ping -t" command but performed simultaneously on many IP ; presenting the results in a ListView highlighting not responding devices with a red box #ce Func replace_And_Go($s_2, $s_3) ; Create a new array wit a new list of IP according to passed second and third octet Local $aNew_IPlist = $aBase_IPlist For $i = 0 To UBound($aNew_IPlist) - 1 $aNew_IPlist[$i][1] = StringReplace(StringReplace($aBase_IPlist[$i][1], $replace2, $s_2), $replace3, $s_3) Next GUISetState(@SW_HIDE, $IPMonkey) GUISetState(@SW_SHOW, $PingGui) ; pass the new list to the pinger Main_GO($aNew_IPlist) GUISetState(@SW_HIDE, $PingGui) GUISetState(@SW_SHOW, $IPMonkey) EndFunc ;==>replace_And_Go Func Main_GO($IPlist) HotKeySet("{esc}", "exitbuttonClick") $StopPing = 0 ; $IPlist = _FileReadToArray_mod(".\IP_List.txt") ; Reads text file for list of IP's ; ; the above command, it loads in the $IPlist array the values contained in the file IP_List.txt ; values in the file should be separated by a semicolon, something like in the following example: ; ; hostname1;192.168.0.1 ; hostname2;192.168.0.5 ; hostnameX;10.59.7.200 ; etc.... ; ; if values in the file are not separated by a semicolon, but another char is used, for example a comma, ; then just pass it as second parameter of the function: $IPlist = _FileReadToArray_mod(".\IP_List.txt", ",") ; _GUICtrlListView_BeginUpdate($listview) _GUICtrlListView_DeleteAllItems($listview) _GUICtrlListView_AddArray($listview, $IPlist) ; fill ListView _GUICtrlListView_EndUpdate($listview) While Not $StopPing ; 1 ; continuously ping addresses of the previously loaded file (IP_List.txt) Sleep(10) ; ; $IPlist is the array loaded with all the IP to be pinged (a 2d array in this case) ; | ; | 1 means the IP are in the second column of the $IPlist array (first colun is nr. 0) ; | | ; | | +--> 0 means return back an array loaded with results from all pinged addresses (responding and not responding) ; | | | if you use 1 then only responding addresses are loaded in the returned array [default] ; | | | if you use 2 then only NOT responding addresses are loaded in the returned array ; | | | In this case we do not need an array to be returned, we only need to perform all pings and pass results ; | | | directly (on the fly) to the "_refresh" callback function that will refresh the listview ; | | | ; | | | 0 means NO lookup name resolution must be performed ; | | | | ; | | | | +--> this is the callback function to be called for each pinged address each time the ping has finished ; | | | | | (see the MultiPing.au3 file for info on all passed params) ; | | | | | 6 parameters are passed to this function, but only 2 are used by the called function in this case: ; | | | | | [4] roundtrip of the responding ping or -1 if IP is down ; | | | | | [5] Index (position) of this IP within the caller's passed array ; | | | | | ; v v v v v _nPing($IPlist, 1, 0, 0, "_refresh") WEnd EndFunc ;==>Main_GO #EndRegion ; Main_GO/Replace_and_GO #Region ; QuickScan/Replace_and_GO2 Func replace_And_Go2($s_2, $s_3) ; Create a new array wit a new list of IP according to passed second and third octet Local $aNew_IPlist = $aBase_IPlist For $i = 0 To UBound($aNew_IPlist) - 1 $aNew_IPlist[$i][1] = StringReplace(StringReplace($aBase_IPlist[$i][1], $replace2, $s_2), $replace3, $s_3) Next GUISetState(@SW_HIDE, $IPMonkey) GUISetState(@SW_SHOW, $PingGui) ; pass the new list to the pinger QuickRun($aNew_IPlist) GUISetState(@SW_HIDE, $PingGui) GUISetState(@SW_SHOW, $IPMonkey) EndFunc ;==>replace_And_Go2 Func QuickRun($IPlist) $userdata1 = GUICtrlRead($data1) $userdata2 = GUICtrlRead($data2) HotKeySet("{esc}", "_button1") Local $Win_X = 1200, $Win_Y = 880 ; dimension of window $PingGui = GUICreate("IP Monkey" & "~~~" & @UserName & "~~~" & "Store" & $userdata1 & $userdata2 & "~~~" & @MON & "." & @MDAY & "." & @YEAR & "~~~" & @HOUR & "." & @MIN, $Win_X, $Win_Y, -1, -1) GUISetOnEvent($GUI_EVENT_CLOSE, "_button1", $PingGui) $listview = GUICtrlCreateListView("", 10, 10, $Win_X - 20, $Win_Y - 40) GUICtrlSetFont(-1, 8) GUICtrlSetStyle($listview, $LVS_ICON) ; + $LVS_NOLABELWRAP) ; Generate colored square images $hImage = _GUIImageList_Create(30, 30) _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0xFFFF00, 30, 30)) ; yellow _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0xFF0000, 30, 30)) ; red _GUIImageList_Add($hImage, _GUICtrlListView_CreateSolidBitMap($listview, 0x00FF00, 30, 30)) ; green _GUICtrlListView_SetImageList($listview, $hImage, 0) $button1 = GUICtrlCreateButton("Exit", 10, $Win_Y - 25, $Win_X - 20, 20) GUICtrlSetTip(-1, "End of program") GUICtrlSetOnEvent(-1, "exitbuttonClick") GUISetState(@SW_SHOW) ;~ $IPlist = _FileReadToArray_mod(".\IP_List.txt") ; Reads text file for list of IP's _GUICtrlListView_BeginUpdate($listview) _GUICtrlListView_AddArray($listview, $IPlist) ; fill ListView _GUICtrlListView_EndUpdate($listview) ;While 1 ; perform Pings and update ListView by the "_refresh" callback function $aFinalResult = _nPing($IPlist, 1, 0, 0, "_refresh") ;~ _ArrayDisplay($aFinalResult) ;DirCheck() EndFunc ;==>QuickRun #EndRegion ; QuickScan/Replace_and_GO2 #Region ; Misc Funcs (network) Func _refresh($Params) ; this receive ping results and displays them in the ListView _GUICtrlListView_SetItemImage($listview, $Params[5], 0) ; set colour to Yellow Sleep(50) ; a little wait If $Params[4] = -1 Then ; Device not responding to ping _GUICtrlListView_SetItemImage($listview, $Params[5], 1) ; set colour to RED _GUICtrlListView_EnsureVisible($listview, $Params[5]) ; Position view to this item Else ; Device responds to ping _GUICtrlListView_SetItemImage($listview, $Params[5], 2) ; set colour to GREEN EndIf EndFunc ;==>_refresh Func _button1() ; Button 1 clicked ;~ $StopPing = 1 Exit EndFunc ;==>_button1 #EndRegion ; Misc Funcs (network) MultiPing.au3 IP_List.txt
-
Whenever we try to access a network share it will prompt for credentials based on the shared folder settings. Like the below prompt Once you save them, they are saved in Windows Credentials of Credentials Manager in Control panel (run --> control keymgr.dll). But not able to found exact file or registry for this setting. So, can anyone suggest how to do this process of adding network credentials using AutoIT.
-
How to enable file sharing for all public,private,work,home networks. I mean programatically using AutoIT.
-
When I run a program in remote vm virtualbix machine windows 7 64 bit with psexec from my current machine. It is working fine in system context. C:\Users\kirud01>"C:\Software\application packaging\PsTools\PsExec.exe" -s -i -d "\\erwin-pc" -c -f "C:\Build\delete.exe" But when I run the same in user context i.e., without -s parameter. The screen is getting freezed in the remote machine. Could you please help me on this. If possible any alternatives for PSEXEC in AutoIT code itself.
- 2 replies
-
- psexec
- remote execution
-
(and 2 more)
Tagged with:
-
Network Interface Info, Statistics, and Traffic (incl. IP, TCP, UDP and ICMP) This is an example of getting and displaying Network Interface Information, Statistics and Traffic. Previously this was just a means to getting Network statistics (specifically IP, TCP, UDP, and ICMP), but now it includes Internet Interface information, as well as Interface-specific statistics. Since this UDF can be used in different ways, let me cover Statistics first: Network Statistics Information Stats example output To retrieve Statistics information, you can call one of the four _Network_xxxxStatistics() functions for IP, TCP, UDP, or ICMP Statistics. These functions accept 1 argument which specifies which protocol to use. Basically, zero is IPv4 and non-zero is IPv6. It defaults to IPv4 if no arguments. Here's the functions: Protocol Statistics Functions: _Network_IPStatistics() -> receives IP statistics _Network_TCPStatistics() -> TCP statistics _Network_UDPStatistics() -> UDP statistics _Network_ICMPStatistics() -> ICMP statistics - To get per-interface statistics requires 2 calls. One call is required to collect information on adapters into an array. Once this information is retrieved, multiple calls to _Network_InterfaceEntryInfo() can be made for each indexed network interface. Note that _Network_IPv4AdaptersInfo() is the only adapter/interface information function which doesn't get index information - so don't use it unless you want further interface information. The main UDF functions to use are: Network Adapter & Interface Functions: _Network_IPv4AdaptersInfo() -> Retrieves information on Physical IPv4 adapters _Network_IPv4AdaptersInfoEx() -> Retrieves much more info on Physical IPv4 adapters _Network_IPv4AddressTable() -> Retrieves information on IPv4 Interfaces _Network_IPAllAddressTable() -> Retrieves information on both IPv4 and IPv6 interfaces Network Statistics for a Given Interface: _Network_InterfaceEntryInfo() -> For a given interface index, retrieves statistics - The simplest way to get overall traffic is to use _Network_IPAllAddressTable() (or _Network_IPv4AddressTable() for IPv4 only) to collect an array of info about interfaces. This needs to be done only once. Then, to collect statistics, for each row in the interface array, call _Network_InterfaceEntryInfo() with $aIPAddressTable[$i][0] to get the statistics for that network interface. IMPORTANT: Note that for all statistics, the data received/sent are represented as 32-bit numbers, and subject to wraparound after 4GBs of data has been transferred. Network Interface Information Regarding Network Interface Information, nearly every function except those ending in xxStatistics(), will return various info regarding the network adapters or interfaces. Currently, IPv4 and IPv6 addresses are retrieved for the interface, as well as for Gateway, DHCP, DNS and WINS servers (there's some XP issues here as to which functions to use - see UDFs). The number of IP addresses (since there can be more than one assigned to each interface) is controlled via a parameter $bGetAllIPs. If this value is non-zero, multiple IP addresses are returned in a string separated by "|" (pipe symbol). Also note that the MAC/Physical Address is returned by most functions as well. These are properly formatted into a hex string in the form "01-23-45-67-89-ab". There is one issue with converting IPv6 addresses - on pre-Vista O/S's (Win XP I'm looking at you) WSAStartup must be called by the code. This is all handled internally, but if you have code that relies on WSAStartup/Cleanup, keep it in mind and let me know if I can better accommodate any potential conflicts. Further notes: - The TCP Statistics gives information about the number of segments sent/received, rather than the # of packets. I'm not totally clear on the association, however here's some links: What's the difference between a TCP segment and a TCP packet? Whats the difference between a Packet, Segment and Frame? - I'm not sure how segments, packets, or datagrams map to # of bytes, or what API functions I might use to figure this out. Any help there would be appreciated. Alternatives: While I have opened access to a lot of detailed network and performance information, there are alternatives - check out Netstat (-e for performance stats) or my >Performance Counters UDF's, which has a lot of varied stats (one example of these: >Network Usage). Following is the example, included in the ZIP file. Note there's a cr@pload of info dumped to the console, so you'll probably want to redirect output or copy-and-paste from the output console: ; ======================================================================================================== ; <NetworkStatsExample.au3> ; ; Example of reading and displaying Network Interface Information and Statistics ; (using <NetworkStatistics.au3> UDF) ; Statistics information, including IP, TCP*, UDP, and ICMP and internet interface traffic, ; are displayed in a 'Splash' window - with both IPv4 and IPv6 data separated ; ; Author: Ascend4nt ; ======================================================================================================== #include "_NetworkStatistics.au3" ; -------------------- HOTKEY FUNCTION & VARIABLE -------------------- Global $bHotKeyPressed = False Func _EscPressed() $bHotKeyPressed=True EndFunc ; -------------------- MAIN PROGRAM CODE -------------------- HotKeySet("{Esc}", "_EscPressed") Local $hSplash, $sSplashText ; Network Stats Local $aUDPStats, $aTCPStats, $aIPStats, $aICMPStats Local $aUDPv6Stats, $aTCPv6Stats, $aIPv6Stats, $aICMPv6Stats Local $aIPv4Adapters, $nAdapters Local $aIPv4AddrTable, $aIPAllAddrTable, $nInterfaces, $aNIEntryInfo Local $sSeparator = "-----------------------------------------" ; IP Stats: IPv4 and IPv6 For $i = 0 To 1 $aIPStats = _Network_IPStatistics($i) If @error Then ConsoleWrite("_Network_IPStatistics("&$i&") error: "&@error&", @extended="&@extended&@CRLF) ContinueLoop EndIf If $i Then ConsoleWrite("IP [IPv6] Stats:") Else ConsoleWrite("IP [IPv4] Stats:") EndIf ConsoleWrite( _ " [0] = IP Forwarding Status: [1 = Enabled, 2 = Disabled] : " & $aIPStats[0] & _ ", [1] = Default initial time-to-live (TTL) for datagrams : " & $aIPStats[1] & @CRLF & _ ", [2] = # Received Datagrams : " & $aIPStats[2] & _ ", [3] = # Received Datagrams w/Header errors : " & $aIPStats[3] & _ ", [4] = # Received Datagrams w/Address errors : " & $aIPStats[4] & @CRLF & _ ", [5] = # Forwarded Datagrams : " & $aIPStats[5] & _ ", [6] = # Received Datagrams w/Unknown Protocol : " & $aIPStats[6] & _ ", [7] = # Received Datagrams Discarded : " & $aIPStats[7] & @CRLF & _ ", [8] = # Received Datagrams Delivered : " & $aIPStats[8] & _ ", [9] = # Requested Outgoing Datagrams : " & $aIPStats[9] & _ ", [10] = # Outgoing Datagrams Discarded : " & $aIPStats[10] & @CRLF & _ ", [11] = # Transmitted Datagrams Discarded : " & $aIPStats[11] & _ ", [12] = # Datagrams w/o Routes that were Discarded : " & $aIPStats[12] & _ ", [13] = TimeOut for Reassembling Incoming Fragmented Datagrams : " & $aIPStats[13] & @CRLF & _ ", [14] = # Datagrams Requiring Reassembly : " & $aIPStats[14] & _ ", [15] = # Datagrams Successfully Reassembled : " & $aIPStats[15] & _ ", [16] = # Datagrams that Failed to be Reassembled : " & $aIPStats[16] & @CRLF & _ ", [17] = # Datagrams that were Fragmented Successfully : " & $aIPStats[17] & _ ", [18] = # Datagrams not Fragmented, and Discarded : " & $aIPStats[18] & _ ", [19] = # Fragments created (for Datagrams) : " & $aIPStats[19] & @CRLF & _ ", [20] = # of Interfaces : " & $aIPStats[20] & _ ", [21] = # of IP addresses associated with PC : " & $aIPStats[21] & _ ", [22] = # of Routes in the Routing table : " & $aIPStats[22] & _ @CRLF) ConsoleWrite($sSeparator & @CRLF) Next ; TCP Stats: IPv4 and IPv6 For $i = 0 To 1 $aTCPStats = _Network_TCPStatistics($i) If @error Then ConsoleWrite("_Network_TCPStatistics("&$i&") error: "&@error&", @extended="&@extended&@CRLF) ContinueLoop EndIf If $i Then ConsoleWrite("TCP [IPv6] Stats:") Else ConsoleWrite("TCP [IPv4] Stats:") EndIf ConsoleWrite( _ "[0] Rto Algorithm = " & $aTCPStats[0] & _ ",[1] Rto Min = " & $aTCPStats[1] & _ ",[2] Rto Max = " & $aTCPStats[2] & _ ",[3] #Max Connections = " & $aTCPStats[3] & _ ",[4] #Active Opens = " & $aTCPStats[4] & _ ",[5] #Passive Opens = " & $aTCPStats[5] & @CRLF & _ " [6] #Failed Connection Attempts = " & $aTCPStats[6] & _ ",[7] #Established Connections that were Reset = " & $aTCPStats[7] & _ ",[8] #Established Connections [current] = " & $aTCPStats[8] & @CRLF & _ " [9] #Recvd Segments = " & $aTCPStats[9] & _ ",[10] #Sent Segments = " & $aTCPStats[10] & _ ",[11] #Retransmitted Segments = " & $aTCPStats[11] & @CRLF & _ " [12] #Receive Errors = " & $aTCPStats[12] & _ ",[13] #Sent Segments with Reset Flag = " & $aTCPStats[13] & _ ",[14] #Connections = " & $aTCPStats[14] & _ @CRLF) ConsoleWrite($sSeparator & @CRLF) Next ; UDP Stats: IPv4 and IPv6 For $i = 0 To 1 $aUDPStats = _Network_UDPStatistics($i) If @error Then ConsoleWrite("_Network_UDPStatistics("&$i&") error: "&@error&", @extended="&@extended&@CRLF) ContinueLoop EndIf If $i Then ConsoleWrite("UDP [IPv6] Stats:") Else ConsoleWrite("UDP [IPv4] Stats:") EndIf ConsoleWrite( _ " [0] #Recvd Datagrams = " & $aUDPStats[0] & _ ",[1] #Discarded Datagrams [invalid port] = " & $aUDPStats[1] & _ ",[2] #Erroneous Datagrams = " & $aUDPStats[2] & @CRLF & _ " [3] #Sent Datagrams = " & $aUDPStats[3] & _ ",[4] #UDP Listener Entries = " & $aUDPStats[4] & _ @CRLF) ConsoleWrite($sSeparator & @CRLF) Next ; ICMP Stats: IPv4 and IPv6 For $i = 0 To 1 $aICMPStats = _Network_ICMPStatistics($i) If @error Then ConsoleWrite("_Network_ICMPStatistics("&$i&") error: "&@error&", @extended="&@extended&@CRLF) ContinueLoop EndIf ConsoleWrite("ICMP [IPv"&4+($i*2)&"] Stats:" & _ " [0] = # Incoming ICMP Messages : " & $aICMPStats[0] & _ ", [1] = # Incoming ICMP Errors : " & $aICMPStats[1] & _ ", [2] = # Outgoing ICMP Messages : " & $aICMPStats[2] & _ ", [3] = # Outgoing ICMP Errors : " & $aICMPStats[3] & _ @CRLF) ConsoleWrite($sSeparator & @CRLF) Next ; IPv4 Adapters Info (very basic info) _Network_IPv4AdaptersInfo() ConsoleWrite($sSeparator & @CRLF) ; IPv4 Adapters Info (comprehensive info) $aIPv4Adapters = _Network_IPv4AdaptersInfoEx() $nAdapters = @extended ConsoleWrite("# of Adapters: "&$nAdapters&@CRLF) For $i = 0 To $nAdapters - 1 ConsoleWrite("Adapter #"&$i+1&":" & _ " [0] Index #"& $aIPv4Adapters[$i][0] & _ ", [1] Type = " & $aIPv4Adapters[$i][1] & _ ", [2] DHCP Enabled Flag = " & $aIPv4Adapters[$i][2] & _ ", [3] WINS Enabled Flag = " & $aIPv4Adapters[$i][3] & _ ", [4] Physical [MAC] Address: " & $aIPv4Adapters[$i][4] & _ ", [5] (0) = " & $aIPv4Adapters[$i][5] & @CRLF & _ ", [6] Description: "& $aIPv4Adapters[$i][6] & _ ", [7] [Empty '']: " & $aIPv4Adapters[$i][7] & _ ", [8] Adapter/Service Name [GUID] = " & $aIPv4Adapters[$i][8] & _ ", [9] [Empty] = " & $aIPv4Adapters[$i][9] & _ ", [10] [Empty] = " & $aIPv4Adapters[$i][10] & @CRLF & _ ", [11] IPv4 Address(es): "& $aIPv4Adapters[$i][11] & _ ", [12] IP Address Mask(s): "& $aIPv4Adapters[$i][12] & @CRLF & _ ", [13] Gateway IPv4 Address(es): "& $aIPv4Adapters[$i][13] & _ ", [14] Gateway Address Mask(s) : "& $aIPv4Adapters[$i][14] & @CRLF & _ ", [15] DHCP IPv4 Address(es) = " & $aIPv4Adapters[$i][15] & _ ", [16] DHCP Address Mask(s) = " & $aIPv4Adapters[$i][16] & _ ", [17] DHCP LeaseObtained Time = " & $aIPv4Adapters[$i][17] & _ ", [18] DHCP LeaseExpires Time = " & $aIPv4Adapters[$i][18] & @CRLF & _ ", [19] Primary WINS Server IP = " & $aIPv4Adapters[$i][19] & _ ", [20] Primary WINS Server Address Mask = " & $aIPv4Adapters[$i][20] & _ ", [21] Secondary WINS Server IP(s) = " & $aIPv4Adapters[$i][21] & _ ", [22] Secondary WINS Server Address Mask(s) = " & $aIPv4Adapters[$i][22] & @CRLF) ConsoleWrite($sSeparator & @CRLF) Next ; IPv4 Interface Info alt #2 $aIPv4AddrTable = _Network_IPv4AddressTable() $nInterfaces = @extended ConsoleWrite(@CRLF) For $i = 0 To $nInterfaces - 1 ConsoleWrite("Adapter #"&$i+1&": [0] Interface Index # = " & $aIPv4AddrTable[$i][0] & _ ", [1] IPv4 Address = " & $aIPv4AddrTable[$i][1] & _ ", [2] Subnet Mask = " & $aIPv4AddrTable[$i][2] & _ ", [3] Broadcast Address = " & $aIPv4AddrTable[$i][3] & @CRLF & _ " [4] Max Reassembly Size = " & $aIPv4AddrTable[$i][4] & _ ", [5] Address Type/State = " & $aIPv4AddrTable[$i][5] & @CRLF) Next ConsoleWrite($sSeparator & @CRLF) ; IPv4 and IPv6 Interface Info (includes everything except Address Masks) ; params: 0 (IPv4 AND IPv6), 0 (don't get all IP's), 0 (don't include down-status interfaces) $aIPAllAddrTable = _Network_IPAllAddressTable(0, 0, 0) $nInterfaces = @extended ConsoleWrite($sSeparator & @CRLF) For $i = 0 To $nInterfaces - 1 ConsoleWrite("Interface #"&$i+1&": [0] Index #"& $aIPAllAddrTable[$i][0] & _ ", [1] Type = " & $aIPAllAddrTable[$i][1] & _ ", [2] Operational Status = " & $aIPAllAddrTable[$i][2] & _ ", [3] Flags = 0x" & Hex($aIPAllAddrTable[$i][3], 8) & _ ", [4] Physical [MAC] Address: " & $aIPAllAddrTable[$i][4] & _ ", [5] MTU = " & $aIPAllAddrTable[$i][5] & @CRLF & _ ", [6] Description: "& $aIPAllAddrTable[$i][6] & _ ", [7] Friendly Name: " & $aIPAllAddrTable[$i][7] & _ ", [8] Adapter/Service Name [GUID] = " & $aIPAllAddrTable[$i][8] & @CRLF & _ ", [9] Max Receive Speed [Vista+] = " & $aIPAllAddrTable[$i][9] & _ ", [10] Max Transmit Speed [Vista+] = " & $aIPAllAddrTable[$i][10] & @CRLF & _ ", [11] IPv4 Address(es): "& $aIPAllAddrTable[$i][11] & _ ", [12] IPv6 Address(es): "& $aIPAllAddrTable[$i][12] & @CRLF & _ ", [13] DNS IPv4 Address(es): "& $aIPAllAddrTable[$i][13] & _ ", [14] DNS IPv6 Address(es): "& $aIPAllAddrTable[$i][14] & @CRLF & _ ", [15] Gateway IPv4 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][15] & _ ", [16] Gateway IPv6 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][16] & @CRLF & _ ", [17] DHCP IPv4 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][17] & _ ", [18] DHCP IPv6 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][18] & @CRLF & _ ", [19] WINS IPv4 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][19] & _ ", [20] WINS IPv6 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][20] & @CRLF & _ ", [21] Connection Type [Vista+] = " & $aIPAllAddrTable[$i][21] & _ ", [22] Tunnel Type [Vista+] = " & $aIPAllAddrTable[$i][22] & @CRLF) ; Interface Statistics & Info for Given index $aNIEntryInfo = _Network_InterfaceEntryInfo($aIPAllAddrTable[$i][0]) ;~ ConsoleWrite("_Network_InterfaceEntryInfo return, @error = " & @error & ", @extended = " & @extended & @CRLF) ConsoleWrite("Interface #"&$i+1&" Entry Info: [0] Interface Index = " & $aNIEntryInfo[0] & _ ", [1] Interface Type = " & $aNIEntryInfo[1] & _ ", [2] Operational Status = " & $aNIEntryInfo[2] & _ ", [3] Admin Status = " & $aNIEntryInfo[3] & _ ", [4] Physical Address = " & $aNIEntryInfo[4] & _ ", [5] MTU [Max Trans. Unit] in bytes = " & $aNIEntryInfo[5] & @CRLF & _ ", [6] Description = " & $aNIEntryInfo[6] & _ ", [7] Interface Name = " & $aNIEntryInfo[7] & @CRLF & _ ", [8] Last change [1/100th second] = " & $aNIEntryInfo[8] & _ ", [9] Interface Speed [bps] = " & $aNIEntryInfo[9] & @CRLF & _ ", [10] # Recvd Data [in Octets] = " & $aNIEntryInfo[10] & _ ", [11] # Recvd Unicast Packets = " & $aNIEntryInfo[11] & _ ", [12] # Recvd Non-Unicast Packets = " & $aNIEntryInfo[12] & _ ", [13] # Recvd Packets Discarded [no error] = " & $aNIEntryInfo[13] & _ ", [14] # Recvd Packets Discarded [error] = " & $aNIEntryInfo[14] & _ ", [15] # Recvd Packets Discarded [unk. protocol] = " & $aNIEntryInfo[15] & @CRLF & _ ", [16] # Sent Data [in Octets] = " & $aNIEntryInfo[16] & _ ", [17] # Sent Unicast Packets = " & $aNIEntryInfo[17] & _ ", [18] # Sent Non-Unicast Packets = " & $aNIEntryInfo[18] & _ ", [19] # Sent Packets Discarded [no error] = " & $aNIEntryInfo[19] & _ ", [20] # Sent Packets Discarded [error] = " & $aNIEntryInfo[20] & @CRLF & _ ", [21] Transmit Queue Length [n/a] = " & $aNIEntryInfo[21] & @CRLF) ConsoleWrite($sSeparator & @CRLF) Next $hSplash=SplashTextOn("Network Usage Information", "", 520, 24 + (19 * 15) + ($nInterfaces * (5.5 * 15)), Default, Default, 16+4, "Lucida Console", 11) ; Start loop Do $aIPStats = _Network_IPStatistics() $aTCPStats = _Network_TCPStatistics() $aUDPStats = _Network_UDPStatistics() $aICMPStats = _Network_ICMPStatistics() $aIPv6Stats = _Network_IPStatistics(1) $aTCPv6Stats = _Network_TCPStatistics(1) $aUDPv6Stats = _Network_UDPStatistics(1) $aICMPv6Stats = _Network_ICMPStatistics(1) $sSplashText = StringFormat("%35s", "== TCP Stats ==") & @CRLF $sSplashText &= StringFormat("IPv4: [Segments] Recvd = %10u | Sent = %10u", $aTCPStats[9], $aTCPStats[10]) & @CRLF $sSplashText &= StringFormat("IPv6: [Segments] Recvd = %10u | Sent = %10u", $aTCPv6Stats[9], $aTCPv6Stats[10]) & @CRLF $sSplashText &= StringFormat("<Total Connections> IPv4: %10u | IPv6: %10u", $aTCPStats[14], $aTCPv6Stats[14]) & @CRLF $sSplashText &= @CRLF & StringFormat("%35s", "== UDP Stats ==") & @CRLF $sSplashText &= StringFormat("IPv4: [Datagrams] Recvd = %10u | Sent = %10u", $aUDPStats[0], $aUDPStats[3]) & @CRLF $sSplashText &= StringFormat("IPv6: [Datagrams] Recvd = %10u | Sent = %10u", $aUDPv6Stats[0], $aUDPv6Stats[3]) & @CRLF $sSplashText &= StringFormat("<Total Listeners> IPv4: %10u | IPv6: %10u", $aUDPStats[4], $aUDPv6Stats[4]) & @CRLF $sSplashText &= @CRLF & StringFormat("%35s", "== IP Stats ==") & @CRLF $sSplashText &= StringFormat("IPv4: [Datagrams] Recvd = %10u | Sent = %10u", $aIPStats[2], $aIPStats[9]) & @CRLF $sSplashText &= StringFormat("IPv6: [Datagrams] Recvd = %10u | Sent = %10u", $aIPv6Stats[2], $aIPv6Stats[9]) & @CRLF $sSplashText &= @CRLF & StringFormat("%35s", "== ICMP Stats ==") & @CRLF $sSplashText &= StringFormat("IPv4: [Messages] Recvd = %10u | Sent = %10u", $aICMPStats[0], $aICMPStats[2]) & @CRLF $sSplashText &= StringFormat("IPv6: [Messages] Recvd = %10u | Sent = %10u", $aICMPv6Stats[0], $aICMPv6Stats[2]) & @CRLF For $i = 0 To $nInterfaces - 1 ;~ $aNIEntryInfo = _Network_InterfaceEntryInfo($aIPv4AddrTable[$i][0]) ;~ $sSplashText &= @CRLF & StringFormat("%35s", "== IP " & $aIPv4AddrTable[$i][1] & " ==" ) & @CRLF $aNIEntryInfo = _Network_InterfaceEntryInfo($aIPAllAddrTable[$i][0]) If @error Then ConsoleWrite("_Network_InterfaceEntryInfo return, @error = " & @error & ", @extended = " & @extended & @CRLF) ExitLoop EndIf If $aIPAllAddrTable[$i][11] <> "" Then $sSplashText &= @CRLF & StringFormat("%40s", "== IPv4 " & $aIPAllAddrTable[$i][11] & " ==" ) & @CRLF Else $sSplashText &= @CRLF & StringFormat("%52s", "== IPv6 " & $aIPAllAddrTable[$i][12] & " ==" ) & @CRLF EndIf $sSplashText &= StringFormat("%45.56s", $aNIEntryInfo[6]) & @CRLF ; Octet *should* be the same as Bytes.. $sSplashText &= StringFormat("Data (Octets/Bytes): Recvd = %10u | Sent = %10u", $aNIEntryInfo[10], $aNIEntryInfo[16]) & @CRLF $sSplashText &= StringFormat("Unicast Packets: Recvd = %10u | Sent = %10u", $aNIEntryInfo[11], $aNIEntryInfo[17]) & @CRLF $sSplashText &= StringFormat("Non-Unicast Packets: Recvd = %10u | Sent = %10u", $aNIEntryInfo[12], $aNIEntryInfo[18]) & @CRLF Next $sSplashText &= @CRLF & StringFormat("%35s", "[ESC] Exits") & @CRLF ControlSetText($hSplash, "", "[CLASS:Static; INSTANCE:1]", $sSplashText) Sleep(500) Until $bHotKeyPressed NetworkStatistics.zip ~prev version. downloads: >100 Updates: 2013-07-11: Changed: _Network_IPv4AdaptersInfoEx() now returns all IP's (if requested) and Address Masks Fixed: WSALastError call possible crash with non-array variable Changed: _Network_IPAllAddressTable() now allows 'down' status interfaces to be returned Added: Some comments on development, info on getting additional stats in the UDF 2013-07-06: Added: Much more Adapter Information Changed: Example is now separate from the UDF Fixed some minor issues here and there Changed: Global Handle to IPHLPAPI.DLL is now contained in the UDF and used to speed up function calls Misc. Other fixes I didn't keep track of! 2013-07-02: Hotfix: Ipv6 indexing error Fixed: indexing, updated and enhanced output Changed: Various functions return arrays even if failure - this is to make XP pre-SP1 and also collection of IPv6 less troublesome. @error should still be checked on return though! Added: Adapter and Interface information and statistics collection 2013-06-20: Now covers all the 'p's - IP and ICMP now added
-
Network Adapter Info use WMI (Windows Management Instrumentation) Features: Show information network card. Easily copy information, for copy just click on the line want to copy. Notifications connection, connection loss. Supports exporting information to file (CSV/INI format). Run: Export to file INI format: NetStatus.exe "PathFile.INI" Export to file CSV format: NetStatus.exe "PathFile.CSV" CSV Export to file CSV format: NetStatus.exe "PathFile.CSV" /CSV Export to file CSV format: NetStatus.exe "PathFile.CSV" --CSV UDF: Opt("MustDeclareVars", 1) ;0=no, 1=require pre-declaration Global $oErrorHandler = ObjEvent("AutoIt.Error", "_SkipObjectError") Func _SkipObjectError() ; Do nothing special, just check @error after suspect functions. EndFunc ;==>_SkipObjectError Global $sAdapterInfo Global Const $sNotAvailable = "N/A", $sBlankIP = "0.0.0.0", $sBlankMAC = "00:00:00:00:00:00" ConsoleWrite(_PrintAdaptersInfo() & @CRLF) ;==>_GetDataSetVar Func _PrintAdaptersInfo() If Not IsArray($sAdapterInfo) Then $sAdapterInfo = _GetListAdaptersInfo(".") Local $sIndex, $sAdapter, $sAdapterName, $sAdapterStatus, $sGetIPType, $sIP, $sSubNetIP, $sMAC, $sGetwayIP, $sGetwayMAC, $sSpeed, $sDNS1, $sDNS2, $sDNS3, $sDNS4, $sDNS5, $sDNS6, $sDNS7, $sDNS8, $sReturn If IsArray($sAdapterInfo) And $sAdapterInfo[0][0] > 0 Then For $x = 1 To $sAdapterInfo[0][0] $sIndex = $sAdapterInfo[$x][0] If ((_StringStripWSCR($sIndex) <> '') And ($sIndex <> $sNotAvailable)) Then $sReturn &= '+ Index: ' & $sIndex & @CRLF & '' $sAdapter = $sAdapterInfo[$x][1] If ((_StringStripWSCR($sAdapter) <> '') And ($sAdapter <> $sNotAvailable)) Then $sReturn &= '- Adapter: ' & $sAdapter & @CRLF & '' $sAdapterName = $sAdapterInfo[$x][2] If ((_StringStripWSCR($sAdapterName) <> '') And ($sAdapterName <> $sNotAvailable)) Then $sReturn &= '- Adapter Name: ' & $sAdapterName & @CRLF & '' $sAdapterStatus = $sAdapterInfo[$x][3] If ((_StringStripWSCR($sAdapterStatus) <> '') And ($sAdapterStatus <> $sNotAvailable)) Then $sReturn &= '- Adapter Status: ' & $sAdapterStatus & @CRLF & '' $sGetIPType = $sAdapterInfo[$x][4] If ((_StringStripWSCR($sGetIPType) <> '') And ($sGetIPType <> $sNotAvailable)) Then $sReturn &= '- IP Type: ' & $sGetIPType & @CRLF & '' $sIP = $sAdapterInfo[$x][5] If ((_StringStripWSCR($sIP) <> '') And ($sIP <> $sNotAvailable) And ($sIP <> $sBlankIP)) Then $sReturn &= '- IP: ' & $sIP & @CRLF & '' $sSubNetIP = $sAdapterInfo[$x][6] If ((_StringStripWSCR($sSubNetIP) <> '') And ($sSubNetIP <> $sNotAvailable) And ($sSubNetIP <> $sBlankIP)) Then $sReturn &= '- SubNet IP: ' & $sSubNetIP & @CRLF & '' $sMAC = $sAdapterInfo[$x][7] If ((_StringStripWSCR($sMAC) <> '') And ($sMAC <> $sNotAvailable) And ($sMAC <> $sBlankMAC)) Then $sReturn &= '- MAC: ' & $sMAC & @CRLF & '' $sGetwayIP = $sAdapterInfo[$x][8] If ((_StringStripWSCR($sGetwayIP) <> '') And ($sGetwayIP <> $sNotAvailable) And ($sGetwayIP <> $sBlankIP)) Then $sReturn &= '- Getway IP: ' & $sGetwayIP & @CRLF & '' $sGetwayMAC = $sAdapterInfo[$x][9] If ((_StringStripWSCR($sGetwayMAC) <> '') And ($sGetwayMAC <> $sNotAvailable) And ($sGetwayMAC <> $sBlankMAC)) Then $sReturn &= '- Getway MAC: ' & $sGetwayMAC & @CRLF & '' $sSpeed = $sAdapterInfo[$x][10] If ((_StringStripWSCR($sSpeed) <> '') And ($sSpeed <> $sNotAvailable)) Then $sReturn &= '- Speed: ' & $sSpeed & @CRLF & '' $sDNS1 = $sAdapterInfo[$x][11] If ((_StringStripWSCR($sDNS1) <> '') And ($sDNS1 <> $sNotAvailable) And ($sDNS1 <> $sBlankIP)) Then $sReturn &= '- DNS 1: ' & $sDNS1 & @CRLF & '' $sDNS2 = $sAdapterInfo[$x][12] If ((_StringStripWSCR($sDNS2) <> '') And ($sDNS2 <> $sNotAvailable) And ($sDNS2 <> $sBlankIP)) Then $sReturn &= '- DNS 2: ' & $sDNS2 & @CRLF & '' $sDNS3 = $sAdapterInfo[$x][13] If ((_StringStripWSCR($sDNS3) <> '') And ($sDNS3 <> $sNotAvailable) And ($sDNS3 <> $sBlankIP)) Then $sReturn &= '- DNS 3: ' & $sDNS3 & @CRLF & '' $sDNS4 = $sAdapterInfo[$x][14] If ((_StringStripWSCR($sDNS4) <> '') And ($sDNS4 <> $sNotAvailable) And ($sDNS4 <> $sBlankIP)) Then $sReturn &= '- DNS 4: ' & $sDNS4 & @CRLF & '' $sDNS5 = $sAdapterInfo[$x][15] If ((_StringStripWSCR($sDNS5) <> '') And ($sDNS5 <> $sNotAvailable) And ($sDNS5 <> $sBlankIP)) Then $sReturn &= '- DNS 5: ' & $sDNS5 & @CRLF & '' $sDNS6 = $sAdapterInfo[$x][16] If ((_StringStripWSCR($sDNS6) <> '') And ($sDNS6 <> $sNotAvailable) And ($sDNS6 <> $sBlankIP)) Then $sReturn &= '- DNS 6: ' & $sDNS6 & @CRLF & '' $sDNS7 = $sAdapterInfo[$x][17] If ((_StringStripWSCR($sDNS7) <> '') And ($sDNS7 <> $sNotAvailable) And ($sDNS7 <> $sBlankIP)) Then $sReturn &= '- DNS 7: ' & $sDNS7 & @CRLF & '' $sDNS8 = $sAdapterInfo[$x][18] If ((_StringStripWSCR($sDNS8) <> '') And ($sDNS8 <> $sNotAvailable) And ($sDNS8 <> $sBlankIP)) Then $sReturn &= '- DNS 8: ' & $sDNS8 & @CRLF & '' $sReturn &= @CRLF & '' Next Return $sReturn Else Return SetError(1, 0, '') EndIf EndFunc ;==>_PrintAdaptersInfo Func _StringStripWSCR($iString = '') $iString = StringStripCR($iString) $iString = StringStripWS($iString, 8) Return $iString EndFunc ;==>_StringStripWSCR ;==>_GetListAdaptersInfo Func _GetListAdaptersInfo($sComputer = ".") Local $Cols = 20, $strIndex, $objVAR, $objVARx, $zAdapter, $zAdapterName, $zSpeed, $zIndex, $zInterfaceIndex, $zGetIPType, $zAdapterStatus, $zIP, $zMAC, $zSubNetIP, $zGetwayIP, $zGetwayMAC Local $aReturn[1][$Cols] = [[0, $Cols]] If $sComputer = Default Then $sComputer = @ComputerName Local $sListIndexInterfaceName = _ListIndexInterfaceName() Local $objWMI = ObjGet("winmgmts:\\" & $sComputer & "\root\cimv2") Local $objWQLx = $objWMI.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID != NULL", "WQL", 0x30) ;~ Local $objWQLx = $objWMI.ExecQuery('Select * From Win32_NetworkAdapter', "WQL", 0x30) If Not @error And IsObj($objWQLx) Then For $objVARx In $objWQLx $zAdapterName = $objVARx.NetConnectionID If (_StringStripWSCR($zAdapterName) = "") Then ContinueLoop $zSpeed = _ByteSuffixRound($objVARx.Speed) ; Vista+ If Int($zSpeed) <= 0 Then For $z = 0 To UBound($sListIndexInterfaceName) - 1 If $sListIndexInterfaceName[$z][1] = $zAdapterName Then $zSpeed = _ByteSuffixRound(InterfaceIndexSpeed($sListIndexInterfaceName[$z][0])) Next EndIf $zAdapterStatus = $objVARx.NetConnectionStatus Switch $zAdapterStatus Case 0, 3 $zAdapterStatus = "Disable" Case 1, 2 $zAdapterStatus = "Connected" Case $zAdapterStatus = 7 $zAdapterStatus = "unPlugged" Case Else $zAdapterStatus = $sNotAvailable EndSwitch $strIndex = $objVARx.Index Local $objWQL = $objWMI.ExecQuery('SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index=' & $strIndex, "WQL", 0x30) If Not @error And IsObj($objWQL) Then For $objVAR In $objWQL $zAdapter = $objVAR.Description $aReturn[0][0] += 1 $zIndex = $aReturn[0][0] ReDim $aReturn[$zIndex * 2][$aReturn[0][1]] $zInterfaceIndex = $objVAR.InterfaceIndex If Int($zInterfaceIndex) <= 0 Then For $z = 0 To UBound($sListIndexInterfaceName) - 1 If $sListIndexInterfaceName[$z][1] = $zAdapterName Then $zInterfaceIndex = $sListIndexInterfaceName[$z][0] Next EndIf $aReturn[$zIndex][0] = $zInterfaceIndex $aReturn[$zIndex][1] = $zAdapter $aReturn[$zIndex][2] = $zAdapterName $aReturn[$zIndex][3] = $zAdapterStatus $zGetIPType = $objVAR.DHCPEnabled If $zGetIPType Then $zGetIPType = "DHCP" Else $zGetIPType = "StaticIP" EndIf $aReturn[$zIndex][4] = $zGetIPType $zIP = $objVAR.IPAddress(0) If _StringStripWSCR($zIP) = "" Then $zIP = $sNotAvailable $aReturn[$zIndex][5] = $zIP $zSubNetIP = $objVAR.IPSubnet(0) If _StringStripWSCR($zSubNetIP) = "" Then $zSubNetIP = $sNotAvailable $aReturn[$zIndex][6] = $zSubNetIP $zMAC = $objVAR.MACAddress If _StringStripWSCR($zMAC) = "" Then $zMAC = $sNotAvailable $aReturn[$zIndex][7] = $zMAC $zGetwayIP = $objVAR.DefaultIPGateway(0) If _StringStripWSCR($zGetwayIP) = "" Then $zGetwayIP = $sNotAvailable $aReturn[$zIndex][8] = $zGetwayIP $zGetwayMAC = $sNotAvailable If _StringStripWSCR($zGetwayIP) <> $sNotAvailable Then $zGetwayMAC = _GetMACFromIP($zGetwayIP) $aReturn[$zIndex][9] = $zGetwayMAC If Number($zSpeed) = 0 Then $zSpeed = $sNotAvailable $aReturn[$zIndex][10] = $zSpeed $aReturn[$zIndex][11] = $sNotAvailable $aReturn[$zIndex][12] = $sNotAvailable $aReturn[$zIndex][13] = $sNotAvailable $aReturn[$zIndex][14] = $sNotAvailable $aReturn[$zIndex][15] = $sNotAvailable $aReturn[$zIndex][16] = $sNotAvailable $aReturn[$zIndex][17] = $sNotAvailable $aReturn[$zIndex][18] = $sNotAvailable Local $zDNS = $objVAR.DNSServerSearchOrder() Local $dnsCount = UBound($zDNS) - 1 $aReturn[$zIndex][19] = $dnsCount If IsArray($zDNS) Then Switch $dnsCount Case 1 $aReturn[$zIndex][11] = $zDNS[0] Case 2 $aReturn[$zIndex][11] = $zDNS[0] $aReturn[$zIndex][12] = $zDNS[1] Case 3 $aReturn[$zIndex][11] = $zDNS[0] $aReturn[$zIndex][12] = $zDNS[1] $aReturn[$zIndex][13] = $zDNS[2] Case 4 $aReturn[$zIndex][11] = $zDNS[0] $aReturn[$zIndex][12] = $zDNS[1] $aReturn[$zIndex][13] = $zDNS[2] $aReturn[$zIndex][14] = $zDNS[3] Case 5 $aReturn[$zIndex][11] = $zDNS[0] $aReturn[$zIndex][12] = $zDNS[1] $aReturn[$zIndex][13] = $zDNS[2] $aReturn[$zIndex][14] = $zDNS[3] $aReturn[$zIndex][15] = $zDNS[4] Case 6 $aReturn[$zIndex][11] = $zDNS[0] $aReturn[$zIndex][12] = $zDNS[1] $aReturn[$zIndex][13] = $zDNS[2] $aReturn[$zIndex][14] = $zDNS[3] $aReturn[$zIndex][15] = $zDNS[4] $aReturn[$zIndex][16] = $zDNS[5] Case 7 $aReturn[$zIndex][11] = $zDNS[0] $aReturn[$zIndex][12] = $zDNS[1] $aReturn[$zIndex][13] = $zDNS[2] $aReturn[$zIndex][14] = $zDNS[3] $aReturn[$zIndex][15] = $zDNS[4] $aReturn[$zIndex][16] = $zDNS[5] $aReturn[$zIndex][17] = $zDNS[6] Case 8 $aReturn[$zIndex][11] = $zDNS[0] $aReturn[$zIndex][12] = $zDNS[1] $aReturn[$zIndex][13] = $zDNS[2] $aReturn[$zIndex][14] = $zDNS[3] $aReturn[$zIndex][15] = $zDNS[4] $aReturn[$zIndex][16] = $zDNS[5] $aReturn[$zIndex][17] = $zDNS[6] $aReturn[$zIndex][18] = $zDNS[7] Case Else $aReturn[$zIndex][11] = $zDNS[0] EndSwitch EndIf Next EndIf Next Return $aReturn EndIf Return SetError(1, 0, "") EndFunc ;==>_GetListAdaptersInfo Func _ListIndexInterfaceName() Local Const $tagIP_ADAPTER_ADDRESSES = "ulong Length;dword IfIndex;ptr Next;ptr AdapterName;ptr FirstUnicastAddress;" & "ptr FirstAnycastAddress;ptr FirstMulticastAddress;ptr FirstDnsServerAddress;ptr DnsSuffix;ptr Description;" & "ptr FriendlyName;byte PhysicalAddress[8];dword PhysicalAddressLength;dword Flags;dword Mtu;dword IfType;int OperStatus;" & "dword Ipv6IfIndex;dword ZoneIndices[16];ptr FirstPrefix;" & "uint64 TransmitLinkSpeed;uint64 ReceiveLinkSpeed;ptr FirstWinsServerAddress;ptr FirstGatewayAddress;" & "ulong Ipv4Metric;ulong Ipv6Metric;uint64 Luid;STRUCT;ptr Dhcpv4ServerSockAddr;int Dhcpv4ServerSockAddrLen;ENDSTRUCT;" & "ulong CompartmentId;STRUCT;ulong NetworkGuidData1;word NetworkGuidData2;word NetworkGuidData3;byte NetworkGuidData4[8];ENDSTRUCT;" & "int ConnectionType;int TunnelType;STRUCT;ptr Dhcpv6ServerSockAddr;int Dhcpv6ServerSockAddrLen;ENDSTRUCT;byte Dhcpv6ClientDuid[130];" & "ulong Dhcpv6ClientDuidLength;ulong Dhcpv6Iaid;ptr FirstDnsSuffix;" Local $aRet, $nBufSize, $stBuffer, $stIP_ADAPTER_ADDRESSES, $pIPAAStruct, $nIPAAStSize Local $pTemp, $nTemp, $nEntries, $aIndexEntries $aRet = DllCall("iphlpapi.dll", "ulong", "GetAdaptersAddresses", "ulong", 0, "ulong", 0x86, "ptr", 0, "ptr", 0, "ulong*", 0) If @error Then Return SetError(1, @error, "") If $aRet[0] Then If $aRet[0] <> 111 Or Not $aRet[5] Then Return SetError(2, $aRet[0], "") EndIf $nBufSize = $aRet[5] $stBuffer = DllStructCreate("int64;byte [" & $nBufSize & "];") $aRet = DllCall("iphlpapi.dll", "ulong", "GetAdaptersAddresses", "ulong", 0, "ulong", 0x86, "ptr", 0, "ptr", DllStructGetPtr($stBuffer), "ulong*", $nBufSize) If @error Then Return SetError(1, @error, "") If $aRet[0] Then Return SetError(2, $aRet[0], "") Dim $aIndexEntries[Floor($nBufSize / 72)][2] $nEntries = 0 $pIPAAStruct = DllStructGetPtr($stBuffer) While $pIPAAStruct <> 0 $stIP_ADAPTER_ADDRESSES = DllStructCreate($tagIP_ADAPTER_ADDRESSES, $pIPAAStruct) $nIPAAStSize = DllStructGetData($stIP_ADAPTER_ADDRESSES, "Length") $nTemp = DllStructGetData($stIP_ADAPTER_ADDRESSES, "OperStatus") If ($nTemp = 2 And Not False) Or DllStructGetData($stIP_ADAPTER_ADDRESSES, "IfType") = 24 Then Else $pTemp = DllStructGetData($stIP_ADAPTER_ADDRESSES, "FirstUnicastAddress") If $pTemp <> 0 Then $aIndexEntries[$nEntries][0] = DllStructGetData($stIP_ADAPTER_ADDRESSES, "IfIndex") $aIndexEntries[$nEntries][1] = _GetStringW_FromPtr(DllStructGetData($stIP_ADAPTER_ADDRESSES, "FriendlyName")) $nEntries += 1 EndIf EndIf $pIPAAStruct = DllStructGetData($stIP_ADAPTER_ADDRESSES, "Next") WEnd If $nEntries = 0 Then Return SetError(-1, 0, "") ReDim $aIndexEntries[$nEntries][2] Return SetExtended($nEntries, $aIndexEntries) EndFunc ;==>_ListIndexInterfaceName Func InterfaceIndexSpeed($IfIndex) Local $tBuffer, $pBuffer, $iResult, $iSpeed $tBuffer = DllStructCreate("wchar[256];dword[5];byte[8];dword[16];char[256]") $pBuffer = DllStructGetPtr($tBuffer) DllStructSetData($tBuffer, 2, $IfIndex, 1) $iResult = DllCall("iphlpapi.dll", "long", "GetIfEntry", "ptr", $pBuffer) If @error Then Return SetError(@error, @extended, 0) $iSpeed = DllStructGetData($tBuffer, 2, 4) ;~ $sDescr = DllStructGetData($tBuffer, 5) $tBuffer = 0 Return SetError($iResult[0], $iSpeed / 1000 / 1000, $iSpeed) EndFunc ;==>InterfaceIndexSpeed Func _GetStringW_FromPtr($pStr) If Not IsPtr($pStr) Or $pStr = 0 Then Return SetError(1, 0, "") Local $aRet = DllCall("kernel32.dll", "ptr", "lstrcpynW", "wstr", "", "ptr", $pStr, "int", 32767) If @error Or Not $aRet[0] Then Return SetError(@error, 0, "") Return $aRet[1] EndFunc ;==>_GetStringW_FromPtr Func _GetMACFromIP($rMAC) If ($rMAC = "") Or ($rMAC = $sNotAvailable) Then Return $sNotAvailable Local $sbMAC = DllStructCreate("byte[6]") Local $siMAC = DllStructCreate("int") DllStructSetData($siMAC, 1, 6) Local $rHexMAC = DllCall("Ws2_32.dll", "int", "inet_addr", "str", $rMAC) $rMAC = $rHexMAC[0] $rHexMAC = DllCall("iphlpapi.dll", "int", "SendARP", "int", $rMAC, "int", 0, "ptr", DllStructGetPtr($sbMAC), "ptr", DllStructGetPtr($siMAC)) $rMAC = "" For $i = 0 To 5 If $i Then $rMAC &= ":" $rMAC = $rMAC & Hex(DllStructGetData($sbMAC, 1, $i + 1), 2) Next If ($rMAC = "") Or ($rMAC = $sBlankMAC) Or ($rMAC = $sNotAvailable) Then Return $sNotAvailable Return $rMAC EndFunc ;==>_GetMACFromIP ;==>_ByteSuffixRound Func _ByteSuffixRound($iBytes, $iRound = 2) $iBytes = Number($iBytes) If $iBytes > 1000000000 Then Return $sNotAvailable Local $A, $aArray[5] = ["Bps", "Kbps", "Mbps", "Gbps", "Tbps"] While $iBytes > 999 $A += 1 If $A > 3 Then ExitLoop $iBytes /= 1000 WEnd Return Round($iBytes, $iRound) & " " & $aArray[$A] EndFunc ;==>_ByteSuffixRound ;==>CreateContentCSV Func CreateContentCSV() Local $sContent If Not IsArray($sAdapterInfo) Then $sAdapterInfo = _GetListAdaptersInfo(".") If IsArray($sAdapterInfo) And $sAdapterInfo[0][0] > 0 Then $sContent &= '"NIC","InterfaceIndex","Adapter","AdapterName","AdapterStatus","GetIPType","IP","SubNetIP","MAC","GetwayIP","GetwayMAC","Speed","DNS1","DNS2","DNS3","DNS4","DNS5","DNS6","DNS7","DNS8"' & @CRLF For $x = 1 To $sAdapterInfo[0][0] $sContent &= '"' & $x & '",' $sContent &= '"' & $sAdapterInfo[$x][0] & '",' $sContent &= '"' & $sAdapterInfo[$x][1] & '",' $sContent &= '"' & $sAdapterInfo[$x][2] & '",' $sContent &= '"' & $sAdapterInfo[$x][3] & '",' $sContent &= '"' & $sAdapterInfo[$x][4] & '",' $sContent &= '"' & $sAdapterInfo[$x][5] & '",' $sContent &= '"' & $sAdapterInfo[$x][6] & '",' $sContent &= '"' & $sAdapterInfo[$x][7] & '",' $sContent &= '"' & $sAdapterInfo[$x][8] & '",' $sContent &= '"' & $sAdapterInfo[$x][9] & '",' $sContent &= '"' & $sAdapterInfo[$x][10] & '",' $sContent &= '"' & $sAdapterInfo[$x][11] & '",' $sContent &= '"' & $sAdapterInfo[$x][12] & '",' $sContent &= '"' & $sAdapterInfo[$x][13] & '",' $sContent &= '"' & $sAdapterInfo[$x][14] & '",' $sContent &= '"' & $sAdapterInfo[$x][15] & '",' $sContent &= '"' & $sAdapterInfo[$x][16] & '",' $sContent &= '"' & $sAdapterInfo[$x][17] & '",' $sContent &= '"' & $sAdapterInfo[$x][18] & '"' & @CRLF Next Return $sContent Else Return SetError(1, 0, False) EndIf EndFunc ;==>CreateContentCSV ;==>CreateContentINI Func CreateContentINI() Local $sContent = "[NetworkInfo]" & @CRLF $sContent &= "Time = " & @YEAR & "/" & @MON & "/" & @MDAY & "-" & @HOUR & ":" & @MIN & ":" & @SEC & @CRLF If Not IsArray($sAdapterInfo) Then $sAdapterInfo = _GetListAdaptersInfo(".") If IsArray($sAdapterInfo) And $sAdapterInfo[0][0] > 0 Then $sContent &= "TotalNIC = " & $sAdapterInfo[0][0] & @CRLF & @CRLF For $x = 1 To $sAdapterInfo[0][0] $sContent &= "[NIC" & $x & "]" & @CRLF $sContent &= "InterfaceIndex = " & $sAdapterInfo[$x][0] & @CRLF $sContent &= "Adapter = " & $sAdapterInfo[$x][1] & @CRLF $sContent &= "AdapterName = " & $sAdapterInfo[$x][2] & @CRLF $sContent &= "AdapterStatus = " & $sAdapterInfo[$x][3] & @CRLF $sContent &= "GetIPType = " & $sAdapterInfo[$x][4] & @CRLF $sContent &= "IP = " & $sAdapterInfo[$x][5] & @CRLF $sContent &= "SubNetIP = " & $sAdapterInfo[$x][6] & @CRLF $sContent &= "MAC = " & $sAdapterInfo[$x][7] & @CRLF $sContent &= "GetwayIP = " & $sAdapterInfo[$x][8] & @CRLF $sContent &= "GetwayMAC = " & $sAdapterInfo[$x][9] & @CRLF $sContent &= "Speed = " & $sAdapterInfo[$x][10] & @CRLF & @CRLF $sContent &= "DNS1 = " & $sAdapterInfo[$x][11] & @CRLF $sContent &= "DNS2 = " & $sAdapterInfo[$x][12] & @CRLF $sContent &= "DNS3 = " & $sAdapterInfo[$x][13] & @CRLF $sContent &= "DNS4 = " & $sAdapterInfo[$x][14] & @CRLF $sContent &= "DNS5 = " & $sAdapterInfo[$x][15] & @CRLF $sContent &= "DNS6 = " & $sAdapterInfo[$x][16] & @CRLF $sContent &= "DNS7 = " & $sAdapterInfo[$x][17] & @CRLF $sContent &= "DNS8 = " & $sAdapterInfo[$x][18] & @CRLF Next Return $sContent Else Return SetError(1, 0, False) EndIf EndFunc ;==>CreateContentINI ;==>_CheckConnect Binary and Source:
-
I've written a small surveillance tool for one of my programs. It shows the time that has already passed, the estimated time until the end, the average time of the steps, and the progress in %. It works pretty well, but I want to add some stats. That'd be the usages of the CPU, RAM, network and hard-drive of all threads in %. Basically what you see in the taskmanager, but without the list of every single process. I'm aware that there's no in-built function for that, and that I'd need an additional library. Are there any for that? Simply functions that return the stats mentioned above. Thanks! Edit: I run an ASUS R752M with an Intel BayTrail M3540 on Windows 10 64-bits.
-
Hi guys I've been looking around to enable/disable network cards using WMI but so far the only way i could get it to work was with this : RunWait(@ComSpec & " /c " & "WMIC PATH Win32_NetworkAdapter WHERE Index=" & $NetAdp_CurrID & " CALL " & $action, "", @SW_HIDE)The $NetAdp_CurrID var would be the index of the network card and the $action var would be enable or disable in my line of code. I know it's possible to do this with wmi without using cmd but i can't figure out how. Anyone who has the answer to my problem? I've tried with using the wmi query and adding .enable() and .disable() at the end but that doesn't work (or at least not for me)
-
Well. I was needing to create a networks shortcut. so I did find anything into the forum. So I write this after reading about Nonfile Object. ;~ Danyfirex 26/07/2015 #include <WinAPIShellEx.au3> Opt("MustDeclareVars", 1) Global Const $SHCONTF_NONFOLDERS = 0x00040 Global Const $SHGDN_NORMAL = 0 Global Const $S_OK = 0 Global Const $sTagSTRRET = "UINT uType;ptr pOleStr;UINT uOffset;CHAR cStr[256]" Global Const $CLSID_ShellLink = "{00021401-0000-0000-C000-000000000046}" Global Const $sIID_IShellLinkW = "{000214F9-0000-0000-C000-000000000046}" Global Const $sTagIShellLink = "getpath hresult(long;long;long;long); " & _ "getidlist hresult(ptr); " & _ "setidlist hresult(ptr); " & _ "getdescription hresult(long;long); " & _ "setdescription hresult(wstr); " & _ "getworkingdirectory hresult(long;long); " & _ "setworkingdirectory hresult(long); " & _ "getarguments hresult(long;long); " & _ "setarguments hresult(ptr); " & _ "gethotkey hresult(long); " & _ "sethotkey hresult(word); " & _ "getshowcmd hresult(long); " & _ "setshowcmd hresult(int); " & _ "geticonlocation hresult(long;long;long); " & _ "seticonlocation hresult(wstr;int); " & _ "setrelativepath hresult(long;long); " & _ "resolve hresult(long;long); " & _ "setpath hresult(wstr)" Global Const $sIID_IPersistFile = "{0000010b-0000-0000-C000-000000000046}" Global Const $sTagIPersistFile = "GetClassID hresult(long); IsDirty hresult(); Load hresult(long;long); Save hresult(wstr;bool); SaveCompleted hresult(long); GetCurFile hresult(long)" Global Const $sIID_IEnumIDList = "{000214F2-0000-0000-C000-000000000046}" Global Const $sTagIEnumIDList = "Next hresult(ulong;ptr*;ulong*);" & _ "Reset hresult();" & _ "Skip hresult(ulong);" & _ "Clone hresult(ptr*);" Global Const $sIID_IShellFolder = "{000214E6-0000-0000-C000-000000000046}" Global Const $sTagIShellFolder = "ParseDisplayName hresult(hwnd;ptr;wstr;ulong*;ptr*;ulong*);" & _ "EnumObjects hresult(hwnd;dword;ptr*);" & _ "BindToObject hresult(ptr;ptr;clsid;ptr*);" & _ "BindToStorage hresult(ptr*;ptr;clsid;ptr*);" & _ "CompareIDs hresult(lparam;ptr*;ptr*);" & _ "CreateViewObject hresult(hwnd;clsid;ptr*);" & _ "GetAttributesOf hresult(uint:ptr*;ulong*);" & _ "GetUIObjectOf hresult(hwnd;uint;ptr*;clsid;uint*;ptr*);" & _ "GetDisplayNameOf hresult(ptr;dword;ptr);" & _ "SetNameOf hresult(hwnd;ptr*;wstr;dword;ptr*);" Local $MyNetWorkConnectionName="Conexión de red inalámbrica" CreateNetWorkConnectionShortCut($MyNetWorkConnectionName) ;~ Success: Return True ;~ Failure: Return False ;~ if $lnkPath = "" ShortCut will be Create on Desktop with the name of the Conections($sConnectionName) Func CreateNetWorkConnectionShortCut($sConnectionName, $lnkPath = "") Local $pConecctionsFolder = 0 Local $oConecctionsFolder = 0 Local $pEnumIDList = 0 Local $oEnumIDList = 0 Local $pPIDLItem = 0 Local $celtFetched = 0 Local $pPIDLConectionsFolder = 0 Local $bRet = False Local $tSTRRET = 0 Local $twstring = 0 Local $pShellFolder = SHGetDesktopFolder() Local $oShellFolder = ObjCreateInterface($pShellFolder, $sIID_IShellFolder, $sTagIShellFolder) If @error Then Return $bRet $pPIDLConectionsFolder = _WinAPI_ShellGetSpecialFolderLocation($CSIDL_CONNECTIONS) If SUCCEEDED($oShellFolder.BindToObject($pPIDLConectionsFolder, Null, $sIID_IShellFolder, $pConecctionsFolder)) Then $oConecctionsFolder = ObjCreateInterface($pConecctionsFolder, $sIID_IShellFolder, $sTagIShellFolder) If IsObj($oConecctionsFolder) Then If SUCCEEDED($oConecctionsFolder.EnumObjects(Null, $SHCONTF_NONFOLDERS, $pEnumIDList)) Then $oEnumIDList = ObjCreateInterface($pEnumIDList, $sIID_IEnumIDList, $sTagIEnumIDList) If IsObj($oEnumIDList) Then $tSTRRET = DllStructCreate($sTagSTRRET) While (SUCCEEDED($oEnumIDList.Next(1, $pPIDLItem, $celtFetched)) And $celtFetched > 0) If SUCCEEDED($oConecctionsFolder.GetDisplayNameOf($pPIDLItem, $SHGDN_NORMAL, DllStructGetPtr($tSTRRET))) Then $twstring = DllStructCreate("wchar Name[512]", $tSTRRET.pOleStr) If $twstring.Name = $sConnectionName Then If $lnkPath = "" Then $lnkPath = @DesktopDir & "\" & $twstring.Name & ".lnk" $bRet = CreateLnk($pPIDLConectionsFolder, $pPIDLItem, $lnkPath) ExitLoop EndIf $twstring = 0 EndIf WEnd EndIf EndIf EndIf EndIf If $pPIDLConectionsFolder Then _WinAPI_CoTaskMemFree($pPIDLConectionsFolder) Return $bRet EndFunc ;==>CreateNetWorkShortCut Func CreateLnk($PIDL1, $PIDL2, $lnkPath) Local $oShellLink = 0 Local $oIPersistFile = 0 Local $pIPersistFile = 0 Local $pAppendID = 0 Local $bRet = False $oShellLink = ObjCreateInterface($CLSID_ShellLink, $sIID_IShellLinkW, $sTagIShellLink) If @error Then Return $bRet $pAppendID = ILAppendID($PIDL1, $PIDL2) If IsObj($oShellLink) And $pAppendID Then If SUCCEEDED($oShellLink.SetIDList($pAppendID)) Then $oShellLink.QueryInterface($sIID_IPersistFile, $pIPersistFile) $oIPersistFile = ObjCreateInterface($pIPersistFile, $sIID_IPersistFile, $sTagIPersistFile) If IsObj($oIPersistFile) Then $bRet = SUCCEEDED($oIPersistFile.Save($lnkPath, True)) EndIf EndIf EndIf Return $bRet EndFunc ;==>CreateLnk Func ILAppendID($PIDLIST_RELATIVE, $LPSHITEMID, $fAppend = True) Local $aRet = DllCall("Shell32.dll", "ptr", "ILAppendID", "ptr", $PIDLIST_RELATIVE, "ptr", $LPSHITEMID, "bool", $fAppend) If @error Then Return SetError(@error, @extended, 0) If $aRet[0] = 0 Then Return SetError(10, $aRet[0], 0) Return $aRet[0] EndFunc ;==>ILAppendID Func SHGetDesktopFolder() Local $aRet = DllCall("Shell32.dll", "long", "SHGetDesktopFolder", "ptr*", Null) If @error Then Return SetError(@error, @extended, 0) If $aRet[0] Then Return SetError(10, $aRet[0], 0) Return $aRet[1] EndFunc ;==>SHGetDesktopFolder Func SUCCEEDED($hr) Return ($hr >= 0) EndFunc ;==>SUCCEEDED Saludos
-
I was needing to check all my connected networks and check if there is internet connection. so I wrote this function. #include <MsgBoxConstants.au3> #include <Array.au3> Global $NLM_ENUM_NETWORK_CONNECTED = 0x01 ;~ Global $NLM_ENUM_NETWORK_DISCONNECTED = 0x02 ;~ Global $NLM_ENUM_NETWORK_ALL = 0x03 Global Enum $eName, $eIsConectedtoInternet Local $aNetworks = GetNetWorks() If @extended Then For $i = 0 To @extended - 1 ConsoleWrite("NetWork Name: " & $aNetworks[$i][$eName] & "| IsConectedToInternet: " & $aNetworks[$i][$eIsConectedtoInternet] & @CRLF) Next _ArrayDisplay($aNetworks, "NetWork Name|NetWork Is Conected to Internet") EndIf ;~ Success: Return an 2DArray[][] and sets @extended Ubound of Array ;~ Failure: Return 0 and set @extended 0 Func GetNetWorks($NLM_ENUM_NETWORK = $NLM_ENUM_NETWORK_CONNECTED) Local $aNetworks[0][2] ;[n][0]NetWorks Name|[n][1]isConnectedtoInternet Local $INetworks = 0 Local $ReDim = 0 Local $oErrorHandler = ObjEvent("AutoIt.Error", "_ErrFunc") Local $oINetworkListManager = ObjCreate("{DCB00C01-570F-4A9B-8D69-199FDBA5723B}") ;Create INetworkListManager Object by CLSID If Not IsObj($oINetworkListManager) Then Return 0 $INetworks = $oINetworkListManager.GetNetworks($NLM_ENUM_NETWORK) If Not IsObj($INetworks) Then Return 0 For $INetwork In $INetworks $ReDim = UBound($aNetworks, 1) + 1 ReDim $aNetworks[$ReDim][2] $aNetworks[$ReDim - 1][0] = $INetwork.GetName $aNetworks[$ReDim - 1][1] = $INetwork.isConnectedtoInternet Next $oINetworkListManager = 0 ;Free Return SetExtended($ReDim, $aNetworks) EndFunc ;==>GetNetWorks ; User's COM error function. Will be called if COM error occurs Func _ErrFunc($oError) ; Do anything here. ConsoleWrite(@ScriptName & " (" & $oError.scriptline & ") : ==> COM Error intercepted !" & @CRLF & _ @TAB & "err.number is: " & @TAB & @TAB & "0x" & Hex($oError.number) & @CRLF & _ @TAB & "err.windescription:" & @TAB & $oError.windescription & @CRLF & _ @TAB & "err.description is: " & @TAB & $oError.description & @CRLF & _ @TAB & "err.source is: " & @TAB & @TAB & $oError.source & @CRLF & _ @TAB & "err.helpfile is: " & @TAB & $oError.helpfile & @CRLF & _ @TAB & "err.helpcontext is: " & @TAB & $oError.helpcontext & @CRLF & _ @TAB & "err.lastdllerror is: " & @TAB & $oError.lastdllerror & @CRLF & _ @TAB & "err.scriptline is: " & @TAB & $oError.scriptline & @CRLF & _ @TAB & "err.retcode is: " & @TAB & "0x" & Hex($oError.retcode) & @CRLF & @CRLF) EndFunc ;==>_ErrFunc Saludos
-
I slightly modified code from this post by Guinness so I can display a computer's network configuration. #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 #cs This program displays specific info about a PC's NIC configuration (see For/next loop below for details) If you click OK it will then display a matrix view of the same info in case you want to copy this info to the clipboard Clicking Cancel will skip the matrix view #ce #include <Array.au3> Global $aArray = _IPDetails(), $sData For $A = 1 To $aArray[0][0] $sData &= "Description: " & $aArray[$A][0] & @CRLF & _ "Connection Name: " & _GetNetworkID($aArray[$A][0]) & @CRLF & _ "IP Address: " & $aArray[$A][1] & @CRLF & _ "MAC: " & $aArray[$A][2] & @CRLF & _ "Default Gateway: " & $aArray[$A][3] & @CRLF & _ "DNS Servers: " & $aArray[$A][4] & @CRLF & _ "Obtain DNS Automatically: " & $aArray[$A][5] & @CRLF & _ "Auto IP: " & $aArray[$A][6] & @CRLF & @CRLF Next $sData = StringTrimRight($sData, 4) If MsgBox (1,"Results (Cancel to skip arrayview)",$sData) = $IDCANCEL then Exit _ArrayDisplay($aArray,"Active Network Adapters","1:7",16,"","Description|IP Address|MAC|Gateway|DNS|ADNS|DHCP") Exit Func _IPDetails() Local $iCount = 0 Local $oWMIService = ObjGet("winmgmts:{impersonationLevel = impersonate}!\\" & "." & "\root\cimv2") Local $oColItems = $oWMIService.ExecQuery("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True", "WQL", 0x30), $aReturn[1][7] = [[0, 7]] If IsObj($oColItems) Then For $oObjectItem In $oColItems $aReturn[0][0] += 1 $iCount += 1 If $aReturn[0][0] <= $iCount + 1 Then ReDim $aReturn[$aReturn[0][0] * 2][$aReturn[0][1]] EndIf $aReturn[$iCount][0] = _IsString($oObjectItem.Description) $aReturn[$iCount][1] = _IsString($oObjectItem.IPAddress(0)) $aReturn[$iCount][2] = _IsString($oObjectItem.MACAddress) $aReturn[$iCount][3] = _IsString($oObjectItem.DefaultIPGateway(0)) $aReturn[$iCount][4] = _WMIArrayToString($oObjectItem.DNSServerSearchOrder(), " - ") $aReturn[$iCount][5] = _WMIRegRead($oObjectItem.SettingID) $aReturn[$iCount][6] = _IsString($oObjectItem.DHCPEnabled) Next ReDim $aReturn[$aReturn[0][0] + 1][$aReturn[0][1]] Return $aReturn EndIf Return SetError(1, 0, $aReturn) EndFunc ;==>_IPDetails Func _WMIRegRead($iGUID) If RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\" & $iGUID & "\", "NameServer") = "" Then Return True EndIf Return False EndFunc ;==>_WMIRegRead Func _GetNetworkID($sAdapter) Local $oWMIService = ObjGet("winmgmts:{impersonationLevel = impersonate}!\\" & "." & "\root\cimv2") Local $oColItems = $oWMIService.ExecQuery('Select * From Win32_NetworkAdapter Where Name = "' & $sAdapter & '"', "WQL", 0x30) If IsObj($oColItems) Then For $oObjectItem In $oColItems Return $oObjectItem.NetConnectionID Next EndIf Return SetError(1, 0, "Unknown") EndFunc ;==>_GetNetworkID Func _IsString($sString) If IsString($sString) Or IsBool($sString) Then Return $sString EndIf Return "Not Available" EndFunc ;==>_IsString Func _WMIArrayToString($aArray, $sDelimeter = "|") ; Guinness' own version of ArrayToString() If IsArray($aArray) = 0 Then Return SetError(1, 0, "Not Available") EndIf Local $iUbound = UBound($aArray) - 1, $sString For $A = 0 To $iUbound $sString &= $aArray[$A] & $sDelimeter Next Return StringTrimRight($sString, StringLen($sDelimeter)) EndFunc ;==>_WMIArrayToString Now I'd like to get this same information about other computers in the workgroup. I thought it would be as simple as making the following change: Local $oWMIService = ObjGet("winmgmts:{impersonationLevel = impersonate}!\\" & "." & "\root\cimv2") to Local $oWMIService = ObjGet("winmgmts:{impersonationLevel = impersonate}!\\" & "othercomputer" & "\root\cimv2")But that throws the following error. I've verified that I can perform remote ops like "PSexec \\othercomputer" and "shutdown /M \\othercomputer" on the remote PC so I don't think it's a problem external to my code. What am I doing wrong? Thank you.
-
Hi I making a small tool that create wifi Hotspot use netsh cmd All command is ok But only sharing option that i dont know how to control That list all network for choice one network to share Then set properties Sharing I find any infomation about 2hour but i cant find anything I thinking about control click but it will not right for all windows version Please. Help me! Have you some ideas?
-
I have two networks that I have to switch between often (really annoying). Does anyone know how to connect to a WiFi network using Autoit? I would like to avoid solutions with MouseClick(). So something like: HotKeySet("_ToggleNetwork", "~") While 1 Sleep(1000) WEnd Func _ToggleNetwork() If Network A is connected Then Connect to Network B If Network B is connected Then Connect to Network A EndFun
- 1 reply
-
- Toggling WiFi Networks
- Toggle
-
(and 2 more)
Tagged with:
-
Hi, I'm trying all day to write a working proxy server, but it still doesn't work correctly. I'm not good at network functions, so maybe I've forgot about something. It should receive, modify and send data between a browser and web server. Here is a code. I just added a short comments. I hope it will make the script more readably. #Region Tables #include <Array.au3> Global $sProxyIP = @IPAddress1, $iProxyPort = 8080, $iProxySocket = -1 Global $iNewSocket, $asLines[0], $sHost, $iLen Global $aiBrowserSocket[0], $asBrowserRecv[0], $aiServerSocket[0], $asServerRecv[0], $aiServerContentLen[0] #EndRegion Tables #Region Initialization If Not TCPStartup() Then Exit @ScriptLineNumber $iProxySocket = TCPListen($sProxyIP, $iProxyPort) If @error Then Exit @ScriptLineNumber #EndRegion Initialization While 1 ;Accepting new sockets $iNewSocket = TCPAccept($iProxySocket) If $iNewSocket >= 0 Then ProxyAddArray($iNewSocket) ;Browser --> Proxy For $socket = 0 To UBound($asBrowserRecv) - 1 $asBrowserRecv[$socket] = BinaryToString(TCPRecv($aiBrowserSocket[$socket], 1024 ^ 2)) If @error Then ProxyDeleteArray($socket) $socket += 1 ContinueLoop EndIf Next ;Browser data analyzing For $socket = 0 To UBound($asBrowserRecv) - 1 $sHost = '' $asLines = StringSplit($asBrowserRecv[$socket], @CRLF, 1) For $line = 1 To $asLines[0] If StringLeft($asLines[$line], 4) = 'Host' Then $sHost = StringTrimLeft($asLines[$line], 6) ExitLoop EndIf Next $aiServerSocket[$socket] = TCPConnect(TCPNameToIP($sHost), 80) If @error Then ProxyDeleteArray($socket) $socket += 1 ContinueLoop EndIf Next ;Proxy --> Web Page For $socket = 0 To UBound($aiServerSocket) - 1 If $aiServerSocket[$socket] < 0 Then ContinueLoop $asServerRecv[$socket] = TCPSend($aiServerSocket[$socket], $asBrowserRecv[$socket]) If @error Then $aiServerSocket[$socket] = -1 Next ;Web Page --> Proxy For $socket = 0 To UBound($aiServerSocket) - 1 If $aiServerSocket[$socket] < 0 Then ContinueLoop $iLen = 0 $asServerRecv[$socket] = BinaryToString(TCPRecv($aiServerSocket[$socket], 1024 ^ 2 * 10)) If StringLen($asServerRecv[$socket]) = 0 Then ContinueLoop $asLines = StringSplit($asServerRecv[$socket], @CRLF, 1) If @error Then $aiServerSocket[$socket] = -1 For $line = 1 To $asLines[0] ;Data lenght If StringLeft($asLines[$line], 14) = 'Content-Length' Then $iLen = StringTrimLeft($asLines[$line], 16) $aiServerContentLen[$socket] = $iLen ExitLoop EndIf Next Next ;Proxy --> Browser For $socket = 0 To UBound($aiBrowserSocket) - 1 If $aiServerContentLen[$socket] > StringLen($asBrowserRecv[$socket]) Then ContinueLoop TCPSend($aiBrowserSocket[$socket], $asServerRecv[$socket]) Next WEnd #Region Proxy Func ProxyAddArray($iSocket) _ArrayAdd($aiBrowserSocket, $iSocket) _ArrayAdd($asBrowserRecv, '') _ArrayAdd($aiServerSocket, -1) _ArrayAdd($asServerRecv, '') _ArrayAdd($aiServerContentLen, 0) EndFunc ;==>ProxyAddArray Func ProxyDeleteArray($iIndex) _ArrayAdd($aiBrowserSocket, $iIndex) _ArrayAdd($asBrowserRecv, $iIndex) _ArrayAdd($aiServerSocket, $iIndex) _ArrayAdd($asServerRecv, $iIndex) _ArrayAdd($aiServerContentLen, $iIndex) EndFunc ;==>ProxyDeleteArray #EndRegion Proxy Important: Before you will check this, you should change connection setting in your web browser. And please do not post links to other old proxy server from Autoit Forums. I've tried them all.
-
-
I needed to convert ip ranges for a firewall. It wasn't able to work with ranges, but with groups of classless IP networks. This one here is helping me to calculate all (classless) networks fitting within an given IP range. While testing the necessary functions I added a small user interface.. giving a small calculator tool. Have fun .- ) range2nets.au3
-
My queestion, is what is the best way to synchronize autoit scripts running on different computers in a network? to the effect that I could sync them, and then beep() and they would both beep at the exact same time I'm not sure even where to start. Has anyone done anything like this before?
-
This is a very simple application to backup a list of your local and network printers to a shared resource. when you restore the printers, the app will just install the printers that were networked. Feel free to improve upon and use. Let me know what you think I have many more applications and I may post more later. #include <File.au3> #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Global $Backpath = "\\Myawesomeserver\useraccounts" Global $fp = ($Backpath & @UserName) #Region ### START Koda GUI section ### Form= $Form1 = GUICreate("Printer Tools", 334, 75, 192, 124) $save = GUICtrlCreateButton("Save Printers", 8, 8, 155, 57) $load = GUICtrlCreateButton("Load Printers", 168, 8, 155, 57) GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $save ExportPrinters() Case $load ImportPrinters() EndSwitch WEnd Func ImportPrinters() $File = $fp & "\NetworkPrinters.txt" FileOpen($File, 0) For $i = 1 to _FileCountLines($File) $line = FileReadLine($File, $i) RunWait(@ComSpec & " /c " & "rundll32 printui.dll,PrintUIEntry /in /n " & $line, "", @SW_HIDE) Next FileClose($File) Msgbox(0, "", "Network Printer Import Complete") endfunc ;==>ImportPrinters Func ExportPrinters() $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colItems = "" $Output = "" $nOutput = "" $objWMIService = ObjGet("winmgmts:\\" & @computername & "\root\CIMV2") $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_Printer", "WQL", _ $wbemFlagReturnImmediately + $wbemFlagForwardOnly) If IsObj($colItems) then For $objItem In $colItems If Stringinstr($objItem.DeviceID, "\\") then $nOutput = $nOutput & $objItem.DeviceID & @CRLF else $Output = $Output & $objItem.DeviceID & @CRLF endif Next FileWrite($fp & "\NetworkPrinters.txt", $nOutput) FileWrite($fp & "\LocalPrinters.txt", $Output) Else FileWrite($fp & "\Printers.txt", "No printers Found") Endif Msgbox(0, "", "Printer Export Complete") EndFunc ;==>ExportPrinters