sh脚本显示ip nei和路由器的mac地址

时间:2014-09-07 18:43:53

标签: shell networking

ip nei s的结果如下

fe80::a7a:4cff:fe9f:a03a     dev   br-lan    lladdr   08:7a:4c:9f:a0:3a STALE
fe80::ba8d:12ff:fe24:3076    dev   br-lan    lladdr   b8:8d:12:24:30:76 STALE
fe80::8ebe:beff:fede:afaf    dev   br-lan    lladdr   8c:be:be:de:af:af STALE
192.168.0.122                dev   br-lan    FAILED
192.168.0.20                 dev   br-lan    FAILED
192.168.0.1                  dev   br-lan    lladdr   00:00:00:00:02:00 STALE
192.168.0.21                 dev   br-lan    lladdr   b8:8d:12:24:30:76 REACHABLE

我想在每一行添加路由器的mac地址。如何编写sh脚本?(需要用路由器的真实mac地址替换{router's mac})

{router's mac}   fe80::a7a:4cff:fe9f:a03a     dev    br-lan   lladdr   08:7a:4c:9f:a0:3a   STALE
{router's mac}   fe80::ba8d:12ff:fe24:3076    dev    br-lan   lladdr   b8:8d:12:24:30:76   STALE
{router's mac}   fe80::8ebe:beff:fede:afaf    dev    br-lan   lladdr   8c:be:be:de:af:af   STALE
{router's mac}   192.168.0.122                dev    br-lan   FAILED
{router's mac}   192.168.0.20                 dev    br-lan   FAILED
{router's mac}   192.168.0.1                  dev    br-lan   lladdr   00:00:00:00:02:00   STALE
{router's mac}   192.168.0.21                 dev    br-lan   lladdr   b8:8d:12:24:30:76 REACHABLE

3 个答案:

答案 0 :(得分:0)

您可以使用awk:

ip neighbor list | awk '{ printf "%s\nrouter's mac ", $0 }'

答案 1 :(得分:0)

所以使用这个命令:

移动:

ip neighbor list | awk -F '[ ,]+' '{print $5" "$1" "$2" "$3" "$4" "$6}'

副本:

ip neighbor list | awk -F '[ ,]+' '{print $5" "$1" "$2" "$3" "$4" "$5" "$6}'

答案 2 :(得分:0)

尝试:

#!/bin/sh

ROUTER_IPADDR="$(ip route get 1.2.3.4 | awk '/ via / {print $3; exit;}')"
test -n "$ROUTER_IPADDR" || { echo "Cannot detect router IP"; exit 1; }

ROUTER_MACADDR="$(ip neigh show to $ROUTER_IPADDR | awk '/ lladdr / {print $5; exit;}')"
test -n "$ROUTER_MACADDR" || { echo "Cannot detect router MAC"; exit 1; }

ip neighbor list | sed "s,^,$ROUTER_MACADDR ,"