Python/Python 모듈탐구

[Python] - 모듈탐구 getmac - Python으로 MAC주소 확인하기

네트워크를 사용해서 프로그래밍을 하다 보면 빼놓을 수 없는 부분이 이 MAC address이다. IP와 같이 쉽게 변경이 불가하고(ARP나 VM은 논외로 하자 자신의 NIC MAC 주소만 두고 보았을 때다.) 앞의 24bit를 이용해서 제조사까지 알아낼 수 있기 때문에, 많은 프로토콜에서 이 MAC Address를 사용한다. 이번 시간에는 getmac모듈과 함께 Python에서 MAC 주소를 알 수 있는 방법을 알아보자


1. Python에서 MAC 주소 가져오기 - GETMAC

getmac은 하나의 매소드만을 제공하는 Python 외장함수이다. >> pip3 install getmac으로 가져와야 한다.(3.X기준)

### getmac의 사용 ###
>>> import getmac

>>> getmac.get_mac_address()
'XX:XX:XX:XX:XX:XX'

간단한 내용이다. getmac의 구현부를 보면 다음과 같은 매서드 정의부를 확인할 수 있다.

def get_mac_address(
    interface=None, ip=None, ip6=None, hostname=None, network_request=True
):
    # type: (Optional[str], Optional[str], Optional[str], Optional[str], bool) -> Optional[str]
    """Get a Unicast IEEE 802 MAC-48 address from a local interface or remote host.

    You must only use one of the first four arguments. If none of the arguments
    are selected, the default network interface for the system will be used.

    Exceptions will be handled silently and returned as a None.
    For the time being, it assumes you are using Ethernet.

    NOTES:
    * You MUST provide str-typed arguments, REGARDLESS of Python version.
    * localhost/127.0.0.1 will always return '00:00:00:00:00:00'

    Args:
        interface (str): Name of a local network interface (e.g "Ethernet 3", "eth0", "ens32")
        ip (str): Canonical dotted decimal IPv4 address of a remote host (e.g 192.168.0.1)
        ip6 (str): Canonical shortened IPv6 address of a remote host (e.g ff02::1:ffe7:7f19)
        hostname (str): DNS hostname of a remote host (e.g "router1.mycorp.com", "localhost")
        network_request (bool): Send a UDP packet to a remote host to populate
        the ARP/NDP tables for IPv4/IPv6. The port this packet is sent to can
        be configured using the module variable `getmac.PORT`.
    Returns:
        Lowercase colon-separated MAC address, or None if one could not be
        found or there was an error.
    """

그니까 정리를 하면 NIC에 대한 이름과, mac주소를 가져올 단말기의 ipv4, v6 주소, DNS 호스트네임을 지정할 수 있다는 의미이다.

 

아래의 방법도 MAC Address를 가져오는데 많이 사용된다.

 

 

2. Python에서 MAC 주소 가져오기 - psutil

>>> import psutil
>>> nics = psutil.net_if_addrs()
### nics는 네트워크 정보를 가진 Dictionary가 된다. 보고 추출하면 된다.

psutil module은 프로세스 관리에 주로 사용된다. RAM이나, 스레드의 상태를 확인하고 변경하는데 특화되어있다. 그중 net_if_addr() 함수는 네트워크의 정보를 가져온다.

 

 

3. Python에서 MAC 주소 가져오기 - uuid

>>> import uuid
>>> a = uuid.getnode()
>>> mac = ':'.join(("%012X" % a)[i:i+2] for i in range(0, 12, 2))

사용할 일이 있을 때 퍼가면 좋을 거 같다.