【问题标题】:Get network interface information获取网络接口信息
【发布时间】:2017-01-06 21:19:48
【问题描述】:

我知道有 ifconfig 命令可以列出网络接口信息。 但我想按以下模式获取信息

Interface_Name IP_Address Net_Mask 状态(上/下)

例如

eth0 192.168.1.1 255.255.255.0 向下

我尝试了 ifconfig 和 grep 命令,但无法获得正确的模式。 还有其他命令或技巧可以做到这一点吗?

【问题讨论】:

    标签: linux ifconfig


    【解决方案1】:

    Python 很好 :D 但让我们看看 bash:

    Interfaces=`ifconfig -a \
        | grep -o -e "[a-z][a-z]*[0-9]*[ ]*Link" \
        | perl -pe "s|^([a-z]*[0-9]*)[ ]*Link|\1|"`
    
    for Interface in $Interfaces; do
        INET=`ifconfig $Interface | grep -o -e "inet addr:[^ ]*" | grep -o -e "[^:]*$"`
        MASK=`ifconfig $Interface | grep -o -e "Mask:[^ ]*"      | grep -o -e "[^:]*$"`
        STATUS="up"
        if [ "$INET" == "" ]; then
            INET="-"
            MASK="-"
            STATUS="down";
        fi
        printf "%-10s %-15s %-16s %-4s\n" "$Interface" "$INET" "$MASK" "$STATUS"
    done
    

    这很简单。

    这是在假设“ifconfig interface不显示互联网地址”意味着接口已关闭的情况下完成的。

    我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      ifconfig 有两种输出模式——默认的一种,它提供更多的输出,而简短的-s,它提供的输出更少(或者,更确切地说,从你的信息中挑选不同的信息位)我喜欢)。那么,如何在默认模式下使用 ifconfig 并在脚本中挑选您想要的特定信息(python、perl、ruby、awk、bash+sed+...,无论您的船是什么;-)。例如,使用 Python:

      import re
      import subprocess
      
      ifc = subprocess.Popen('ifconfig', stdout=subprocess.PIPE)
      res = []
      for x in ifc.stdout:
        if not x.strip():
          print ' '.join(res)
          del res[:]
        elif not res:
          res.append(re.match(r'\w+', x).group())
        else:
          mo = re.match(r'\s+inet addr:(\S+).*Mask:(\S+)', x)
          if mo:
            res.extend(mo.groups())
          elif re.match(r'\sUP\s', x):
            res.append('up')
          elif re.match(r'\sDOWN\s', x):
            res.append('down')
      
      if res: print ' '.join(res)
      

      并且输出应该是你想要的(我希望很容易翻译成我提到的任何其他语言)。

      【讨论】:

        【解决方案3】:

        您可能对ip 命令感兴趣。以下示例重点介绍以 CIDR 表示法输出的全球有效 IPv4 地址。

        # list interfaces that are up
        ip -family inet -oneline addr show scope global | awk '{ printf "%s %s up\n", $2, $4 }'
        
        # list interfaces that are down
        ip -family inet -oneline link show scope global | grep ' DOWN ' | sed 's/\://g' | awk '{ printf "%s none down\n", $2}'
        

        (请注意,示例中省略了所需的网络掩码表示。)

        由于ip 非常强大,您也许可以使用其他参数找到更简洁的解决方案。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-19
          • 1970-01-01
          • 2011-04-17
          • 2013-05-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多