arpy.py 1.99 KB
Newer Older
1 2 3 4
#! /usr/bin/env python
from scapy.all import sendp, Ether, ARP
import argparse
import logging
Sigmund Augdal's avatar
Sigmund Augdal committed
5
from nova_router import parse_ip, format_ip, setupLogfile
6 7 8 9 10 11 12 13
from pyroute2.netlink.iproute import IPRoute

DESCRIPTION = "Send unsolicited arp packages"
BROADCAST_MAC = "ff:ff:ff:ff:ff:ff"


def parse_args():
    parser = argparse.ArgumentParser(description=DESCRIPTION)
Sigmund Augdal's avatar
Sigmund Augdal committed
14
    parser.add_argument('--logfile', help="send output to logfile")
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
    parser.add_argument('--interface', default="eth0",
                        help="Interface to send on")
    parser.add_argument('--vip1')
    parser.add_argument('--vip2')
    parser.add_argument('--vip-up')
    parser.add_argument('first_address', help="Address range to claim")
    parser.add_argument('last_address', help="Address range to claim")

    return parser.parse_args()


def mymac(interface):
    return open("/sys/class/net/{}/address".format(interface)).read().strip()


def do_send(mymac, address, interface):
    pkg = Ether(src=mymac, dst=BROADCAST_MAC) / ARP(pdst=address, op=1, psrc=address, hwdst=BROADCAST_MAC, hwsrc=mymac)
    logging.info("Sending packet %s to interface %s", repr(pkg), interface)
33
    sendp(pkg, iface=interface)
34 35 36 37 38 39 40 41 42 43 44 45 46 47


def has_address(address):
    ir = IPRoute()
    for event in ir.get_addr():
        if event['event'] == 'RTM_NEWADDR':
            for (key, value) in event['attrs']:
                if key == 'IFA_ADDRESS' and value == address:
                    return True
    return False


def main():
    args = parse_args()
Sigmund Augdal's avatar
Sigmund Augdal committed
48 49 50 51
    if args.logfile:
        setupLogfile(args.logfile)
    else:
        logging.basicConfig(level=logging.DEBUG)
52 53 54 55 56 57 58 59
    mac = mymac(args.interface)
    do_send(mac, args.vip_up, args.interface)
    if has_address(args.vip1) and has_address(args.vip2):
        for address in range(parse_ip(args.first_address), parse_ip(args.last_address) + 1):
            do_send(mac, format_ip(address), args.interface)


if __name__ == '__main__':
Sigmund Augdal's avatar
Sigmund Augdal committed
60 61 62 63
    try:
        main()
    except Exception:
        logging.exception("Unhandled exception")