linux - 如何使用 bash 获取服务器的 IP 地址

标签 linux bash shell awk grep

目标: 从服务器中提取 IP 地址。然而,问题在于专用和 VPS 有很大不同。提取、检查并打印 IP 地址的最佳或最理想方式是什么?

我想我可以用以下内容进行检查?

root@host]# /sbin/ifconfig venet0:0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
IP IS HERE
root@host]# /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
eth0: error fetching interface information: Device not found

最佳答案

要获取服务器的 IP 地址(无论它是否是 VPS),您可以执行以下操作:

#!/bin/bash

a="`netstat -i | cut -d' ' -f1 | grep eth0`";
b="`netstat -i | cut -d' ' -f1 | grep venet0:0`";

if [ "$a" == "eth0" ]; then
  echo "eth0 found"
  ip="`/sbin/ifconfig eth0 | awk -F':| +' '/inet addr/{print $4}'`";
elif [ "$b" == "venet0:0" ]; then
  echo "venet found"
  ip="`/sbin/ifconfig venet0:0 | awk -F':| +' '/inet addr/{print $4}'`"; 
fi

echo $ip;

希望这有帮助。

jwpat7致敬提供比 grep、cut、awk 更简洁的 awk 命令。

关于linux - 如何使用 bash 获取服务器的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12788607/

相关文章:

linux - 如何做一个 if 语句 bash linux

javascript - 如何从命令行与社交网站交互(自动 YouTube 发布、查找新视频的标题等)

python - os.system(cmd) 与终端中的 cmd 不同

python - 关于将shell命令插入python

linux - 请帮忙为下面的场景编写unix脚本

linux - linux下如何使用sed命令替换字符串?

linux - CentOS 7 上的固件同步安装

linux - 从变量更新 pom 文件的 Shell 命令

linux - 如何编辑段落中的设置?

linux - shell 脚本错误