简体   繁体   English

BASH IP地址检查

[英]BASH IP Address Check

I am working on a BASH shell script where I need to be able to check and see if the IP address returned from: 我正在使用BASH Shell脚本,需要在其中检查并查看IP地址是否从以下地址返回:

dig $HOSTNAME +short

is within a particular subnet or not. 是否在特定子网内。 For example, if part of 192.168.10.x or 10.130.10.x then do z else do y. 例如,如果192.168.10.x或10.130.10.x的一部分,则执行z,否则执行y。

I am not sure how to manipulate or check the IP address after I have it stored in a variable so that I can build out the logical test described above. 我不确定将IP地址存储在变量中后如何操作或检查IP地址,从而无法构建上述逻辑测试。

If your subnets are full class C then you can just do a substring check: 如果您的子网是完整的C类,那么您可以进行子字符串检查:

if [ ${IP#192.168.10.*} == ${IP} -a ${IP#10.130.10.*} == ${IP} ]
then
    echo "not in either subnet"
else
    echo "in one of the subnets"
fi

Edit: Note, this of course doesn't validate that the IPs are valid, but it alleviates the need for external tools. 编辑:请注意,这当然不会验证IP是否有效,但是可以减轻对外部工具的需求。

I ended up using the following code to make it work: 我最终使用以下代码使其工作:

if [[ "$IP" == *10.130.10.* || "$IP" == *192.168.10.* ]]; then
   mount code goes here
fi

Thanks for everyone's help and explaining things to me to allow me to further learn about scripting. 感谢大家的帮助,并向我解释了所有内容,以便我进一步了解脚本。 It is really appreciated! 真的很感激!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM