简体   繁体   中英

How do I parse the output of getmac command?

After doing some research I found out that the best way to get the Ethe.net MAC address under windows is the "getmac" command. (getmac module of python does not produce the same..): Now I want to use this command from within a python code to get the MAC address. I figured out that my code should start something like this:

import os
if sys.platform == 'win32':
    os.system("getmac")
    do something here to get the first mac address that appears in the results

here is an example output

Physical Address    Transport Name                                            
=================== ==========================================================  
1C-69-7A-3A-E3-40   Media disconnected                                        
54-8D-5A-CE-21-1A   \Device\Tcpip_{82B01094-C274-418F-AB0A-BC4F3660D6B4}      

I finally want to get 1C-69-7A-3A-E3-40 preferably without the dashes. Thanks in advance.

Two things. First of all, I recommend you find ways of getting the mac address more elegantly. This question's answer seems to use the uuid module , which is perhaps a good cross-platform solution.

Having said that , if you want to proceed with parsing the output of a system call, I recommend the use of Python's subprocess module . For example:

import subprocess

output_of_command = subprocess.check_output("getmac")

This will run getmac and the output of that command will go into a variable. From there, you can parse the string.

Here's how you might extract the mac address from that string:

# I'm setting this directly to provide a clear example of the parsing, separate
# from the first part of this answer.

my_string = """Physical Address Transport Name
=================== ==========================================================
1C-69-7A-3A-E3-40 Media disconnected
54-8D-5A-CE-21-1A \Device\Tcpip_{82B01094-C274-418F-AB0A-BC4F3660D6B4}"""

my_mac_address = my_string.rsplit('=', 1)[-1].split(None, 1)[0]

The first split is a right split . It's breaking up the string by the '=' character, once, starting from the end of the string. Then, I'm splitting the output of that by whitespace, limiting to one split, and taking the first string value.

Again, however, I would discourage this approach to getting a mac address. Parsing the human-readable output of command line scripts is seldom advisable because the output can unexpectedly be different than what your script is expecting. You can assuredly get the mac address in a more robust way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM