如何用bash提取网卡ip地址?

来源地址: http://www.linuxsir.org/bbs/showthread.php?t=21008

如何用bash提取网卡ip地址?比如,我想显示如下的效果:

You eth0's IP = [ 192.168.0.1 ]

网友 Pye给出的方法如下,在CentOS 5下测试可以得到正确的结果:
[root@host ~]# ifconfig | sed -ne 's/ *inet addr:/([0-9]/{1,3/}/.[0-9]/{1,3/}/.[0-9]/{1,3/}/.[0-9]/{1,3/}/) *B.*/Your IP is:/1/p'
Your IP is:10.0.0.66
Your IP is:192.168.120.66

网友 X11给出了另一种方法,在CentOS 5下测试也可以得到正确的结果:
[root@host ~]# echo your ip is [`ifconfig eth0 | grep inet | cut -d : -f 2 | cut -d " " -f 1`]
your ip is [10.0.0.66]

这个原来就是取ppp0的ip用的,一样可以获取ppp0的IP地址,当然如果你要的就是P-t-P的地址就要改了。因为我需要的正好是P-t-P地址,所以将第一个cut中的2修改为3,即可以得到PPP网关地址:
[root@host ~]# echo your PPP gateway is [`ifconfig ppp0 | grep inet | cut -d : -f 3 | cut -d " " -f 1`]
your PPP gateway is [125.34.40.1]

后面网友 n0fe@r又给出了更多的方法,但是我没有测试:
再给几种方法,老外网站上看到的
IPDIN1="$(/sbin/ifconfig |awk -F'[: ]+' '/inet addr:/ {print $4}' | egrep -v '(^127/.|^192/.168)')"
IPDIN2="$(/sbin/ifconfig | grep inet | grep -v 192.168 | grep -v 127 | awk '{print $2}' | cut -f 2 -d ':')"
IPDIN3="$(ifconfig ppp0 | grep inet | tac -s addr: | fmt -15 | grep ^[123456789])"
IPDIN4="$(ifconfig ppp0 | sed -e '/inet/!d' -e 's/.*addr://' -e 's/[ ].*//')"
取ppp0的ip的,你也可以改造成取ethn的,4种方法最后都是得到的ip,我用来写iptable firewall script的

接下来还有更多的方法,列举一些如下:
ifconfig eth0|sed -ne 's/^.*addr:/([0-9.]*/).*$//1/p'

echo $(ifconfig eth0|awk '/inet/ {split ($2,x,":");print x[2]}')

/sbin/ip a|awk '/ppp0$/{print $2}'

for int in $(cat /proc/net/dev | awk -F: '/:/{print $1}'); do
        /sbin/ifconfig $int|awk '/inet addr/{print $2}'|tr -d 'addr:'
done

ifconfig eth0 | sed -n 's/^ *.*addr:/([0-9.]*/) .*$//1/p'
ifconfig eth0| grep addr: |cut -c21-33

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值