Sign in to follow this  
Followers 0
kerrycorcoran

Capture MAC Address

25 posts in this topic

Anyone know of a script to capture the MAC Address?

Thanks in advance.

Kerry

Share this post


Link to post
Share on other sites



I Have one but not at tis location.

Maybe you can re create it.

I used

_rundos("ipconfig /all > temp.txt")

after that filtered te temp.txt using stringregexpreplace

someting like "[0-9A-F]{2}:[0-9A-F]{2}: etc etc

sorry I donot have it at this computer

Share this post


Link to post
Share on other sites

Created a better one then the one I had

CAll the file getmac.au3 or something

; ----------------------------------------------------------------------------
;
; AutoIt Version: 3.1.1.97
; Author:        MrSpacely
;
; Script Function:
;   Gets MAC addresses from ipconfig /all command tested on windows 2000 sp4 to windows xp sp2
;   Might work on windows 98 not tested
;
;   _GetMAC
;   --------------------------------------------------------------------------------
;
;   Returns the MAC address of the computer.
;
;
;   _GetMAC ([Index])
;
;   Parameters
;   
;   Index       Select wich MAC address you want. Often computers have more then one
;           Can range from 1 to infinite.
;           Default is 1.
;           If you use 0 it returns the amount of MAC addressen found.
;           If you use -1 it returns the last MAC address found.
;
;   Return Value
;
;   Success: Returns the MAC address.
;   Failure: Returns 0 
;
;
; ----------------------------------------------------------------------------


#Include <process.au3>

Func _GetMAC ($getmacindex = 1) 
    _RunDOS( "ipconfig /all > getmactm.txt")
    $getmacfl = fileopen("getmactm.txt",0)
    if $getmacfl = -1 then 
        return 0
        filedelete("getmactm.txt")
    endif
    $getmacfilesize = Filegetsize("getmactm.txt") 
    $getmacstring = FileRead($getmacfl,$getmacfilesize) 
    fileclose($getmacfl)
    filedelete("getmactm.txt")
    $getmacstring = StringStripWS ( $getmacstring, 3)
    $macdashed = StringRegExp ( $getmacstring, "([0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2})",3)
    if NOT @extended then return 0
    if NOT isarray($macdashed) then return 0
    if $getmacindex = 0 then return ubound($macdashed)
    if $getmacindex < -1 then return 0
    if $getmacindex > ubound($macdashed) OR $getmacindex = -1 then  $getmacindex = ubound($macdashed)  
    $macsemicolon = StringReplace($macdashed[$getmacindex-1],"-",":",0)
    return $macsemicolon
EndFunc

example code call this file test.au3 or something

#include "getmac2.au3"

msgbox(0,"",_GetMAC(0) & @CRLF & _GetMAC(1) & @CRLF & _GetMAC(-1))

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

In an effort to not require an external file, may I suggest a slight modification to MrSpacely's code?

Func _GetMAC($getmacindex = 1)
    $ipHandle = Run(@ComSpec & ' /c ipconfig /all', '', @SW_HIDE, 2)
    $macdashed = StringRegExp(StringStripWS(StdoutRead($ipHandle), 3), '([0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2})', 3)
    If Not @extended Then Return 0
    If Not IsArray($macdashed) Then Return 0
    If $getmacindex = 0 Then Return UBound($macdashed)
    If $getmacindex < - 1 Then Return 0
    If $getmacindex > UBound($macdashed) Or $getmacindex = -1 Then $getmacindex = UBound($macdashed)
    $macsemicolon = StringReplace($macdashed[$getmacindex - 1], '-', ':', 0)
    Return $macsemicolon
EndFunc ;==>_GetMAC
Edited by MSLx Fanboy

Writing AutoIt scripts since
_DateAdd("d", -2, _NowCalcDate())

Share this post


Link to post
Share on other sites

In an effort to not require an external file, may I suggest a slight modification to MrSpacely's code?

Func _GetMAC($getmacindex = 1)
    $ipHandle = Run(@ComSpec & ' /c ipconfig /all', '', @SW_HIDE, 2)
    $macdashed = StringRegExp(StringStripWS(StdoutRead($ipHandle), 3), '([0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2})', 3)
    If Not @extended Then Return 0
    If Not IsArray($macdashed) Then Return 0
    If $getmacindex = 0 Then Return UBound($macdashed)
    If $getmacindex < - 1 Then Return 0
    If $getmacindex > UBound($macdashed) Or $getmacindex = -1 Then $getmacindex = UBound($macdashed)
    $macsemicolon = StringReplace($macdashed[$getmacindex - 1], '-', ':', 0)
    Return $macsemicolon
EndFunc;==>_GetMAC
I appreciate all the assistance on this! :P

Now, for the bad news. The code you guys are writing is WAY above my level of expertise. At this point I am attemping to learn how to code this and understand what I am coding.

The approach I took was to run IPCONFIG /all to a text file. I then opened that text file and read a specific line (the line containing the MAC address) and then I assigned a variable to the MAC.

The first problem I noticed was if I ran the script on another computer the line that gets read is not the same..if I count them they are the same, but for some reason AIv3 is not pulling the same information. I imagine this has to do with the various window sizes in which notepad can open??

Anyway, how would I go about searching a txt file for string of characters? I assume this is an array?

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

As you read my code you can simply call the function

_GetMAC(1)

to get the first MAC found and use it in your code

You donot have to rewrite the hole function

because I (and MSLx Fanboy his addtition) works completely

you may use it in your script;)

#Include <process.au3>

;here your code
msgbox(64,"Example","My MAC address is " & _GetMAC(1)); Will show a messagebox showing the mac address


;here code wich is needed

Func _GetMAC($getmacindex = 1)
    $ipHandle = Run(@ComSpec & ' /c ipconfig /all', '', @SW_HIDE, 2)
    $macdashed = StringRegExp(StringStripWS(StdoutRead($ipHandle), 3), '([0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2})', 3)
    If Not @extended Then Return 0
    If Not IsArray($macdashed) Then Return 0
    If $getmacindex = 0 Then Return UBound($macdashed)
    If $getmacindex < - 1 Then Return 0
    If $getmacindex > UBound($macdashed) Or $getmacindex = -1 Then $getmacindex = UBound($macdashed)
    $macsemicolon = StringReplace($macdashed[$getmacindex - 1], '-', ':', 0)
    Return $macsemicolon
EndFunc;==>_GetMAC
Edited by MrSpacely

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

In an effort to not require an external file, may I suggest a slight modification to MrSpacely's code?

Func _GetMAC($getmacindex = 1)
    $ipHandle = Run(@ComSpec & ' /c ipconfig /all', '', @SW_HIDE, 2)
    $macdashed = StringRegExp(StringStripWS(StdoutRead($ipHandle), 3), '([0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2})', 3)
    If Not @extended Then Return 0
    If Not IsArray($macdashed) Then Return 0
    If $getmacindex = 0 Then Return UBound($macdashed)
    If $getmacindex < - 1 Then Return 0
    If $getmacindex > UBound($macdashed) Or $getmacindex = -1 Then $getmacindex = UBound($macdashed)
    $macsemicolon = StringReplace($macdashed[$getmacindex - 1], '-', ':', 0)
    Return $macsemicolon
EndFunc;==>_GetMAC
Hmm fun

I made the capture code before they added this stream read thing.

Good fix

Edited by MrSpacely

Share this post


Link to post
Share on other sites

Tis code does what you want. Capture to a text file, finds a string, deletes some characters and displays a message.

$err = RunWait(@ComSpec & ' /c ipconfig /all' & _
  ' | find "Physical Address" > a.tmp', @ScriptDir, @SW_HIDE)

If $err Then
; There was an error finding it
EndIf

$mac = FileReadLine("a.tmp", 1)
If @error Then
; There was an error finding it
EndIf

FileDelete("a.tmp")

$mac = StringTrimLeft($mac,43)

MsgBox(4096,"",$mac)

If you don't want to delete the characters before the mac address, remove the StringTrimLeft line.

Hope it helps


CheersNobby

Share this post


Link to post
Share on other sites

What if there is more than 1 NIC installed on a system?


Writing AutoIt scripts since
_DateAdd("d", -2, _NowCalcDate())

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

Tis code does what you want. Capture to a text file, finds a string, deletes some characters and displays a message.

$err = RunWait(@ComSpec & ' /c ipconfig /all' & _
  ' | find "Physical Address" > a.tmp', @ScriptDir, @SW_HIDE)

If $err Then
; There was an error finding it
EndIf

$mac = FileReadLine("a.tmp", 1)
If @error Then
; There was an error finding it
EndIf

FileDelete("a.tmp")

$mac = StringTrimLeft($mac,43)

MsgBox(4096,"",$mac)

If you don't want to delete the characters before the mac address, remove the StringTrimLeft line.

Hope it helps

Thanks for adding but regexp is much more efficient.

My regexp just looks for all MAC addresses no need to trim or do anything.

check http://www.regular-expressions.info/ for more info

regexp rocks :P

also find "Physical Address" > a.tmp

find only works on windows XP physical address only works on english version

Edited by MrSpacely

Share this post


Link to post
Share on other sites

What if there is more than 1 NIC installed on a system?

then call my function with _GetMAC(0) to get the amount of MAC's

and select on using _GetMAC(3) or something

Hmm I just think you reacted on that other script :P

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

...The code you guys are writing is WAY above my level of expertise. At this point I am attemping to learn how to code this and understand what I am coding...

...Anyway, how would I go about searching a txt file for string of characters?...

;write ipconfig output to temp file
RunWait(@ComSpec & ' /c ipconfig /all > c:\temp\IP.txt', "", @SW_HIDE)

;reads the entire file into the variable
$info = FileRead('c:\temp\IP.txt', FileGetSize('c:\temp\IP.txt'))
;See help file sample for FileRead for some error checking code.

;make an array by splitting each line at the carriage return/line feed
$infoARRAY = StringSplit($info, @CRLF, 1)

;loop thru part of the array
For $i = 1 To $infoARRAY[0]
    
;if the string "Physical Address" is found in the line then
    If StringInStr($infoARRAY[$i], "Physical Address") Then
        
    ;return the last 18 characters of that line
        $macLONG = StringRight($infoARRAY[$i], 18)
        
    ;remove the dashes
        $macSHORT = StringReplace($macLONG, '-', '')
    EndIf
Next

MsgBox(0, "Mac", $macLONG & @CR & $macSHORT)
This post was just to answer your specific question.

See all of the other posts for why code like this will not work in all cases.

...hope this helps...

Edit: and then there is this post

http://www.autoitscript.com/forum/index.php?showtopic=9129

where GregThompson uses

net config workstation

to get the mac of the active NIC

Edit2: I explored "net config workstation" a bit more using different dialup connections. You will not always get a MAC address from that command - it depends on the type of connection. Also, "net config workstation" returns a line named "Workstation active on" which I took to be the "active NIC" if there were more than one. This may not be the case for certain connection scenarios.

A wireless, wired and dialup connection all walked into a bar... uhmm... were all connected (had an IP) and "net config workstation" returned two MAC addresses. One for the wireless and one for the wired.

Edited by herewasplato

[size="1"][font="Arial"].[u].[/u][/font][/size]

Share this post


Link to post
Share on other sites

#13 ·  Posted (edited)

Thanx hwp! :P

This is nicely laid out & works well... once I had created the c:\temp folder. And it got the ACTIVE nic, not my first one, which is disconnected. Thanx for the link to GregThompson's script as well. Mike

Edited by Mikey

Share this post


Link to post
Share on other sites

Using scriptomatic to create this:

You'll need the beta

$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20
$colItems = ""
$strComputer = "localhost"

$Output=""
$Output = $Output & "Computer: " & $strComputer  & @CRLF
$Output = $Output & "==========================================" & @CRLF
$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
$colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter", "WQL", _
                                          $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

If IsObj($colItems) then
   For $objItem In $colItems
      
      $Output = $Output & "MACAddress: " & $objItem.MACAddress & @CRLF
      $Output = $Output & "Name: " & $objItem.Name & @CRLF
      $Output = $Output & "NetConnectionID: " & $objItem.NetConnectionID & @CRLF
      $Output = $Output & "NetConnectionStatus: " & $objItem.NetConnectionStatus & @CRLF
      $strNetworkAddresses = $objItem.NetworkAddresses(0)
      $Output = $Output & "NetworkAddresses: " & $strNetworkAddresses & @CRLF
      $Output = $Output & "PermanentAddress: " & $objItem.PermanentAddress & @CRLF
      if Msgbox(1,"WMI Output",$Output) = 2 then ExitLoop
      $Output=""
   Next
Else
   Msgbox(0,"WMI Output","No WMI Objects Found for class: " & "Win32_NetworkAdapter" )
Endif


Func WMIDateStringToDate($dtmDate)

    Return (StringMid($dtmDate, 5, 2) & "/" & _
    StringMid($dtmDate, 7, 2) & "/" & StringLeft($dtmDate, 4) _
    & " " & StringMid($dtmDate, 9, 2) & ":" & StringMid($dtmDate, 11, 2) & ":" & StringMid($dtmDate,13, 2))
EndFunc

Share this post


Link to post
Share on other sites

#15 ·  Posted (edited)

;write ipconfig output to temp file
RunWait(@ComSpec & ' /c ipconfig /all > c:\temp\IP.txt', "", @SW_HIDE)

;reads the entire file into the variable
$info = FileRead('c:\temp\IP.txt', FileGetSize('c:\temp\IP.txt'))
;See help file sample for FileRead for some error checking code.

;make an array by splitting each line at the carriage return/line feed
$infoARRAY = StringSplit($info, @CRLF, 1)

;loop thru part of the array
For $i = 1 To $infoARRAY[0]
    
;if the string "Physical Address" is found in the line then
    If StringInStr($infoARRAY[$i], "Physical Address") Then
        
;return the last 18 characters of that line
        $macLONG = StringRight($infoARRAY[$i], 18)
        
;remove the dashes
        $macSHORT = StringReplace($macLONG, '-', '')
    EndIf
Next

MsgBox(0, "Mac", $macLONG & @CR & $macSHORT)
This post was just to answer your specific question.

See all of the other posts for why code like this will not work in all cases.

...hope this helps...

Edit: and then there is this post

http://www.autoitscript.com/forum/index.php?showtopic=9129

where GregThompson uses

net config workstation

to get the mac of the active NIC

Like I said regexp is better your script doesn't work on any other language version.

Please donot say my script doesn't work all the time

My script works on any language and also works with 300 network cards installed

So you did not see the other post did not read any of the other scripts.

Also using stringtrim is never fail save other version of windows often use a diffrent amount of spaces

So it fail your script fails

Please reread my script and see my script fails less then yours;)

Edited by MrSpacely

Share this post


Link to post
Share on other sites

What if there is more than 1 NIC installed on a system?

@kerrycorcoran,

Forgot to say - Welcome to the forum! So, welcome.

[Try not to be overwhelmed by all of the helpful posts and code.]

I think that MSL was pointing out something for you (and those posting scripts) to think about and Ill add: What if the MAC address has been changed via a NetworkAddress entry? What if it changes with every boot? or randomly thru out the day? The point is; you asked how to capture the MAC address. You might not want to put too much stock in a MAC address these days. At least on the XP OS, it is easy to change.


[size="1"][font="Arial"].[u].[/u][/font][/size]

Share this post


Link to post
Share on other sites

@kerrycorcoran,

Forgot to say - Welcome to the forum! So, welcome.

[Try not to be overwhelmed by all of the helpful posts and code.]

I think that MSL was pointing out something for you (and those posting scripts) to think about and Ill add: What if the MAC address has been changed via a NetworkAddress entry? What if it changes with every boot? or randomly thru out the day? The point is; you asked how to capture the MAC address. You might not want to put too much stock in a MAC address these days. At least on the XP OS, it is easy to change.

MAC addresses are hardware burned into the chips

Old intel chips had a function to change new ones donot.

Ofcourse there are ways to spoof this but its not happening on every computer actually its very likely

Share this post


Link to post
Share on other sites

...So you did not see the other post did not read any of the other scripts...

@ MrSpacely ,

I did read all of the other posts and IMNSHO, none of them did what my post attempted (he says arrogantly) :-).

You missed the point of my post. My post and code was not about making a script that works in all cases. It is about attempting to teaching the original poster (OP) how to do what was requested ["how would I go about searching a txt file for string of characters"].

You and your posts can educate the OP further as time/desire allows. (Your post/code has the potential to do that if you wish to explain each line of code to the OP instead of posting it and saying - use this. The OP might not understand how to call UDF functions.)

I'm not saying that my script will work in all cases - in fact, I think that I mentioned that it will not always work... but I bet that it answered the specific question asked and we can build on that knowledge in later posts.

BTW, only Chris L clearly mentioned the need for the beta AutoIt release to run the code in his/her post. You (MrSpacely) gave a hint with this line "AutoIt Version: 3.1.1.97." If you are going to post code that requires beta to a person that joined the forum a few hours ago you might want to make it clear that they need the beta release and how to get it.

Also keep in mind that I do not have/want the beta release of AutoIt so I can not try your code... I do not need to know the MAC address of any system on my network (they are all fake).


[size="1"][font="Arial"].[u].[/u][/font][/size]

Share this post


Link to post
Share on other sites

#19 ·  Posted (edited)

MAC addresses are hardware burned into the chips

Old intel chips had a function to change new ones donot.

Ofcourse there are ways to spoof this but its not happening on every computer actually its very likely

"Spoof" is not a very well defined term. If you consider one registry entry a spoof, then so be it.

Edit: I like your code (in post 3 and the subsequent mods) very much - I can tell what it does without running it. I do not think that it is the best code to post for a person that is new to the forum unless you are going to explain it better... but that is just me.

Edited by herewasplato

[size="1"][font="Arial"].[u].[/u][/font][/size]

Share this post


Link to post
Share on other sites

Well I saw ChrisL's excellent WMI/Scripto example in another thread so I hacked together the following function from it. It's a cut-down function that returns the macs and their descriptions. Just posting for completness/an alternative method as I've seen Chris's example on page one of this thread - someone may find it useful.

; Code hacked from ChrisL excellent WMI Example
; Nice one, Chris!
;
; Builds a string of all active MAC addy's on the local (localhost) system
; Requires Beta (Current Stable is 3.1.1.0)

;usage example
msgbox (0," ", _AllActiveMACs())



Func _AllActiveMACs()
$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20
$strComputer = "localhost"

$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
$colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration", "WQL", _
                                            $wbemFlagReturnImmediately + $wbemFlagForwardOnly)  
    If IsObj($colItems) then
        $Output=""
        For $objItem In $colItems
            If stringlen($objItem.MACAddress) > 1 then ; "empty" MAC are returned as "0"
                                                    ;truncate the line below to lose the descriptions
                $Output = $Output & $objItem.MACAddress & " (" & $objItem.caption & ")" & @CRLF
            EndIf
        Next
        return $Output 
    Else
       Return "No Active MACs"; no active MACs found
    Endif
endfunc

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0