通过主机名解析MAC地址

1 投票
2 回答
2810 浏览
提问于 2025-04-16 17:16

我在实习期间写了几个perl脚本,现在想让它们更好用。这些脚本需要输入一个mac地址,然后返回连接的交换机、速度等等信息。
我希望能用计算机的主机名来代替mac地址。那么,我该怎么把主机名转换成mac地址呢?
谢谢,再见。

编辑 -> 解决方案可以是:bash命令、perl模块或者其他类似强大的东西……

2 个回答

0

在UNIX系统中,ethers文件是用来把以太网地址和IP地址(或者主机名)对应起来的。如果你的/etc/ethers文件维护得很好,你可以在里面查找相关信息。

2

这有帮助吗?

[mpenning@Bucksnort ~]$ arp -an
? (4.121.8.3) at 08:00:27:f5:5b:6b [ether] on eth0
? (4.121.8.4) at 08:00:27:f5:5b:6b [ether] on eth0
? (4.121.8.1) at 00:1b:53:6b:c9:c4 [ether] on eth0
[mpenning@Bucksnort ~]$

在Python中...

#!/usr/bin/env python
import subprocess
import re

def parse_arpline(line, hosts):
    match = re.search(r'\((\S+?)\)\s+at\s+(\S+)', line)
    if match is not None:
        ipaddr = match.group(1)
        mac = match.group(2)
        hosts.append((ipaddr, mac))
    return hosts

SUBNET = '192.168.1.0/24'  # Insert your subnet here
subprocess.Popen([r"nmap","-sP", SUBNET],stdout=subprocess.PIPE).communicate()
p = subprocess.Popen([r"arp","-an"],stdout=subprocess.PIPE).communicate()[0].split('\n')
hosts = []
ii = 0
for line in p:
    hosts = parse_arpline(line, hosts)
    ii +=1
# Iterate and do something with the hosts list
print hosts

在Perl中...

my $SUBNET = '192.168.1.0/24';  # Insert your subnet here
`nmap -sP $SUBNET`;
my $p = `arp -an`;
for my $line (split('\n', $p)) {
    $line=~/\((\S+?)\)\s+at\s+(\S+)/;
    $ipaddr = $1;
    $mac = $2;
    # do something with with each mac and ip address
}

撰写回答