我是新来的,只是学习python。我需要帮助才能在Windows中使用python获取正确的网卡mac地址。我试图搜索,发现了这些:
如果我从命令提示符运行“ipconfig / all”,我会得到:
Windows-IP-Konfiguration
Hostname . . . . . . . . . . . . : DESKTOP-CIRBA63
Primäres DNS-Suffix . . . . . . . :
Knotentyp . . . . . . . . . . . . : Hybrid
IP-Routing aktiviert . . . . . . : Nein
WINS-Proxy aktiviert . . . . . . : Nein
Ethernet-Adapter Ethernet:
Verbindungsspezifisches DNS-Suffix:
Beschreibung. . . . . . . . . . . : Realtek PCIe FE Family Controller
Physische Adresse . . . . . . . . : 32-A5-2C-0B-14-D9
DHCP aktiviert. . . . . . . . . . : Nein
Autokonfiguration aktiviert . . . : Ja
IPv4-Adresse . . . . . . . . . . : 192.168.142.35(Bevorzugt)
Subnetzmaske . . . . . . . . . . : 255.255.255.0
Standardgateway . . . . . . . . . : 192.168.142.1
DNS-Server . . . . . . . . . . . : 8.8.8.8
8.8.4.4
NetBIOS über TCP/IP . . . . . . . : Deaktiviert
Ethernet-Adapter Ethernet 2:
Medienstatus. . . . . . . . . . . : Medium getrennt
Verbindungsspezifisches DNS-Suffix:
Beschreibung. . . . . . . . . . . : Norton Security Data Escort Adapter
Physische Adresse . . . . . . . . : 00-CE-35-1B-77-5A
DHCP aktiviert. . . . . . . . . . : Ja
Autokonfiguration aktiviert . . . : Ja
Tunneladapter isatap.{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}:
Medienstatus. . . . . . . . . . . : Medium getrennt
Verbindungsspezifisches DNS-Suffix:
Beschreibung. . . . . . . . . . . : Microsoft ISATAP Adapter
Physische Adresse . . . . . . . . : 00-00-00-00-00-00-00-A0
DHCP aktiviert. . . . . . . . . . : Nein
Autokonfiguration aktiviert . . . : Ja
我需要获取Realtek网卡的mac地址( 32-A5-2C-0B-14-D9 ),而不是诺顿或Windows隧道创建的网卡。
如果我使用Python,Python给了我另一个mac地址的结果:
"uuid.getnode() or "getmac"
我认为最好的方法是获得输出
"ipconfig /all"
,
在“Beschreibung”查看“Realtek”然后获取“Physische Adresse”信息以获取我的真实mac地址。
如何在Windows上的python中执行此操作?任何帮助表示赞赏。提前谢谢。
答案 0 :(得分:3)
下面的python3脚本是基于Stephen Rauch的(感谢wmic实用程序指针它真的很方便)
它只从计算机中检索 IP 和活动接口, 处理具有多个值的字段(在一个nic上有几个ips / mask或网关),从ip / mask创建IPv4Iinterface or v6 python objects,并输出一个每个nic有一个dict的列表。
#python3
from subprocess import check_output
from xml.etree.ElementTree import fromstring
from ipaddress import IPv4Interface, IPv6Interface
def getNics() :
cmd = 'wmic.exe nicconfig where "IPEnabled = True" get ipaddress,MACAddress,IPSubnet,DNSHostName,Caption,DefaultIPGateway /format:rawxml'
xml_text = check_output(cmd, creationflags=8)
xml_root = fromstring(xml_text)
nics = []
keyslookup = {
'DNSHostName' : 'hostname',
'IPAddress' : 'ip',
'IPSubnet' : '_mask',
'Caption' : 'hardware',
'MACAddress' : 'mac',
'DefaultIPGateway' : 'gateway',
}
for nic in xml_root.findall("./RESULTS/CIM/INSTANCE") :
# parse and store nic info
n = {
'hostname':'',
'ip':[],
'_mask':[],
'hardware':'',
'mac':'',
'gateway':[],
}
for prop in nic :
name = keyslookup[prop.attrib['NAME']]
if prop.tag == 'PROPERTY':
if len(prop):
for v in prop:
n[name] = v.text
elif prop.tag == 'PROPERTY.ARRAY':
for v in prop.findall("./VALUE.ARRAY/VALUE") :
n[name].append(v.text)
nics.append(n)
# creates python ipaddress objects from ips and masks
for i in range(len(n['ip'])) :
arg = '%s/%s'%(n['ip'][i],n['_mask'][i])
if ':' in n['ip'][i] : n['ip'][i] = IPv6Interface(arg)
else : n['ip'][i] = IPv4Interface(arg)
del n['_mask']
return nics
if __name__ == '__main__':
nics = getNics()
for nic in nics :
for k,v in nic.items() :
print('%s : %s'%(k,v))
print()
导入它或从cmd提示符中使用它:
python.exe getnics.py
将输出如下内容:
hardware : [00000000] Intel(R) Centrino(R) Wireless-N 2230 Driver
gateway : ['192.168.0.254']
ip : [IPv4Interface('192.168.0.40/24'), IPv6Interface('fe80::7403:9e12:f7db:60c/64')]
mac : xx:xx:xx:xx:xx:xx
hostname : mixer
hardware : [00000002] Killer E2200 Gigabit Ethernet Controller
gateway : ['192.168.0.254']
ip : [IPv4Interface('192.168.0.28/24')]
mac : xx:xx:xx:xx:xx:xx
hostname : mixer
用windows10测试。 我对mac地址字段有一些疑问,例如VM或欺骗情况,似乎wmic只返回一个字符串,而不是数组。
答案 1 :(得分:2)
您可以使用XML格式的wmic检索Windows界面信息,然后将xml转换为dict。从生成的词典中,您可以收集所有需要的信息:
import UIKit
import CoreMotion
class ViewController: UIViewController
{
let manager=CMMotionManager()
var accelerationX: Double=0.0
var accelerationY: Double=0.0
var accelerationZ: Double=0.0
@IBOutlet weak var valueLabelX: UILabel!
@IBOutlet weak var valueLabelY: UILabel!
@IBOutlet weak var valueLabelZ: UILabel!
override func viewDidLoad()
{
super.viewDidLoad()
if manager.isAccelerometerAvailable
{
manager.accelerometerUpdateInterval=0.1
let queue=OperationQueue.main
manager.startAccelerometerUpdates(to: queue, withHandler: { [weak self] (data, error) in
if let acceleration=data?.acceleration
{
self?.outputAccelerationData(data: acceleration)
}
})
}
else
{
print("Error: Accelerometer not available on this device")
}
}
func outputAccelerationData(data:CMAcceleration)
{
self.accelerationX=data.x
self.accelerationY=data.y
self.accelerationZ=data.z
valueLabelX.text=String(format: "%.2f", self.accelerationX)
valueLabelY.text=String(format: "%.2f", self.accelerationY)
valueLabelZ.text=String(format: "%.2f", self.accelerationZ)
}
}
此函数将返回一个dicts列表,可以从生成的dicts中返回所需的信息:
def get_interfaces_with_mac_addresses(interface_name_substring=''):
import subprocess
import xml.etree.ElementTree
cmd = 'wmic.exe nic'
if interface_name_substring:
cmd += ' where "name like \'%%%s%%\'" ' % interface_name_substring
cmd += ' get /format:rawxml'
DETACHED_PROCESS = 8
xml_text = subprocess.check_output(cmd, creationflags=DETACHED_PROCESS)
# convert xml text to xml structure
xml_root = xml.etree.ElementTree.fromstring(xml_text)
xml_types = dict(
datetime=str,
boolean=bool,
uint16=int,
uint32=int,
uint64=int,
string=str,
)
def xml_to_dict(xml_node):
""" Convert the xml returned from wmic to a dict """
dict_ = {}
for child in xml_node:
name = child.attrib['NAME']
xml_type = xml_types[child.attrib['TYPE']]
if child.tag == 'PROPERTY':
if len(child):
for value in child:
dict_[name] = xml_type(value.text)
elif child.tag == 'PROPERTY.ARRAY':
if len(child):
assert False, "This case is not dealt with"
else:
assert False, "This case is not dealt with"
return dict_
# convert the xml into a list of dict for each interface
interfaces = [xml_to_dict(x)
for x in xml_root.findall("./RESULTS/CIM/INSTANCE")]
# get only the interfaces which have a mac address
interfaces_with_mac = [
intf for intf in interfaces if intf.get('MACAddress')]
return interfaces_with_mac