按主机名解析mac地址

时间:2011-05-09 12:20:06

标签: python perl ip mac-address hostname

我在实习期间写了几个perl脚本,我想简化它们的使用。脚本在arg中输入一个mac地址,并返回连接的交换机,速度等等。 我想给出一个计算机的主机名,而不是给出一个mac地址。那么,如何将主机名解析为mac地址?
谢谢再见。

编辑 - >解决方案可能是:bash命令或perl模块或类似的强大功能......

2 个答案:

答案 0 :(得分: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

in 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
}

答案 1 :(得分:0)

UNIX系统上的ethers文件将以太网地址映射到IP号码(或主机名)。如果您的/etc/ethers得到妥善维护,您可以在那里查找。