LoginSignup
2
5

More than 3 years have passed since last update.

ネットワークのすべてのアドレスを列挙する

Posted at

ネットワークのすべてのアドレスを列挙する。

自宅内のIoT機器をメンテナンスするのにarp -a コマンドだけでは、足りない。Windows 10とRaspberry Piで動作するスクリプトを作成した。

準備

sudo pip install kamene #python3 で動作するscapy

kamene (formerly known as "scapy for python3" or scapy3k)

discover.py
# -*- coding: utf-8 -*-
import logging,requests
logging.getLogger("kamene.runtime").setLevel(logging.ERROR)
from kamene.all import *
import netifaces
from netifaces import interfaces, ifaddresses, AF_INET
_ip=lambda ip:(int(ip.split(".")[0]),int(ip.split(".")[1]),int(ip.split(".")[2]),int(ip.split(".")[3]) )
'''
ネットワークに接続されている機器のアドレスの取得
'''
def discover():
    s,ip = ip_addr()
    n=[(x[1][ARP].psrc,x[1][ARP].hwsrc) for x in arping(ip, timeout=1, verbose=0)[0]]
    return '.'.join(map(str,s)),ip,(sorted(n,key=lambda ip:(int(ip[0].split(".")[0]),int(ip[0].split(".")[1]),int(ip[0].split(".")[2]),int(ip[0].split(".")[3]) )))
'''
ネットワークアドレスの取得
'''
def ip_addr():
    nx=[netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifaces.ifaddresses(iface)]
    nxx=nx[0] if nx[0]!="127.0.0.1" else nx[1]
    n=_ip(nxx)
    mask='.'.join(map(str,n[:3]))+".*" #ネットワーク検索用 マスク 例 192.168.1.*
    return n,mask
'''
Mac address to company
'''
def MacInfo(mac):
    r = requests.get('http://macvendors.co/api/%s'% mac)
    return  (r.json()['result'])['company']

if __name__ == '__main__':
    ip,mask,adresses=discover()
    print("My IP:%s"%ip)
    print("Mask :%s"%mask)
    for i,x in enumerate(adresses):
        print("%3s %-15s %-18s %s"%(i,x[0],x[1],MacInfo(x[1])))

結果

pi@raspberrypi:~/tools$ sudo python discover.py
My IP:192.168.1.10
Mask :192.168.1.*
  0 192.168.1.1     58:52:8a:3f:8a:21  Mitsubishi Electric Corporation
  1 192.168.1.90    b0:e8:92:10:3c:f6  SEIKO EPSON CORPORATION
  2 192.168.1.104   e4:e4:ab:58:7e:36  Apple, Inc.
  3 192.168.1.108   b8:27:eb:97:47:1a  Raspberry Pi Foundation
  4 192.168.1.111   b8:27:eb:97:47:1a  Raspberry Pi Foundation
  5 192.168.1.151   78:0f:77:17:5d:70  HangZhou Gubei Electronics Technology Co.,Ltd
  6 192.168.1.155   84:0d:8e:a7:d8:3a  Espressif Inc.
  7 192.168.1.158   b4:e6:2d:67:92:c2  Espressif Inc.
  8 192.168.1.199   00:04:13:21:11:fd  SNOM Technology AG
pi@raspberrypi:~/tools$ 
2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5