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

简介: 来源地址: http://www.linuxsir.org/bbs/showthread.php?t=21008如何用bash提取网卡ip地址?比如,我想显示如下的效果:You eth0's IP = [ 192.

来源地址: 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

 

目录
相关文章
|
监控 安全 Shell
防止员工泄密的措施:在Linux环境下使用Bash脚本实现日志监控
在Linux环境下,为防止员工泄密,本文提出使用Bash脚本进行日志监控。脚本会定期检查系统日志文件,搜索敏感关键词(如"password"、"confidential"、"secret"),并将匹配项记录到临时日志文件。当检测到可疑活动时,脚本通过curl自动将数据POST到公司内部网站进行分析处理,增强信息安全防护。
328 0
|
Linux Shell Windows
4:Bash shell命令-步入Linux的现代方法
4:Bash shell命令-步入Linux的现代方法
212 0
|
Ubuntu 安全 Linux
不用安装虚拟机,直接在Windows上面运行Linux Bash Shell,嗯!真香!!!
不用安装虚拟机,直接在Windows上面运行Linux Bash Shell,嗯!真香!!!
683 0
|
关系型数据库 MySQL Shell
【Linux命令】-bash: mysql: command not found
【Linux命令】-bash: mysql: command not found
211 0
|
存储 Shell Linux
Linux Bash 脚本中的 IFS 是什么?
【4月更文挑战第25天】
364 0
Linux Bash 脚本中的 IFS 是什么?
|
存储 Shell Linux
Linux|创建和使用 Bash 别名
Linux|创建和使用 Bash 别名
|
Java Shell Linux
【linux进程控制(三)】进程程序替换--如何自己实现一个bash解释器?
【linux进程控制(三)】进程程序替换--如何自己实现一个bash解释器?
|
Shell Linux
【Linux】Bash支持各种指令选项的原理:命令行参数
【Linux】Bash支持各种指令选项的原理:命令行参数
|
存储 Shell Linux
【攻防世界】unseping (反序列化与Linux bash shell)
【攻防世界】unseping (反序列化与Linux bash shell)
|
Linux Shell 开发工具
linux】-bash:vim:未找到命令
linux】-bash:vim:未找到命令
265 0

热门文章

最新文章