BASH IP Address Check - macos

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.

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.

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!

Related

Rejecting inputs that include WWW. in bash

I am trying to block inputs of domains without www. in regex Bash.
Was using : \b(?:(?!www.)\w)+\b
Update:
Was able to resolve this issue by using the suggested expression.
Successfully Implemented As
while [[ ! $domain =~ www.*[.]([^\s]+) ]]; do
echo "Enter domain without www."
read domain
echo
done
You can determinate domains with "www." and then block them
With http/https:
http[s]*:\/\/www.*[.]([^\s]+)
without http/https:
www.*[.]([^\s]+)

how to sum ip addresses

I'm creating a *.deb package that transform your wireless card into an hotspot.
I'm stuck at the configurations:
I have to write a postinst file in which I ask to the user what ip address he likes for his hotspot and then use it to generate the range & the subnet addresses for the isc-dhcp-server.
Something like that:
10.10.0.01 + 0.0.0.9 = 10.10.0.10
I know how to assign strings and numbers to variables and how to ask to user his choosen IP, but how to modify a variable and assign the result to another one? expr thinks it's a floating number and won't work.
Hoping that everything it's clear enough,
waiting for a help,
thank you in advance
Avoid leading zeros.
IFS="." read -a a <<< 10.10.0.1
IFS="." read -a b <<< 0.0.0.9
s="$[a[0]+b[0]].$[a[1]+b[1]].$[a[2]+b[2]].$[a[3]+b[3]]"
echo $s
Output:
10.10.0.10
Ok, I found a workaround method:
when I ask to the user its choosen ip I use these:
IFS="." read -r a b c d
choosenip="$a.$b.$c.$d"
subnetip="$a.$b.$c.0"
rangeipmin="$a.$b.$c.20"
rangeipmax="$a.$b.$c.30"
IFS change the default "space" or "tab" to whatever you want.
So when I have to put these in the dhcpd.conf with "echo", I just have to call the variables.
If you have more elegant ways to do that, you're welcome.
Thank you

Multiple conditions in Bash for outputting error

My question is similar to ones asked multiple times before. I have a script that checks multiple variables on a machine and logs that data. For instance, I'm checking Firewall and Encryption on the machine, and if one or both of them are off I need to echo exactly what is turned off. I'm looking at using something along the lines of this...
if [ $firewall -eq "Off" ] || [ $Encryption -eq "Off" ]; then
echo Please fix ****
else
echo "Everything is great"
fi
I'm having a problem of how parse out the data in the second line.
EDIT: I've gotten some great answers, but the thing I'm curious about is, how would I work it if I have a list of 5 things I'm checking on, and say 2 of them are not meeting the standard. I'd like to output only those that are not passing to the end user so they know what they need to fix?
So given the example above, let's say I'm testing for Firewall, Encryption, Patches, and Disk Space. If the user needs to fix Firewall and Encryption, I'd like to output only those two. If another user has issues with Disk Space, one one to them, and another user has everything okay, then a message that everything is fine.
EDIT 2:* I'm pulling the information I require, the only problem is I need to have one of two different pop-up windows. Either one that shows what exactly is wrong, and that could be any number of things, or one that shows that everything is working properly.
So far I've come up with the code below, but it's showing me two windows, one that shows the errors, and the other "Everything is great" pop-up in that order. Where am I going wrong?
for i in Software Firewall XProtect; do
if [[ "${!i}" == "Off" ]]; then
osascript -e 'tell app "System Events" to display dialog "Compliance Check results \r \r'$i' needs attention\r \rPress OK to continue."'
Elseif
osascript -e 'tell app "System Events" to display dialog "Compliance Check results \r \rEverything looks good. \r \rPress OK to continue."'
fi
done
Thank you in advance for all the help.
-eq is used for Integer comparison only.
Better to simplify your code like this:
if [ "$firewall" = "Off" ]; then
echo "firewall is Off"
elif [ "$Encryption" = "Off" ]; then
echo "Encryption is Off"
else
echo "Everything is great"
fi
EDIT: To check multiple variable you can use this for loop:
for i in A B C D; do
[[ "${!i}" == "Off" ]] && echo "$i is Off"
done
try this
if [[ ${firewall:-} = "Off" || ${Encryption:-} = "Off" ]]; then
echo Please fix ****
else
echo "Everything is great"
fi

How to parametrize verbosity of debug output (BASH)?

During the process of writing a script, I will use the command's output in varying ways, and to different degrees - in order to troubleshoot the task at hand.. For example, in this snippet, which reads an Application's icon resource and returns whether or not it has the typical .icns extension...
icns=`defaults read /$application/Contents/Info CFBundleIconFile`
if ! [[ $icns =~ ^(.*)(.icns)$ ]]; then
echo -e $icns "is NOT OK YOU IDIOT! **** You need to add .icns to "$icns"."
else
echo -e $icns "\t Homey, it's cool. That shits got its .icns, proper."
fi
Inevitably, as each bug is squashed, and the stdout starts relating more to the actual function vs. the debugging process, this feedback is usually either commented out, silenced, or deleted - for obvious reasons.
However, if one wanted to provide a simple option - either hardcoded, or passed as a parameter, to optionally show some, all, or none of "this kind" of message at runtime - what is the best way to provide that simple functionality? I am looking to basically duplicate the functionality of set -x but instead of a line-by rundown, it would only print the notifications that I had architected specificically.
It seems excessive to replace each and every echo with an if that checks for a debug=1|0, yet I've been unable to find a concise explanation of how to implement a getopts/getopt scheme (never can remember which one is the built-in), etc. in my own scripts. This little expression seemed promising, but there is very little documentation re: 2>$1 out there (although I'm sure this is key to this puzzle)
[ $DBG ] && DEBUG="" || DEBUG='</dev/null'
check_errs() {
# Parameter 1 is the return code Para. 2 is text to display on failure.
if [ "${1}" -ne "0" ]; then
echo "ERROR # ${1} : ${2}"
else
echo "SUCESSS "
fi }
Any concise and reusable tricks to this trade would be welcomed, and if I'm totally missing the boat, or if it was a snake, and it would be biting me - I apologize.
One easy trick is to simply replace your "logging" echo comamnd by a variable, i.e.
TRACE=:
if test "$1" = "-v"; then
TRACE=echo
shift
fi
$TRACE "You passed the -v option"
You can have any number of these for different types of messages if you wish so.
you may check a common open source trace library with support for bash.
http://sourceforge.net/projects/utalm/
https://github.com/ArnoCan/utalm
WKR
Arno-Can Uestuensoez

to which subnet IP address belongs?

I have to write a script in bash , perl or python.
I got file with three columns (for manually manage connect-proxy)
SUBNET/IP socks_port socks_ip
1.2.3.* 1080 9.8.7.6
1.1.* 1080 6.8.7.6
I want to know to which subnet belongs IP address,
for example:
$ my_script 1.1.1.2
this IP belongs to 1.1.* subnet so I want back second line.
BASH: quick and dirty, use cut, then grep over the file.
PYTHON: use ip.rsplit() and then line.split()[].startswith() iterating through the file.
PERL: no idea.
Cheers!
If the file is in the format given (i.e. using *), it'll be fairly easy to use bash pattern matching to compare this to the ip address. However, as #Mark Drago pointed out, this format anything except octet-boundary subnets, so if you need to support arbitrary subnet boundaries, you need a better format.
Assuming you are using the "1.2.*" format, this should work:
#!/bin/bash
ip="$1"
found_match=false
while read subnet socks_port socks_ip; do
if [[ "$ip" == $subnet ]]; then # this'll do glob-style pattern matching against $subnet
echo "subnet=$subnet, socks_port=$socks_port, socks_ip=$socks_port"
found_match=true
break # assuming you don't want to check for multiple matches
fi
done </path/to/subnet/file
if ! $found_match; then
echo "No match found in subnet file"
fi

Resources