杂项4

来源:互联网 发布:表格不同行数据相加 编辑:程序博客网 时间:2024/06/06 02:23

11.grep获取主机名和IP地址
 方法一.从host文件获取
  get_host_info()
  { 
  HostName=`hostname`
  #过滤纯注释行(以#开头或者以空格+#开头的行),
  #然后过滤127.0.0.1,获取本机的ip地址
HostIP=`cat /etc/hosts|grep -v "^[ ]*\#" | grep -v 127.0.0.1 | grep $HostName | awk '{print $1}'`
  if [ $? -ne 0 ];then
  echo "Error! can't get Host IP"
  return  1
  fi 
   if [ $? –eq 0 ]; then
    return 0;
   else
    return 1;
 }

方法二.从ifconfig获取
  get_host_info()
   { 
    #得到ip地址所在行
 ip=`ifconfig -a | grep [1-9][0-9]\{0,2\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" | awk '{print $2}'`
    #提取ip地址
   ip=`echo $ip | awk '{print $2}'`
   is_ip_address $ip
   if [ $? –eq 0 ]; then
    return 0;
   else
    return 1;
  }
 注:is_ip_address函数见“六.13 确定字符串是否是ip地址”

原创粉丝点击