BASH IP Address Check

2019-08-17 06:41发布

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.

2条回答
我想做一个坏孩纸
2楼-- · 2019-08-17 07:40

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.

查看更多
\"骚年 ilove
3楼-- · 2019-08-17 07:42

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!

查看更多
登录 后发表回答