Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Linux下Shell脚本获取网络信息

在linux的网络编程中,经常需要用到网络信息如:ip、gateway、dns等。以下脚本实现了获取网络信息的功能,包括ip、broadcast、netmask、gateway以及dns的信息。
  1. #! /bin/sh

  2. default_route=$(ip route show)
  3. default_interface=$(echo $default_route | sed -e "s/^.*dev ([^ ]*).*$/1/" | head -n 1)
  4. address=$(ip addr show label $default_interface scope global | awk "$1 == "inet" { print $2,$4}")
  5.   
  6. #ip address
  7. ip=$(echo $address | awk "{print $1 }")
  8. ip=${ip%%/*}
  9.   
  10. #broadcast
  11. broadcast=$(echo $address | awk "{print $2 }")
  12.   
  13. #mask address
  14. mask=$(route -n |grep "U[ ]" | head -n 1 | awk "{print $3}")
  15.   
  16. #gateway address
  17. gateway=$(route -n | grep "UG[ ]" | awk "{print $2}")
  18.   
  19. #dns
  20. dns=$(cat /etc/resolv.conf | grep nameserver | awk "{print $2}")
  21.   
  22. echo ip:$ip,mask:$mask,broadcast:$broadcast,gateway:$gateway,dns:$dns