Python 取得 mac address 的方法

本篇介紹 Python 取得 mac address 的方法。

python3-get-mac-address.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import uuid

macaddr = uuid.UUID(int = uuid.getnode()).hex[-12:]
print(macaddr)

macaddr_list = []
for i in range(0,11,2):
print(macaddr[i:i+2])
macaddr_list.append(macaddr[i:i+2])
print(macaddr_list)
print(type(macaddr_list))

macaddr2 = ':'.join(macaddr_list)
print(macaddr2)

結果如下,

1
2
3
4
5
6
7
8
9
10
aa00112b3cd4
aa
00
11
2b
3c
d4
['aa', '00', '11', '2b', '3c', 'd4']
<class 'list'>
aa:00:11:2b:3c:d4

寫成函式的話,範例如下,

python3-get-mac-address2.py
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import uuid

def get_mac_address():
macaddr = uuid.UUID(int = uuid.getnode()).hex[-12:]
return ":".join([macaddr[i:i+2] for i in range(0,11,2)])

print(get_mac_address())

結果如下,

1
aa:00:11:2b:3c:d4

其它相關文章推薦
Python 新手入門教學懶人包
Python 讀取 txt 文字檔
Python 寫檔,寫入 txt 文字檔
Python 讀取 csv 檔案
Python 寫入 csv 檔案
Python 讀寫檔案
Python 產生 random 隨機不重複的數字 list
Python PyAutoGUI 使用教學
Python OpenCV resize 圖片縮放