Linux ifdata 命令:在不解析 ifconfig 输出的情况下查看网络接口信息

R在 shell 脚本中读取 IP 地址需要很多时间,并且各种 Linux 发行版将 IP 地址存储在不同的文本文件中。 所以我们大多数人最终都会编写 shell 管道/脚本来使用 ifconfig | 获取信息。 grep ‘inet 地址:’| grep -v ‘127.0.0.1’ | 切-d:-f2 | awk ‘{ print $1}’ 语法。 ifconfig+shell pipe hack 有一个替代方法——ifdata 命令。 这是一个鲜为人知的工具,可用于检查网络接口是否存在并查找有关您的接口的信息,例如 IP、网络掩码、MTU 等等。 无需编写 shell 管道并通过 ifconfig 或 ip 命令获取信息。 该命令被设计为易于被 shell 脚本使用。

如何安装 ifdata 命令?

只需在 shell 提示符下键入以下命令:
$ sudo apt-get install moreutils

或者
$ sudo yum install moreutils

例子

查看接口ppp0是否存在,输入:

ifdata -e ppp0 && echo "Found" || echo "Not found"

或者

ifdata -e ppp0 && echo "Found" || { echo "Not found, starting pppd..."; pppd call barISP; }

显示 eth0 配置:
$ ifdata -p eth0

示例输出:

192.168.1.5 255.255.255.0 192.168.1.255 1500

获取接口的IPv4地址,输入:

#!/bin/bash
# my firewall script
# Get ip for eth0
_ip=$(ifdata -pa eth0)
_ipt=/sbin/iptables
 
## do something on $_ip ##
echo "Setting firewall for eth0 and ${_ip}..."

ifdata 命令支持的所有选项的完整摘要:

Usage: ifdata [options] iface
     -e   Reports interface existence via return code
     -p   Print out the whole config of iface
    -pe   Print out yes or no according to existence
    -pa   Print out the address
    -pn   Print netmask
    -pN   Print network address
    -pb   Print broadcast
    -pm   Print mtu
    -ph   Print out the hardware address
    -pf   Print flags
    -si   Print all statistics on input
   -sip   Print # of in packets
   -sib   Print # of in bytes
   -sie   Print # of in errors
   -sid   Print # of in drops
   -sif   Print # of in fifo overruns
   -sic   Print # of in compress
   -sim   Print # of in multicast
    -so   Print all statistics on output
   -sop   Print # of out packets
   -sob   Print # of out bytes
   -soe   Print # of out errors
   -sod   Print # of out drops
   -sof   Print # of out fifo overruns
   -sox   Print # of out collisions
   -soc   Print # of out carrier loss
   -som   Print # of out multicast
  -bips   Print # of incoming bytes per second
  -bops   Print # of outgoing bytes per second

我希望你也能用这个小小的。

相关互联网链接