使用shell获取ip地址

linux wiki

s

 

ifconfig返回的信息中包括IP地址,但要在Shell中获取当前IP地址,则要麻烦一些

获取方法

由于不同系统中ifconfig返回信息的格式有一定差别,故分开讨论:[1]

Linux:

LC_ALL=C ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' |
cut -d: -f2 | awk '{ print $1}'

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所在的列

样例代码

下面是一则示例的代码[2]

#!/bin/sh
# Shell script scripts to read ip address
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project 
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
# 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"

代码出处

  1. ↑ http://www.cyberciti.biz/tips/read-unixlinux-system-ip-address-in-a-shell-script.html
  2. ↑ http://bash.cyberciti.biz/misc-shell/read-local-ip-address/
取自" http://www.linux-wiki.cn/index.php?title=Shell%E4%B8%AD%E8%8E%B7%E5%8F%96%E5%BD%93%E5%89%8DIP%E5%9C%B0%E5%9D%80&variant=zh-cn"

你可能感兴趣的:(SHELL)