BASH IP Address Check

放肆的年华 提交于 2020-01-25 20:54:12

问题


I am working on a BASH shell script where I need to be able to check and see if the IP address returned from:

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.

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.


回答1:


If your subnets are full class C then you can just do a substring check:

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.




回答2:


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!



来源:https://stackoverflow.com/questions/7970251/bash-ip-address-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!