如何用bash提取网卡ip地址?比如,我想显示如下的效果:
<code>You eth0's IP = [ 192.168.0.1 ]</code>
<code>[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</code>
<code>[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]</code>
这个原来就是取ppp0的ip用的,一样可以获取ppp0的IP地址,当然如果你要的就是P-t-P的地址就要改了。因为我需要的正好是P-t-P地址,所以将第一个cut中的2修改为3,即可以得到PPP网关地址:
<code>[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]</code>
<code>再给几种方法,老外网站上看到的 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的</code>
接下来还有更多的方法,列举一些如下:
<code>ifconfig eth0|sed -ne 's/^.*addr:/([0-9.]*/).*$//1/p'</code>
<code>echo $(ifconfig eth0|awk '/inet/ {split ($2,x,":");print x[2]}')</code>
<code>/sbin/ip a|awk '/ppp0$/{print $2}'</code>
<code>for int in $(cat /proc/net/dev | awk -F: '/:/{print $1}'); do /sbin/ifconfig $int|awk '/inet addr/{print $2}'|tr -d 'addr:' done</code>
<code>ifconfig eth0 | sed -n 's/^ *.*addr:/([0-9.]*/) .*$//1/p' ifconfig eth0| grep addr: |cut -c21-33</code>