用shell脚本获取当前IP地址的方法,可用于Linux系统,freebad,以及solaris系统等。 ifconfig返回的信息中包括IP地址,但要在Shell中获取当前IP地址,则要麻烦一些。
获取方法
一、Linux:
LC_ALL=C ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | LC_ALL=C 英文输出
1,ifconfig 输出ip相关信息
# LC_ALL=C ifconfig
lo Link encap:Local Loopback
2,grep 'inet addr:' 截取包含ip的那两行
# LC_ALL=C ifconfig|grep "inet addr:"
inet addr:192.168.1.247 Bcast:0.0.0.0 Mask:255.255.255.0 inet addr:127.0.0.1 Mask:255.0.0.0
3,grep -v '127.0.0.1' 去掉本地指向的那行
# LC_ALL=C ifconfig|grep "inet addr:"|grep -v "127.0.0.1"
inet addr:192.168.1.247 Bcast:0.0.0.0 Mask:255.255.255.0
4,cut -d: -f2 -d: 以:分割字符串 -f2:取第二组数据
# LC_ALL=C ifconfig|grep "inet addr:"|grep -v "127.0.0.1"|cut -d: -f2
192.168.1.247 Bcast
5,awk '{ print $1}' $1 表示默认以空格分割的第一组 同理 $@表示第二组
# LC_ALL=C ifconfig|grep "inet addr:"|grep -v "127.0.0.1"|cut -d: -f2|awk '{print $1}'
192.168.1.247 # LC_ALL=C ifconfig|grep "inet addr:"|grep -v "127.0.0.1"|cut -d: -f2|awk '{print $2}' Bcast
二、FreeBSD/OpenBSD:
LC_ALL=C ifconfig | grep -E 'inet.[0-9]' | grep -v '127.0.0.1' |
awk '{ print $2}'
三、Solaris:
LC_ALL=C ifconfig -a | grep inet | grep -v '127.0.0.1' |
awk '{ print $2}' 三段代码的原理类似,都是先获取含有IP的行,再去掉含有127.0.0.1的行。最后获取IP所在的列。
Shell中获取IP地址
ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' |
cut -d: -f2 | awk '{ print $1}'
先获取含有IP的行,再去掉含有127.0.0.1的行。最后获取IP所在的列:
复制代码代码示例:
#!/bin/sh
# Shell script scripts to read ip address # Get OS name OS=`uname` IO="" # store IP case $OS in Linux) IP=`ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`;; FreeBSD|OpenBSD) IP=`ifconfig | grep -E 'inet.[0-9]' | grep -v '127.0.0.1' | awk '{ print $2}'` ;; SunOS) IP=`ifconfig -a | grep inet | grep -v '127.0.0.1' | awk '{ print $2} '` ;; *) IP="Unknown";; esac echo "$IP"
附2,
-v, –invert-match
Invert the sense of matching, to select non-matching lines. (-v is specified by POSIX.)
因此,可以使用grep -v来排除,观察这4行,以inet6开头的是不需要的,ip为127.0.0.1开头的也是不需要的,那命令就很简单了,首先取出带ip的这一行
复制代码代码示例:
/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6
得到的结果:
inet addr:192.168.123.5 Bcast:192.168.123.255 Mask:255.255.255.0
现在只需要取出ip,这个可以使用强大的awk就非常简单了,代码如下:
复制代码代码示例:
awk '{print $2}'
然后去掉前面的addr:
复制代码代码示例:
awk '{print $2}'|tr -d "addr:"
完整代码:
复制代码代码示例:
/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"
另外一些参考方法:
复制代码代码示例:
/sbin/ifconfig|sed -n ‘/inet addr/s/^[^:]*:\([0-9.]\{7,15\}\) .*/\1/p’
方法二: (需要已配置dns)
复制代码代码示例:
local_host=”`hostname –fqdn`”
local_ip=`host $local_host 2>/dev/null | awk ‘{print $NF}’`
方法三:(需要已配置dns)
复制代码代码示例:
local_host=”`hostname –fqdn`”
nslookup -sil $local_host 2>/dev/null | grep Address: | sed ’1d’ | sed ‘s/Address://g’ |