gpt4 book ai didi

bash - 在 shell 脚本中如何验证给定主机名是否属于 localhostname 系列

转载 作者:行者123 更新时间:2023-11-29 09:32:09 26 4
gpt4 key购买 nike

在 shell 脚本中如何验证给定的主机名是否为 localhost

例如:-

localhost
127.0.0.1
myhostname.com
::1

都属于同一个机器名,有什么方法可以识别给定的主机名属于本地主机名系列

最佳答案

通常所有本地主机名都在/etc/hosts 文件中:

grep -c machine_name /etc/hosts

如果机器名称在本地主机中,上面的命令返回 1 或更大,否则为 0。

例如:

grep -c myhostname.com /etc/hosts
1

grep -c google.com /etc/hosts
0

不确定这是否正是您要找的,但我希望它能有所帮助。

注意部分匹配,例如,如果你在/etc/hosts 中有 'myhost' grep -c host 也会返回 1。在这种情况下,您需要使用正则表达式或使用 cut、awk 和类似工具解析/etc/hosts 文件。或者使用以下命令:

grep -c  '\bmachine name\b'

要跳过评论,请使用以下命令:

grep -v '^#.*' /etc/hosts | grep -c machine_name

完整的命令是

grep -v '^#.*' /etc/hosts | grep -c '\bmachine_name\b'

关于bash - 在 shell 脚本中如何验证给定主机名是否属于 localhostname 系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14338808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com